Can you link values for two JFormattedTextFields?

前端 未结 2 875
既然无缘
既然无缘 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:29

    You can use a key listener. You simply add a key listener to both fields using the below code. the reason you need the other events is it will throw errors unless you have them in the code.

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

    } I have tested this out and it works perfectly what ever you type into one field will show up in the other as you type it.

提交回复
热议问题