本人刚学JAVA才二个星期,写了一个小程序,但运行时,键盘的监听不行.
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.applet.Applet;
public class two extends JFrame implements KeyListener{
JLabel lab1,lab2;
Icon pic;
JPanel inputPanel,testPanel,Panel;
public two()
{
inputPanel=new JPanel(new GridLayout(4,2,5,5));
JTextField sexTF=new JTextField(10);
JLabel stuNumLab=new JLabel("学生学号");
JLabel nameLab=new JLabel("学生姓名");
JTextField nameTF=new JTextField(10);
JLabel ageLab=new JLabel("学生年龄");
JTextField ageTF=new JTextField(10);
JLabel sexLab=new JLabel("学生性别");
JTextField stuNumTF=new JTextField(10);
inputPanel.add(stuNumLab);
inputPanel.add(stuNumTF);
inputPanel.add(nameLab);
inputPanel.add(nameTF);
inputPanel.add(ageLab);
inputPanel.add(ageTF);
inputPanel.add(sexLab);
inputPanel.add(sexTF);
testPanel=new JPanel(new FlowLayout(FlowLayout.CENTER));
lab1 = new JLabel("嘿嘿,开始演示~~~~~");
pic = new ImageIcon("ts00.gif");
lab2 = new JLabel();
lab2.setIcon(pic);
testPanel.add(lab1);testPanel.add(lab2);
this.addKeyListener(this);
Panel=new JPanel(new GridLayout(2,1,10,10));
Panel.add(inputPanel);Panel.add(testPanel);
add(Panel);
setSize(500,300);
show();
}
public void keyPressed(KeyEvent e)
{
if(e.getKeyText(e.getKeyCode()).equals("Up"))
{
lab1.setText("嘿嘿,开始演示~");
pic = new ImageIcon("ts00.gif");
lab2.setIcon(pic);
}
else if(e.getKeyText(e.getKeyCode()).equals("Down"))
{
lab1.setText("打劫~~");
pic = new ImageIcon("ts01.gif");
lab2.setIcon(pic);
}
}
public void keyReleased(KeyEvent e)
{
}
public void keyTyped(KeyEvent e)
{
}
public static void main(String a[])
{
new two();
}
}
[此贴子已经被作者于2007-10-20 9:40:30编辑过]