import?java.awt.*?;
import?javax.swing.*?;
import?java.awt.event.*;
public?class?ButtonTest?extends?JFrame?implements?KeyListener{
private?JButton?b1?=?new?JButton("Click")?; public?ButtonTest(){ this.getContentPane().add(b1)?; b1.addKeyListener(this)?; this.setDefaultCloseOperation(this.EXIT_ON_CLOSE); this.pack()?; } public?void?keyReleased(KeyEvent?ke){ } public?void?keyPressed(KeyEvent?ke){ if(ke.getKeyChar()?==?ke.VK_ENTER){System.out.println?("ok................")?;
} } public?void?keyTyped(KeyEvent?ke){ } public?static?void?main(String[]?args){ new?ButtonTest().show()?;}
}
方法二:
import?java.awt.*?;
import?javax.swing.*?;
import?java.awt.event.*;
public?class?ButtonTest?extends?JFrame{
private?JButton?b1?=?new?JButton("Click")?; public?ButtonTest(){ this.getContentPane().add(b1)?; b1.addKeyListener(new?KeyAdapter(){public?void?keyPressed(KeyEvent?ke){
if(ke.getKeyChar()?==?ke.VK_ENTER){
System.out.println?("ok..............")?;}
}
} )?; this.setDefaultCloseOperation(this.EXIT_ON_CLOSE)?; this.pack()?; } public?static?void?main(String[]?args){ new?ButtonTest().show()?;}
}