我有一个带有 JSpinner
的 GUI,使用 SpinnerNumberModel
使用 double
值。
一旦我更改了 JSpinner
的 Editor
的内容,我希望背景变为黄色(以表明当前显示的值不是分别“保存”在 JSpinner
中的 Model
。
如果该内容无效(例如,超出我的 SpinnerNumberModel
或文本“abc”指定的允许范围),背景应更改为红色。
我已经尝试使用 FocusListener
来实现我想要的,但还没有成功,而且我不确定它是否可以正常工作,因为我需要检查 focussing 和 focusing 之间的内容散焦。
我检查了 Swing
组件的所有 Listeners
的教程,但找不到适合该工作的合适的。 ( here I informed myself )
我是 Listeners
概念的新手,如果能帮助我更接近解决问题,同时也有助于全面理解 Listeners
以及如何使用它们,我将不胜感激在这种情况下更好!
我的非常基本的代码示例,上面提到的使用焦点监听器的糟糕尝试:
public class test implements FocusListener{
JFrame frame;
SpinnerNumberModel model;
JSpinner spinner;
JComponent comp;
JFormattedTextField field;
public test() {
JFrame frame = new JFrame("frame");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BoxLayout(frame.getContentPane(), BoxLayout.Y_AXIS));
model = new SpinnerNumberModel(0., 0., 100., 0.1);
spinner = new JSpinner(model);
comp = spinner.getEditor();
field = (JFormattedTextField) comp.getComponent(0);
field.addFocusListener(this);
frame.getContentPane().add(spinner);
frame.getContentPane().add(new JButton("defocus spinner")); //to have something to defocus when testing :)
frame.pack();
frame.setVisible(true);
}
@Override
public void focusGained(FocusEvent e) {
// TODO Auto-generated method stub
//when the values of the field and the spinner don't match, the field should get yellow
if(!field.getValue().equals(spinner.getModel().getValue())) {
field.setBackground(Color.YELLOW);
}
}
@Override
public void focusLost(FocusEvent e) {
// TODO Auto-generated method stub
//if they match again, reset to white
if(!field.getValue().equals(spinner.getModel().getValue())) {
field.setBackground(Color.RED);
}
}
}
最佳答案
JSpinner 使用文本字段作为微调器的编辑器
因此,您可以将 DocumentListener
添加到用作编辑器的文本字段的 Document
。
类似于:
JTextField textField = ((JSpinner.DefaultEditor)spinner.getEditor()).getTextField());
textField.getDocument.addDocumentListener(...);
然后,当添加/删除文本时,将生成一个 DocumentEvent,您可以进行错误检查。阅读 Listener For Changes on a Document 上的 Swing 教程部分获取更多信息和工作示例。
关于java - 如何根据字段的当前编辑内容更改 JSpinner 的背景颜色?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44871170/