开发者

locking JTextField from external updates while editing

开发者 https://www.devze.com 2023-02-20 09:57 出处:网络
My GUI displays the data coming from the backend every 500ms. I\'m having a race condition when it comes to editing fields. By the time the Action listener is invoked, the value from the backend overw

My GUI displays the data coming from the backend every 500ms. I'm having a race condition when it comes to editing fields. By the time the Action listener is invoked, the value from the backend overwrites whatever the user entered manually into a text field.

Is there a way to lock the field or use a semaphore or retrieve new value from elsewhere?

Thanks.

        JTextField tf = new JTextField();
        tf.setName("reg_r"+i);          
        tf.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                // TODO Auto-generated method stub
                开发者_开发问答JTextField tf = (JTextField)e.getSource();

                //prints OLD value!
                System.err.println(tf.getText());

            }
        });


The solution i came up with is to detect when the text field is being edited and not update it.

JTextField tf = (JTextField) FrameUtils
                    .getComponentById(
                            instance.getContentPane(), "reg_r"
                                    + i);
            Component c = (Component) getFocusOwner();
            if (c == null || !tf.getName().equals(c.getName())) {
            // JTextField is not focused/being edited, proceed with update
            tf.setText(...);
            }
0

精彩评论

暂无评论...
验证码 换一张
取 消