Java事件处理机制里的actionevevt和keyevent有什么区别和联系? 20
2个回答
2015-06-12
展开全部
你没有把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
}
}
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
}
}
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询
广告 您可能关注的内容 |