我有一个 JFormattedTextField
组件,其 Integer
值在没有焦点时每秒更新 3 次。
为了更新值,我使用 Swing Timer。
我想让用户编辑其值(以更新模型中的某些值),但我知道 JFormattedTextField
的值不会在每次失去焦点时更新。因此,在lostFocus事件中更改模型属性是不明智的,另一方面,当模型失去焦点时,更新程序模块可以更改其值,这使得情况变得更加困难。
很明显,我也不能使用 propertyListener
,因为该值每秒更新 3 次!
现在我想知道如何在有利的 JFormattedTextField
功能上更新变量,并让更新程序在没有焦点时更新我的 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();
}
}
最佳答案
如果在焦点丢失时将编辑提交到 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()));
}
关于java - 如何获取由 Swing 计时器每秒更新 3 次的 JFormattedTextField 的用户编辑值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20734217/