简单例子
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;public class MyTest extends JFrame implements KeyListener,ActionListener{
private static final long serialVersionUID = -7206058252243611005L;JPanel pan=new JPanel();
JPanel panbut=new JPanel();
JTextField txt1=new JTextField();
JTextField txt2=new JTextField();
JTextField txt3=new JTextField();
JButton but1=new JButton("测试1");
JButton but2=new JButton("测试2");
JButton but3=new JButton("测试3");
public static void main(String[] args){
MyTest w =new MyTest();
w.setVisible(true);
}
MyTest(){
this.setSize(300,400);
pan.setLayout(new GridLayout(3,2));
pan.add(new JLabel("输入1"));
pan.add(txt1);
pan.add(new JLabel("输入2"));
pan.add(txt2);
pan.add(new JLabel("输入3"));
pan.add(txt3);
panbut.setLayout(new FlowLayout());
panbut.add(but1);
panbut.add(but2);
panbut.add(but3);
this.setLayout(new BorderLayout());
this.add(pan,BorderLayout.CENTER);
this.add(panbut,BorderLayout.SOUTH);
txt1.addKeyListener(this);
txt2.addKeyListener(this);
txt3.addKeyListener(this);
but1.addKeyListener(this);
but2.addKeyListener(this);
but3.addKeyListener(this);
but1.addActionListener(this);
but2.addActionListener(this);
but3.addActionListener(this);
but2.setName("测试2");
}
@Override
public void keyPressed(KeyEvent arg0) {
// TODO Auto-generated method stub
int key= arg0.getKeyCode();
if (key==KeyEvent.VK_ENTER) {
String name=arg0.getComponent().getName();
if (name!=null)
if (arg0.getComponent().getName().equals("测试2")) {
but2.doClick();
return;
}
arg0.getComponent().transferFocus();
}
}
@Override
public void keyReleased(KeyEvent arg0) {
// TODO Auto-generated method stub
}
@Override
public void keyTyped(KeyEvent arg0) {
// TODO Auto-generated method stub
}
@Override
public void actionPerformed(ActionEvent arg0) {
// TODO Auto-generated method stub
String butname=arg0.getActionCommand();
if (butname.equals("测试1")) {
JOptionPane.showMessageDialog(null, "错误!", "测试1", JOptionPane.ERROR_MESSAGE);
return;
}
if (butname.equals("测试2")) {
JOptionPane.showMessageDialog(null, "警告!", "测试2", JOptionPane.WARNING_MESSAGE);
return;
}
if (butname.equals("测试3")) {
JOptionPane.showMessageDialog(null, "信息!", "测试3", JOptionPane.INFORMATION_MESSAGE);
return;
}
}
}