当前位置: 首页 > 面试题库 >

通过关键竞标进行JLabel移动

白才捷
2023-03-14
问题内容

我有个简短的脚本,人们不断告诉我,我需要使用Key绑定来移动Jlabel,但我不知道该怎么做。没有人对如何以不使用键侦听器的方式实现键绑定有任何想法,或者如果添加按钮会出现问题?

import java.awt.BorderLayout;
import java.awt.EventQueue;

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.KeyStroke;
import javax.swing.border.EmptyBorder;
import java.awt.CardLayout;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.ActionEvent;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.SwingConstants;
import java.awt.Color;
import java.awt.Font;

public class Screen extends JFrame {

    private JPanel contentPane;
    int x,y;

    /**
     * Launch the application.
 */
public static void main(String[] args) {
    EventQueue.invokeLater(new Runnable() {
        public void run() {
            try {
                Screen frame = new Screen();
                frame.setVisible(true);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    });
}

/**
 * Create the frame.
 */
public Screen() {
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    setBounds(100, 100, 450, 300);
    contentPane = new JPanel();
    contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
    setContentPane(contentPane);
    contentPane.setLayout(new CardLayout(0, 0));

    JPanel panel = new JPanel();
    contentPane.add(panel, "p1");
    panel.setLayout(null);

    JButton btnPlay = new JButton("Play");
    btnPlay.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent arg0) {
            CardLayout c =(CardLayout)(contentPane.getLayout());
            c.show(contentPane, "p2");
        }
    });
    btnPlay.setBounds(185, 164, 53, 23);
    panel.add(btnPlay);

    JLabel lblGame = new JLabel("Game");
    lblGame.setHorizontalAlignment(SwingConstants.CENTER);
    lblGame.setBounds(189, 28, 46, 14);
    panel.add(lblGame);

    JPanel panel_1 = new JPanel();
    contentPane.add(panel_1, "p2");
    panel_1.setLayout(null);

    JLabel player = new JLabel("P");
    player.setHorizontalAlignment(SwingConstants.CENTER);
    player.setFont(new Font("Tahoma", Font.BOLD, 27));
    player.setForeground(Color.BLACK);
    player.setBackground(Color.BLACK);
    player.setBounds(x, y, 51, 40);
        panel_1.add(player);
}
}

问题答案:

与大多数事情一样,开始看看教程“
如何使用键绑定”,几乎所有答案都将基于这些内容。

您可以做这样简单的事情…

import com.sun.glass.events.KeyEvent;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import javax.swing.AbstractAction;
import javax.swing.ActionMap;
import javax.swing.InputMap;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.KeyStroke;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;

public class Test {

    public static void main(String[] args) {
        new Test();
    }

    public Test() {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
                    ex.printStackTrace();
                }

                JFrame frame = new JFrame("Testing");
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.add(new TestPane());
                frame.pack();
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
            }
        });
    }

    public interface Movable {
        public void changeLocation(int xDelta, int yDelta);
    }

    public class TestPane extends JPanel implements Movable {

        private JLabel player;

        public TestPane() {
            setLayout(null);
            player = new JLabel("X");
            player.setSize(player.getPreferredSize());
            add(player);

            setupKeyBindings();
        }

        @Override
        public Dimension getPreferredSize() {
            return new Dimension(200, 200);
        }

        protected void setupKeyBindings() {
            InputMap im = getInputMap(WHEN_IN_FOCUSED_WINDOW);
            ActionMap am = getActionMap();

            im.put(KeyStroke.getKeyStroke(KeyEvent.VK_W, 0), "up");
            im.put(KeyStroke.getKeyStroke(KeyEvent.VK_S, 0), "down");
            im.put(KeyStroke.getKeyStroke(KeyEvent.VK_A, 0), "left");
            im.put(KeyStroke.getKeyStroke(KeyEvent.VK_D, 0), "right");

            int xDelta = player.getWidth();
            int yDelta = player.getHeight();

            am.put("up", new MoveAction(this, 0, -yDelta));
            am.put("down", new MoveAction(this, 0, yDelta));
            am.put("left", new MoveAction(this, -xDelta, 0));
            am.put("right", new MoveAction(this, xDelta, 0));
        }

        @Override
        public void changeLocation(int xDelta, int yDelta) {
            int xPos = player.getX() + xDelta;
            int yPos = player.getY() + yDelta;
            if (xPos + player.getWidth() > getWidth()) {
                xPos = getWidth() - player.getWidth();
            } else if (xPos < 0) {
                xPos = 0;
            }
            if (yPos + player.getHeight() > getHeight()) {
                yPos = getHeight() - player.getHeight();
            } else if (xPos < 0) {
                yPos = 0;
            }
            player.setLocation(xPos, yPos);
        }

    }

    public class MoveAction extends AbstractAction{
        private Movable movable;
        private int xDelta;
        private int yDelta;

        public MoveAction(Movable movable, int xDelta, int yDelta) {
            this.movable = movable;
            this.xDelta = xDelta;
            this.yDelta = yDelta;
        }

        @Override
        public void actionPerformed(ActionEvent e) {
            movable.changeLocation(xDelta, yDelta);
        }

    }

}

正如我反复告诉您或您的同班同学一样,您不应该以这种方式使用组件。相反,您应该遵循自定义的绘画路线,从长远来看,它将为您提供更大的灵活性和更少的问题。

import com.sun.glass.events.KeyEvent;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.FontMetrics;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Rectangle;
import java.awt.event.ActionEvent;
import javax.swing.AbstractAction;
import javax.swing.ActionMap;
import javax.swing.InputMap;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.KeyStroke;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;

public class Test {

    public static void main(String[] args) {
        new Test();
    }

    public Test() {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
                    ex.printStackTrace();
                }

                JFrame frame = new JFrame("Testing");
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.add(new TestPane());
                frame.pack();
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
            }
        });
    }

    public interface Movable {

        public void changeLocation(int xDelta, int yDelta);
    }

    public class TestPane extends JPanel implements Movable {

        private Rectangle player;

        public TestPane() {
            String text = "X";
            FontMetrics fm = getFontMetrics(getFont());
            int width = fm.stringWidth(text);
            int height = fm.getHeight();

            player = new Rectangle(0, 0, width, height);

            setupKeyBindings();
        }

        @Override
        public Dimension getPreferredSize() {
            return new Dimension(200, 200);
        }

        protected void setupKeyBindings() {
            InputMap im = getInputMap(WHEN_IN_FOCUSED_WINDOW);
            ActionMap am = getActionMap();

            im.put(KeyStroke.getKeyStroke(KeyEvent.VK_W, 0), "up");
            im.put(KeyStroke.getKeyStroke(KeyEvent.VK_S, 0), "down");
            im.put(KeyStroke.getKeyStroke(KeyEvent.VK_A, 0), "left");
            im.put(KeyStroke.getKeyStroke(KeyEvent.VK_D, 0), "right");

            int xDelta = player.width;
            int yDelta = player.height;

            am.put("up", new MoveAction(this, 0, -yDelta));
            am.put("down", new MoveAction(this, 0, yDelta));
            am.put("left", new MoveAction(this, -xDelta, 0));
            am.put("right", new MoveAction(this, xDelta, 0));
        }

        @Override
        public void changeLocation(int xDelta, int yDelta) {
            int xPos = player.x + xDelta;
            int yPos = player.y + yDelta;
            if (xPos + player.width > getWidth()) {
                xPos = getWidth() - player.width;
            } else if (xPos < 0) {
                xPos = 0;
            }
            if (yPos + player.height > getHeight()) {
                yPos = getHeight() - player.height;
            } else if (xPos < 0) {
                yPos = 0;
            }
            player.setLocation(xPos, yPos);
            repaint();
        }

        @Override
        protected void paintComponent(Graphics g) {
            super.paintComponent(g);
            Graphics2D g2d = (Graphics2D) g.create();
            g2d.setColor(Color.RED);
            g2d.draw(player);
            FontMetrics fm = g2d.getFontMetrics();
            g2d.drawString("X", player.x, player.y + fm.getAscent());
            g2d.dispose();
        }

    }

    public class MoveAction extends AbstractAction {

        private Movable movable;
        private int xDelta;
        private int yDelta;

        public MoveAction(Movable movable, int xDelta, int yDelta) {
            this.movable = movable;
            this.xDelta = xDelta;
            this.yDelta = yDelta;
        }

        @Override
        public void actionPerformed(ActionEvent e) {
            movable.changeLocation(xDelta, yDelta);
        }

    }

}

您还应该适当地使用布局管理器。这些可以保护您的头发和时间。

有关更多详细信息,请参见在容器中布置组件



 类似资料:
  • 我试图遍历一个JList,其中每个项目都包含:JGroup-JLabel 目前我拥有的是: 我得到的结果是: Item=javax。摆动JPanel[,0,0,0x0,无效,layout=java.awt.FlowLayout,alignmentX=0.0,alignmentY=0.0,border=,flags=9,maximumSize=,minimumSize=,preferredSize=

  • 所以我手头有一个非常奇怪的问题,数小时的搜索没有提供任何信息。 我有一个包含uitextfield的uiview。现在,该视图最初位于可见屏幕之外,坐标为x=-500,y=-500。 然而,在响应按钮按下此视图动画和移动到屏幕的中心。 现在,每当我点击作为此视图子视图的uitextfield时。此视图会在屏幕外移动回其原始坐标。 我已经疯狂地检查了我的代码,一旦它进入,就没有任何东西会再次将视图移

  • 我有表,和,一个用户有很多帖子,每个帖子有很多评论(在评论表中),还有一个用户有很多评论,但不完全需要匿名用户(在评论表中),下面的代码为每个帖子播种一些评论,但user_id从不由评论的所有者填写。我希望评论有相关的user_id注入数组外面

  • 问题内容: 故事: 像Google ReCaptcha一样,解决验证码的方法之一就是尝试 模仿人的鼠标动作 :移动,悬停和点击。 一些用户报告说,随着B样条曲线的作用而使鼠标移动。 问题: 如何通过selenium将鼠标移动到遵循B样条轨迹的特定元素上? 请注意,常规会直接且太快地“跳转”到元素。我的理解是,这是放慢移动速度的问题,它遵循B样条轨迹的数学模型从点到点平滑地“跳跃”。 我们正在使用量

  • 我试着用Java写一个包含图像的标签每秒钟都在移动的程序,但不幸的是代码没有运行,尽管它包含零错误。有没有人知道发生了什么。代码如下: 拜托,有谁能帮我。

  • 问题内容: 我将Ebean与Play 2 Framework结合使用,并得到了两种模型:用户模型和书本模型。用户模型与书籍模型以一对多关系连接。因此,每个用户可以拥有很多书,甚至根本没有书。书籍模型本身也具有属性。现在,我想在用户模型中创建一个查询,该查询仅返回具有某些属性书的用户。例如:一个属性可能是条件,例如new或used。现在,给我所有拥有新状态书籍的用户。是否可以使用Ebean方法创建这