Can you link values for two JFormattedTextFields?

前端 未结 2 878
既然无缘
既然无缘 2021-01-27 07:11

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 chang

2条回答
  •  南方客
    南方客 (楼主)
    2021-01-27 07:19

    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.

    • use DocumentListener,

    • for example (only the one directions)

    enter image description here

    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();
                }
            });
        }
    }
    

提交回复
热议问题