主题:这个简单的程序哪有问题
各位java高手帮忙看下这个程序哪有错误,为什么我按上下左右键没反映
代码如下:
import java.awt.event.*;
import java.awt.*;
import javax.swing.*;
public class labelmove{
private JLabel label;
public labelmove(JFrame f){
f.setSize(500,500);
f.setVisible(true);
label=new JLabel("注意标签的移动",JLabel.CENTER);
Container contentpane=f.getContentPane();
label.setForeground(Color.red);
label.setBackground(Color.pink);
contentpane.setBackground(Color.yellow);
contentpane.add(label);
Handler h=new Handler();
label.addKeyListener(h);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public static void main(String arg[]){
new labelmove(new JFrame("主窗口"));
}
private class Handler implements KeyListener{
public void keyTyped(KeyEvent e){
if(e.getKeyCode()==KeyEvent.VK_UP)
label.setLocation(label.getX(),label.getY()+100);
if(e.getKeyCode()==KeyEvent.VK_LEFT)
label.setLocation(label.getX()-100,label.getY());
if(e.getKeyCode()==KeyEvent.VK_DOWN)
label.setLocation(label.getX(),label.getY()-100);
if(e.getKeyCode()==KeyEvent.VK_RIGHT)
label.setLocation(label.getX()+100,label.getY());
}
public void keyPressed(KeyEvent e){
}
public void keyReleased(KeyEvent e){
}
}
}
代码如下:
import java.awt.event.*;
import java.awt.*;
import javax.swing.*;
public class labelmove{
private JLabel label;
public labelmove(JFrame f){
f.setSize(500,500);
f.setVisible(true);
label=new JLabel("注意标签的移动",JLabel.CENTER);
Container contentpane=f.getContentPane();
label.setForeground(Color.red);
label.setBackground(Color.pink);
contentpane.setBackground(Color.yellow);
contentpane.add(label);
Handler h=new Handler();
label.addKeyListener(h);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public static void main(String arg[]){
new labelmove(new JFrame("主窗口"));
}
private class Handler implements KeyListener{
public void keyTyped(KeyEvent e){
if(e.getKeyCode()==KeyEvent.VK_UP)
label.setLocation(label.getX(),label.getY()+100);
if(e.getKeyCode()==KeyEvent.VK_LEFT)
label.setLocation(label.getX()-100,label.getY());
if(e.getKeyCode()==KeyEvent.VK_DOWN)
label.setLocation(label.getX(),label.getY()-100);
if(e.getKeyCode()==KeyEvent.VK_RIGHT)
label.setLocation(label.getX()+100,label.getY());
}
public void keyPressed(KeyEvent e){
}
public void keyReleased(KeyEvent e){
}
}
}