我有一个JSpinner
使用SpinnerNumberModel
使用double
值的GUI。如何根据当前编辑的字段内容更改JSpinner的背景颜色?
只要我改变JSpinner
的Editor
的内容,我希望背景更改为黄色(表明当前显示的值不是“保存”分别在JSpinner
之一的Model
。
如果该内容无效(如出由指定的允许范围内的我SpinnerNumberModel
或文本为“ABC”)的背景应更改为红色。
我想实现我想用一个FocusListener
既可但还没有成功,我也不确定它是否可以工作,因为我需要检查聚焦和散焦之间的内容。
我选中了所有Listeners
的教程,其中存在Swing
组件,但无法找到适合该作业的正确组件。 (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);
}
}
}
1)为了更好地帮助越早,张贴[MCVE]或[简要,独立的,正确的示例](http://www.sscce.org/)。 2)请参阅[检测/修复代码块的悬挂紧密支架](http://meta.stackexchange.com/q/251795/155831),以解决问题,我不再担心修复问题。 3)为什么不改变微调框的边框颜色,或者它旁边图标的颜色?我总是小心地改变使用颜色出于各自原因的组件的BG颜色。 –
感谢fb,我会尽快为自己找到一个解决方案来修复代码示例,并且已经修复了悬挂支架! 这样的东西肯定会让你这样的经验丰富的用户感到厌烦,但对于像我这样的新手来说肯定是个大陷阱;) – Vito