这个例子用java编写。在窗体中创建了两个文本框,为第一个文本框添加了按键监听器,文本内容的改变会同步到第二个文本框中。
注意实现KeyListener这个接口,一定要在里面加上 keyPressed,keyReleased,keyTyped这三个函数,大小写注意,否则会报错。
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JTextField;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
public class EventDemo extends JFrame {
private JTextField textField1;
private JTextField textField2;
public static void main(String args[]){
EventDemo frame = new EventDemo();
frame.setVisible(true);
}
public EventDemo(){
super();
getContentPane().setLayout(null);
setBounds(100,100,305,113);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
textField1 = new JTextField();
textField1.addKeyListener(new TextKeyListener());
textField1.setBounds(115, 12, 172, 22);
getContentPane().add(textField1);
textField2 = new JTextField();
textField2.setBounds(115, 40, 172, 22);
getContentPane().add(textField2);
final JLabel label = new JLabel();
label.setText("the first textfield :");
label.setBounds(10,12,99,18);
getContentPane().add(label);
final JLabel label_1 = new JLabel();
label_1.setText("the second textfield :");
label_1.setBounds(10,40,99,18);
getContentPane().add(label_1);
}
private final class TextKeyListener implements KeyListener{
public void keyPressed(KeyEvent e){
}
public void keyReleased(KeyEvent e){
String text = textField1.getText();
textField2.setText(text);
}
public void keyTyped(KeyEvent e){
}
}
}