JAVA事件处理中的KeyEvent问题
发布网友
发布时间:2022-05-01 13:55
我来回答
共4个回答
热心网友
时间:2023-10-16 12:39
你没有把KeyListener监听加到JFrame中,在MovingBall类中的this.add(mp); 语句后面加上一句this.addKeyListener(mp);就行了。完整的程序如下:
import java.awt.*;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import javax.swing.*;
public class MovingBall extends JFrame{
MyPanel mp=null;
public MovingBall(){
mp= new MyPanel();
this.add(mp);
this.addKeyListener(mp); //这里加了一句
this.setSize(400,300);
this.setTitle("Moving Ball");
this.setLocationRelativeTo(null);
this.setVisible(true);
}
public static void main(String[] args) {
MovingBall movingBall= new MovingBall();
}
}
class MyPanel extends JPanel implements KeyListener{
int x=10;
int y=10;
public void paint(Graphics g){
super.paint(g);
g.fillOval(x,y,10,10);
}
public void keyPressed(KeyEvent e) {
if(e.getKeyCode()==KeyEvent.VK_DOWN){
y++;
}
else if(e.getKeyCode()==KeyEvent.VK_UP){
y--;
}
else if(e.getKeyCode()==KeyEvent.VK_LEFT){
x--;
}
else if(e.getKeyCode()==KeyEvent.VK_RIGHT){
x++;
}
this.repaint();
}
public void keyReleased(KeyEvent arg0) {
// TODO Auto-generated method stub
}
public void keyTyped(KeyEvent arg0) {
// TODO Auto-generated method stub
}
}
热心网友
时间:2023-10-16 12:39
addKeyListener到JFrame上即可。 注意添加监听的位置。
热心网友
时间:2023-10-16 12:40
还要重写方法啊
public void keyReleased(KeyEvent arg0) {
// TODO Auto-generated method stub
}
public void keyTyped(KeyEvent arg0) {
// TODO Auto-generated method stub
}
热心网友
时间:2023-10-16 12:40
没加监听
热心网友
时间:2023-10-16 12:39
你没有把KeyListener监听加到JFrame中,在MovingBall类中的this.add(mp); 语句后面加上一句this.addKeyListener(mp);就行了。完整的程序如下:
import java.awt.*;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import javax.swing.*;
public class MovingBall extends JFrame{
MyPanel mp=null;
public MovingBall(){
mp= new MyPanel();
this.add(mp);
this.addKeyListener(mp); //这里加了一句
this.setSize(400,300);
this.setTitle("Moving Ball");
this.setLocationRelativeTo(null);
this.setVisible(true);
}
public static void main(String[] args) {
MovingBall movingBall= new MovingBall();
}
}
class MyPanel extends JPanel implements KeyListener{
int x=10;
int y=10;
public void paint(Graphics g){
super.paint(g);
g.fillOval(x,y,10,10);
}
public void keyPressed(KeyEvent e) {
if(e.getKeyCode()==KeyEvent.VK_DOWN){
y++;
}
else if(e.getKeyCode()==KeyEvent.VK_UP){
y--;
}
else if(e.getKeyCode()==KeyEvent.VK_LEFT){
x--;
}
else if(e.getKeyCode()==KeyEvent.VK_RIGHT){
x++;
}
this.repaint();
}
public void keyReleased(KeyEvent arg0) {
// TODO Auto-generated method stub
}
public void keyTyped(KeyEvent arg0) {
// TODO Auto-generated method stub
}
}
热心网友
时间:2023-10-16 12:39
addKeyListener到JFrame上即可。 注意添加监听的位置。
热心网友
时间:2023-10-16 12:40
还要重写方法啊
public void keyReleased(KeyEvent arg0) {
// TODO Auto-generated method stub
}
public void keyTyped(KeyEvent arg0) {
// TODO Auto-generated method stub
}
热心网友
时间:2023-10-16 12:40
没加监听