【问题标题】:KeyListener not working with PaintComponentKeyListener 不适用于 PaintComponent
【发布时间】:2014-04-29 15:49:44
【问题描述】:

我的程序应该等待左箭头键或右箭头键被按下,然后更改一个值,以便下次更新 PaintComponent 时,屏幕看起来会有所不同。但是,当我运行程序时,屏幕并没有改变。

这里是变量声明:

static KeyListener listen;

public static int slide = 0;

这是主要的 KeyListener 声明:

listen = new KeyListener() {
        public void keyPressed(KeyEvent arg0) {
            if(arg0.getKeyCode() == KeyEvent.VK_LEFT && slide>0) {
                slide--;
                System.out.println("Left pressed. Slide is " + slide);
            }
            else if(arg0.getKeyCode() == KeyEvent.VK_RIGHT) {
                slide++;
                System.out.println("Right pressed. Slide is " + slide);
            }
        }
        public void keyReleased(KeyEvent arg0) {}
        public void keyTyped(KeyEvent arg0) {}

    };

以下是用于绘画的方法:

public void paintComponent(Graphics g){
        super.paintComponent(g);
        this.setBackground(new Color(0, 0, 20));
        g.drawImage(exitButton, 20, 20, null);
        drawBoard(g);
    }



    public void drawBoard(Graphics g){

        if(slide == 0) {
            String[] text0 = {"This is the test",
                    "for the Presenter application",
                    "Here is a nicely framed picture of the Berlin Wall."
                    };
            makeTextBox(text0);
            g.drawImage(textBox, textX, textY,(boxW)*2,(boxH)*2, null);
            g.setColor(Color.blue);
            g.fillRect(wallX-10, wallY-10, wallW+20, wallH+20);
            g.drawImage(wall, wallX, wallY, null);
        }
        else if(slide == 1) {
            String[] text1 = {"Here is the second page...",
                                "Welcome."};
            makeTextBox(text1);
            g.drawImage(textBox, textX, textY,(boxW)*2,(boxH)*2, null);
        }

    }

当我运行程序时,程序会打印if(slide == 0) 大小写,但是当我按下箭头键时,屏幕上没有任何变化。

【问题讨论】:

  • 你有没有将keylistener添加到任何东西?
  • 您是否将 KeyListener 添加到您的容器中?
  • 你在某个时候需要repaint() :-)
  • 啊是的repaint();,我似乎总是忘记这一点。

标签: java swing jpanel paintcomponent keylistener


【解决方案1】:

你需要在组件被调用之前添加key listener:

addKeyListener(new KeyListener() {
    /* ... methods as before ... */
});

您还需要使组件具有焦点并赋予它焦点:

setFocusable(true);
requestFocusInWindow();

最后,如果要在按键时重绘屏幕,则必须在按键处理程序中调用组件的repaint()方法。

【讨论】:

    【解决方案2】:

    不要使用 KeyListener,它现在可以在组件没有焦点时工作!

    Swing 旨在与Key Bindings 一起使用。有关更多信息和使用 Key Bindings 的示例,请参阅 Motion Using the Keyboard

    【讨论】:

      猜你喜欢
      • 2011-12-18
      • 2018-07-07
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多