您可以链接两个JFormattedTextFields的值吗? [英] Can you link values for two JFormattedTextFields?
问题描述
我有一个带有2个JFormattedTextFields的接口,我需要它们的值(不仅仅是显示的文本)是相同的.理想情况下,它们都应该是可编辑的,并且其中一个的变化反映在另一个中.
I've got an interface with 2 JFormattedTextFields for which I need the values (not just the displayed text) to be identical. Ideally they should both be editable, with a change in one being mirrored in the other.
我首先只是在两个文档之间共享一个文档,但是很快遇到了一个问题,即它仅链接显示的文本,而不链接基础值. (对不起,我!)
我没有尝试为值"属性添加互惠的PropertyChangeListeners,因为我希望这会建立一个无限的修改循环.
I started by just sharing a single Document between the two, but quickly ran into the problem that this only links the displayed text, not the underlying value. (Silly me!)
I haven't tried adding reciprocal PropertyChangeListeners for the "value" property because I would expect that to set up an infinite loop of modification.
我错过了什么吗?有什么办法可以做到这一点?还是我只允许用户编辑两者之一,而只让值沿一个方向传播?
Am I missing something? Is there some way to do this? Or am I stuck with only allowing users to edit one of the two and only having the value propagate in one direction?
谢谢!
推荐答案
我需要相同的值(而不仅仅是显示的文本). 理想情况下,它们都应该是可编辑的,并且其中一个要更改 相互映照.
I need the values (not just the displayed text) to be identical. Ideally they should both be editable, with a change in one being mirrored in the other.
-
使用 DocumentListener ,
(仅一个方向)
import java.awt.GridLayout; import javax.swing.*; import javax.swing.event.DocumentEvent; import javax.swing.event.DocumentListener; public class TextLabelMirror { private JPanel mainPanel = new JPanel(); private JTextField field = new JTextField(20); private JTextField field1 = new JTextField(20); public TextLabelMirror() { field.getDocument().addDocumentListener(new DocumentListener() { @Override public void changedUpdate(DocumentEvent e) { updateLabel(e); } @Override public void insertUpdate(DocumentEvent e) { updateLabel(e); } @Override public void removeUpdate(DocumentEvent e) { updateLabel(e); } private void updateLabel(DocumentEvent e) { java.awt.EventQueue.invokeLater(new Runnable() { @Override public void run() { field1.setText(field.getText()); } }); } }); mainPanel.setLayout(new GridLayout(1, 0, 10, 0)); mainPanel.add(field); mainPanel.add(field1); } public JComponent getComponent() { return mainPanel; } private static void createAndShowUI() { JFrame frame = new JFrame("TextLabelMirror"); frame.getContentPane().add(new TextLabelMirror().getComponent()); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.pack(); frame.setLocationRelativeTo(null); frame.setVisible(true); } public static void main(String[] args) { java.awt.EventQueue.invokeLater(new Runnable() { @Override public void run() { createAndShowUI(); } }); } }
这篇关于您可以链接两个JFormattedTextFields的值吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!