谢谢你们的回复。我将使用下面的代码(忽略导入)来显示我的问题。(简而言之,将上面的文本字段称为“field1”,将下面的文本字段称为“field2”) 在diaog中,当我在field1中输入时,单击field2,field2将在field1中显示文本。但如果我在 field1 中输入,并显示其弹出菜单以复制/粘贴,我不想将 field1 的文本显示到 field2。
public class MyDialog extends JDialog {
public MyDialog() {
final JTextField name = new JTextField(20);
name.setEditable(true);
final JTextField clone = new JTextField(20);
clone.setEditable(true);
getContentPane().setLayout(new GridLayout(2, 1));
getContentPane().add(name);
getContentPane().add(clone);
name.addFocusListener(new FocusAdapter() {
public void focusLost(FocusEvent e) {
clone.setText(name.getText());
}
});
addPopupMenu(name);
}
private void addPopupMenu(final JTextField name) {
JPopupMenu menu = new JPopupMenu();
JMenuItem copyItem = menu.add(name.getActionMap().get(DefaultEditorKit.copyAction));
copyItem.setText("copy");
JMenuItem pasteItem = menu.add(name.getActionMap().get(DefaultEditorKit.pasteAction));
pasteItem.setText("paste");
name.setComponentPopupMenu(menu);
}
public static void main(String args[]){
MyDialog dlg = new MyDialog();
dlg.setSize(500, 200);
dlg.setVisible(true);
}
}