KeyListener不能与PaintComponent一起使用 [英] KeyListener not working with PaintComponent

查看:144
本文介绍了KeyListener不能与PaintComponent一起使用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

My program is supposed to wait for either the left or right arrow key to be pressed, then change a value so the next time PaintComponent is updated, the screen looks different. However, the screen doesn't change when I run the program.

以下是变量声明:

static KeyListener listen;

public static int slide = 0;

以下是主菜单中的KeyListener声明:

Here's the KeyListener declaration in the main:

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)大小写,但是当我按箭头键时,屏幕上没有任何变化.

When I run the program, the program prints the if(slide == 0) case, but when I press the arrow keys, nothing changes on screen.

推荐答案

您需要先将键侦听器添加到组件中,然后才能调用该组件:

You need to add the key listener to the component before it will be called:

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

您还需要使组件具有可聚焦性,并使其具有焦点:

You also need to make the component focusable and give it the focus:

setFocusable(true);
requestFocusInWindow();

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

Finally, if you want to redraw the screen when the key is pressed, you have to call the component's repaint() method in the key press handler.

这篇关于KeyListener不能与PaintComponent一起使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆