您可以使用一键收听。您只需使用下面的代码将密钥侦听器添加到这两个字段。你需要其他事件的原因是它会抛出错误,除非你在代码中包含它们。
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class CreateGrid
{
JFrame thisframe;
JFormattedTextField jFormattedTextField1, jFormattedTextField2;
public CreateGrid()
{
GridLayout thislayout = new GridLayout(0,2);
thisframe = new JFrame();
thisframe.setLayout(thislayout);
jFormattedTextField1 = new JFormattedTextField();
jFormattedTextField2 = new JFormattedTextField();
jFormattedTextField1.addKeyListener(new KeyAdapter()
{
public void keyReleased(KeyEvent e)
{
JFormattedTextField textField = (JFormattedTextField) e.getSource();
String text = textField.getText();
jFormattedTextField2.setText(text);
}
public void keyTyped(KeyEvent e)
{
}
public void keyPressed(KeyEvent e)
{
}
});
jFormattedTextField2.addKeyListener(new KeyAdapter()
{
public void keyReleased(KeyEvent e)
{
JFormattedTextField textField = (JFormattedTextField) e.getSource();
String text = textField.getText();
jFormattedTextField1.setText(text);
}
public void keyTyped(KeyEvent e)
{
}
public void keyPressed(KeyEvent e)
{
}
});
thisframe.add(jFormattedTextField1);
thisframe.add(jFormattedTextField2);
thisframe.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
thisframe.setVisible(true);
thisframe.pack();
}
public static void main(String args[])
{
new CreateGrid();
}
} 我已经测试了这一点,它完美的作品,你键入一个场什么都将显示在其他您所输入的。
我没有想到DocumentListener会为我工作,因为我使用的是JFormattedTextField对象,而我想要复制的不仅仅是显示的文本(我可以通过使用同一个文档来完成),但是价值本身,一旦它被验证。此外,我想我认为调用setText()会触发一个DocumentEvent,所以我不能在两个方向上使用它。那是不正确的? – cmolodo 2013-02-20 13:55:31
仅使用'setText()'而不是使用'Document'操作,'DocumentListene'r没有被指定为将事件触发到'Document',然后必须使用'AbstractDocument'或'DocumentFilter' – mKorbel 2013-02-20 14:19:39