我有一个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();
}
}
答案 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()));
}