如何获取由Swing Timer更新3次/秒的JFormattedTextField的用户编辑值?

时间:2013-12-22 21:27:01

标签: java swing timer jformattedtextfield focuslistener

我有一个JFormattedTextField组件,其Integer值在没有焦点时会在一秒钟内更新3次。

为了更新值,我使用Swing Timer。

我希望用户能够编辑其值(更新模型中的某些值),但我知道每次失去焦点时JFormattedTextField的值都不会更新。因此,在lostFocus事件中更改模型属性是不明智的,另一方面,当它失去焦点时,更新程序模块可以更改其值,这会使情况更加困难。

很明显,我也不能使用propertyListener,因为该值会在一秒钟内更新3次!

现在我想知道如何能够更新地方获利JFormattedTextField功能上的变量,让updater在没有焦点时更新我的​​JFormattedTextField!是否可以或者我必须使用inputDialog?怎么样?

例如,在下面的代码中,当我在GUI中将字段值更改为200,然后单击JFrame使其失去焦点时,控制台中打印的值不是200.这是以前的一个很好的随机值在该领域。

public class SwingTimerFormattedTextFieldTester {

    public static void main(String... args){
        final JFrame frame = new JFrame();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setBounds(0, 0, 300, 200);
        final JFormattedTextField field = new JFormattedTextField(new Long(100));
        field.setColumns(20);
        frame.addMouseListener(new MouseAdapter() {

            @Override
            public void mouseClicked(MouseEvent e) {
                frame.requestFocus();
                e.consume();
            }


        });

        frame.getContentPane().setLayout(new FlowLayout());
        frame.getContentPane().add(field);
        frame.setVisible(true);

        Timer timer = new Timer(330, new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                if(!field.hasFocus()){
                    field.setValue(ThreadLocalRandom.current().nextLong());
                }
            }
        });
        timer.start();

        field.addFocusListener(new FocusListener() {

            @Override
            public void focusGained(FocusEvent e) {
                field.setBackground(Color.CYAN);
            }

            @Override
            public void focusLost(FocusEvent e) {
                field.setBackground(Color.WHITE);
                System.out.println(String.valueOf((Long)field.getValue()));
            }
        });

        frame.requestFocus();
    }

}

1 个答案:

答案 0 :(得分:4)

如果在焦点丢失时将编辑提交给JFormattedTextField会怎样?

 @Override
 public void focusLost(FocusEvent e) {
    try {
       if (field.isEditValid()) {
          field.commitEdit();
       }
    } catch (ParseException e1) {
       e1.printStackTrace();
    }
    field.setBackground(Color.WHITE);
    System.out.println(String.valueOf((Long) field.getValue()));
 }