gpt4 book ai didi

java - KeyListener 无法与 PaintComponent 一起使用

转载 作者:行者123 更新时间:2023-12-02 05:53:00 24 4
gpt4 key购买 nike

我的程序应该等待按下左箭头键或右箭头键,然后更改一个值,以便下次更新 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) 情况,但是当我按箭头键时,屏幕上没有任何变化。

最佳答案

您需要在组件被调用之前添加关键监听器:

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

您还需要使组件可聚焦并为其提供焦点:

setFocusable(true);
requestFocusInWindow();

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

关于java - KeyListener 无法与 PaintComponent 一起使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23369447/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com