gpt4 book ai didi

java - 如何修复 KeyListener

转载 作者:行者123 更新时间:2023-12-01 12:46:55 24 4
gpt4 key购买 nike

为什么这不起作用JFrame 已制作完毕,油漆正在工作,但我无法让按键监听器工作。我尝试在按键监听器中打印一些内容,但按下左箭头时它没有显示。

import java.awt.event.KeyEvent;


public class movingsquare extends runpaintgui{
public void key(KeyEvent e) {
if (e.getKeyCode() == KeyEvent.VK_LEFT){

x = x - 5;
repaint();
System.out.println( x);
}

}
}

其他类

import java.awt.Graphics;
import java.awt.event.KeyEvent;

import javax.swing.JFrame;

public class runpaintgui extends JFrame{
int x = 30;
public static void main(String[] args){
runpaintgui frame = new runpaintgui();
frame.setSize(1275, 775);
frame.setResizable(false);
frame.setTitle("game");
frame.setVisible(true);

}
public void paint(Graphics g){
super.paint(g);

g.fill3DRect(x, 30, 60, 60, true);


}


}

最佳答案

这样更改您的代码:

package de.swisslife.muellerj.test;

import java.awt.Graphics;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;

import javax.swing.JFrame;

public class runpaintgui extends JFrame implements KeyListener{

public runpaintgui(){

this.setSize(1275, 775);
this.setResizable(false);
this.setTitle("game");
this.setVisible(true);
this.addKeyListener(this);
this.setVisible(true);;
}
int x = 30;
public static void main(String[] args){
runpaintgui runpaintgui = new runpaintgui();

}
public void paint(Graphics g){
super.paint(g);

g.fill3DRect(x, 30, 60, 60, true);


}

public void keyTyped(KeyEvent e) {
// TODO Auto-generated method stub

}
public void keyPressed(KeyEvent e) {
if (e.getKeyCode() == KeyEvent.VK_LEFT){

x = x - 5;
repaint();
System.out.println( x);
}

}
public void keyReleased(KeyEvent e) {
// TODO Auto-generated method stub

}
}

关于java - 如何修复 KeyListener,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24606339/

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