import java.awt.FlowLayout; import java.awt.event.KeyAdapter; import java.awt.event.KeyEvent; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JOptionPane; public class MyFrame extends JFrame { private static final long serialVersionUID = -1355767503289477449L; public MyFrame(){ setSize(300,300); setLayout(new FlowLayout()); setVisible(true); this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); this.addWindowListener(new WindowAdapter() { @Override public void windowActivated(WindowEvent e) {//激活窗口時,使窗口得到焦點 requestFocusInWindow(); } }); this.addKeyListener(new KeyAdapter() {//窗體增長鍵盤監聽事件 @Override public void keyPressed(KeyEvent e) { JOptionPane.showMessageDialog(null, KeyEvent.getKeyText(e.getKeyCode())); } }); } public static void main(String[] args) { MyFrame myFrame = new MyFrame(); JButton jbutton = new JButton("TEST"); jbutton.setSize(30,30); myFrame.add(jbutton); } }