【问题标题】:Using KeyListener on a JFrame to move a component在 JFrame 上使用 KeyListener 来移动组件
【发布时间】:2014-09-29 06:49:52
【问题描述】:

所以我想将字符串移向用户推动的方向,但它不起作用。它与 mouselistener 一起工作,所以我认为这已经足够了。我应该将侦听器添加到其他东西吗?

public class Snake extends JComponent implements KeyListener{

    private int x;
    private int y;
    private String s;

    public Snake(String s, int x, int y){
        this.s = s;
        this.x = x;
        this.y = y;
        addKeyListener(this);
    }

    @Override
    protected void paintComponent(Graphics g) {
        g.drawString(s, x, y);
    }


    @Override
    public void keyTyped(KeyEvent e) {

    }

    @Override
    public void keyPressed(KeyEvent e) {
        int code = e.getKeyCode();
        switch(code) {
            case KeyEvent.VK_UP:
                y-=15;
            case KeyEvent.VK_DOWN:
                y+=15;
            case KeyEvent.VK_RIGHT:
                x+=15;
            case KeyEvent.VK_LEFT:
                x-=15;
        }
        repaint();
    }

    @Override
    public void keyReleased(KeyEvent e) {

    }
}

public class Game {

    public static void main(String[] args){
        JFrame frame = new JFrame("Up Up And Away!");
        JComponent star = new Snake("*", 250, 100);
        frame.add(star);
        frame.setSize(500, 300);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setVisible(true);
    }
}

【问题讨论】:

标签: java swing keylistener


【解决方案1】:

正如其他人提到的。使用Key Bindings 可能会更好。但是,在您的情况下,您的焦点在其他地方,因此您的组件只需要抓住焦点。只需在主目录中添加 star.grabFocus();。即:

public static void main(String[] args){
    JFrame frame = new JFrame("Up Up And Away!");
    JComponent star = new Test2("*", 250, 100);
    frame.add(star);
    frame.setSize(500, 300);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setVisible(true);

    star.grabFocus();
}

那么它应该可以工作了。

【讨论】:

  • 我认为他应该使用在他的 Snake 课程中使用的 keyListener,就像我在这里 stackoverflow.com/a/26098190/1966247 所做的那样,它正在工作
  • 谢谢它的工作,但由于某种原因,它只是向下或向左移动,而不是向右或向上移动。我知道这不是 keylistener 的问题,但我不确定为什么这两个方向有效而其他两个方向无效
  • 我认为你忘记了你的 switch 语句中的中断
  • 每个“案例”的结尾都需要有一个“中断”,否则你会得到一些有趣的结果。
【解决方案2】:

您的KeyListener 应用在JComponent 而不是JFrame,当您运行程序时JFrame 具有焦点(只有JFrame 可以监听KeyEvents),将以下行添加到您的Game 类中然后它应该工作:)

frame.addKeyListener((KeyListener)star); 

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-10-05
    • 1970-01-01
    • 1970-01-01
    • 2012-01-19
    • 1970-01-01
    • 2017-02-18
    • 1970-01-01
    相关资源
    最近更新 更多