importjava.awt.*;importjava.awt.event.*;publicclassTestK{publicstaticvoidmain(String[]args){newKFrame().launchFrame();}}classKFrameextendsFrame{Labellab;TextFieldtf;Butto...
import java.awt.*;
import java.awt.event.*;
public class TestK {
public static void main(String[] args) {
new KFrame().launchFrame();
}
}
class KFrame extends Frame {
Label lab;
TextField tf;
Button u,d,l,r;
Panel p;
public void launchFrame() {
setBounds(100,100,200,200);
lab = new Label("");
tf = new TextField("",10);
p = new Panel();
p.add(lab);
p.add(tf);
u = new Button("Up");
d = new Button("Down");
l = new Button("Left");
r = new Button("Right");
u.addActionListener(new ButtonMonitor());
d.addActionListener(new ButtonMonitor());
l.addActionListener(new ButtonMonitor());
r.addActionListener(new ButtonMonitor());
add(u, BorderLayout.NORTH);
add(d, BorderLayout.SOUTH);
add(r, BorderLayout.EAST);
add(l, BorderLayout.WEST);
add(p, BorderLayout.CENTER);
pack();
this.addKeyListener(new MyListener());
this.addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
setVisible(true);
}
class MyListener extends KeyAdapter {
public void keyPressed(KeyEvent e) {
int keyCode = e.getKeyCode();
if(keyCode == KeyEvent.VK_UP) {
System.out.println("UP");
lab.setText("UP");
} else if(keyCode == KeyEvent.VK_DOWN) {
lab.setText("DOWN");
} else if(keyCode == KeyEvent.VK_LEFT) {
lab.setText("LEFT");
} else if(keyCode == KeyEvent.VK_RIGHT) {
lab.setText("RIGHT");
}
}
}
class ButtonMonitor implements ActionListener {
public void actionPerformed(ActionEvent e) {
Button b = (Button)e.getSource();
String s = b.getLabel();
tf.setText(s);
}
}
}
单独的两个Listener都可以的
但是加在一起就只有ActionListener能实现了
KeyListener就不起作用啦
为什么会这样啊????
可以编译,也可以运行,但是按上下左右键的时候没有反应啦
(注意是实现Listener中的功能!!!)
展开