- Java code
import javax.swing.*;import java.awt.*;import java.awt.event.*;public class ShutFrame extends JFrame implements ActionListener,KeyListener{ private JLabel label_1 = null; private JLabel label_2= null; private JLabel overTime = null; private JTextField HH = null; private JTextField mm = null; private JTextField ss = null; private JButton exit = null; private JButton hide = null; private JButton start = null; public ShutFrame(){ label_1 = new JLabel("请输入时,分,秒!"); label_2 = new JLabel("距离关机时间还有:"); overTime = new JLabel("在这里显示时间"); HH = new JTextField(3); mm = new JTextField(3); ss = new JTextField(3); exit = new JButton("退出"); hide = new JButton("隐藏"); start = new JButton("开始"); JPanel jp1= new JPanel(); JPanel jp2= new JPanel(); JPanel jp3= new JPanel(); jp1.add(label_1); jp1.add(HH); jp1.add(mm); jp1.add(ss); jp2.add(label_2); jp2.add(overTime); jp3.add(exit); jp3.add(hide); jp3.add(start); this.setLayout(new GridLayout(3,1)); this.add(jp1); this.add(jp2); this.add(jp3); this.setBounds(200,200,250,200); hide.addActionListener(this); this.addKeyListener(this); this.setVisible(true); } public void actionPerformed(ActionEvent e){ this.setVisible(false); } public void keyTyped(KeyEvent e){ } public void keyPressed(KeyEvent e){ System.out.println(e.getKeyCode()); //System.out.println(e.VK_KP_DOWN); if(e.getKeyCode() == 40){//下 } if(e.getKeyCode() == 39){//右 } if(e.getKeyCode() == 37){//左 } if(e.getKeyCode() == 38){//上 } } public void keyReleased(KeyEvent e){ System.out.println(e.getKeyCode()); } public static void main(String[] args){ ShutFrame s = new ShutFrame(); } }
------解决方案--------------------
要为监听按键动作的控件直接添加KeyListener,而不是ShutFrame亦或JPanel,因为一开始默认的焦点已经在你的JTextFiled控件中了,所以产生的事件是控件的事件,EDT是不会分发给ShutFrame或者JPanel的。