JFrame添加 KeyListener事件

‍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);
 }
} 

你可能感兴趣的:(JFrame,KeyListener)