Java 如何更改JSpinner(数字模型)的背景色?

Java 如何更改JSpinner(数字模型)的背景色?,java,swing,colors,background,jspinner,Java,Swing,Colors,Background,Jspinner,我想将我的JSpinner的背景色更改为红色,以通知用户一个错误。我的微调器使用数字模型(不知道它是否会影响)。 我尝试了很多解决方案,但没有一个奏效 jspinner.setBackground(Color.red); jspinner.getEditor().getComponent(0).setBackground(Color.red); 我知道我必须访问微调器的特定组件(如JFormattedTextField),但我不知道怎么做…) 编辑 这应该起作用: JSpinner.Numbe

我想将我的
JSpinner
的背景色更改为红色,以通知用户一个错误。我的微调器使用数字模型(不知道它是否会影响)。 我尝试了很多解决方案,但没有一个奏效

jspinner.setBackground(Color.red);
jspinner.getEditor().getComponent(0).setBackground(Color.red);
我知道我必须访问微调器的特定组件(如
JFormattedTextField
),但我不知道怎么做…)

编辑 这应该起作用:

JSpinner.NumberEditor jsEditor = (JSpinner.NumberEditor) 
spinner.getEditor(); jsEditor.getTextField().setBackground(Color.red);
但事实并非如此。有人知道为什么吗?

JComponent editor=spinner.getEditor();
JComponent editor = spinner.getEditor();
        int n = editor.getComponentCount();
        for (int i=0; i<n; i++)
        {
            Component c = editor.getComponent(i);
            if (c instanceof JTextField)
            {
                c.setForeground(Color.red);
                c.setBackground(Color.red);
            }
        }
int n=editor.getComponentCount(); 对于(int i=0;i
JComponent editor=spinner.getEditor();
int n=editor.getComponentCount();

对于(int i=0;i这是更改jSpinner背景色的最简单方法:

SpinnerNumberModel nummodel = new SpinnerNumberModel(5, 0, 10, 1);
JSpinner numspinner = new JSpinner(nummodel);
numspinner.getEditor().getComponent(0).setBackground(Color.green);
                     //getComponent(0) gives you text field

这是更改jSpinner背景色的最简单方法:

SpinnerNumberModel nummodel = new SpinnerNumberModel(5, 0, 10, 1);
JSpinner numspinner = new JSpinner(nummodel);
numspinner.getEditor().getComponent(0).setBackground(Color.green);
                     //getComponent(0) gives you text field

工作(当然它不适用于
DateEditor/Model
),例如可以直接从
JSpinner.NumberEditor jsEditor=(JSpinner.NumberEditor)spinner.getEditor();
JFormattedTextField textField=jsEditor.getTextField();
@mKorbel
JSpinner.NumberEditor jsEditor=(JSpinner.NumberEditor)spinner.getEditor();和JFormattedTextField textField=jsEditor.getTextField().setBackground(Color.red);
应该可以工作。这是swing的一个bug吗?@Widea的一个bug是JSpinner.DateEditor对标准设置没有反应,getEditorXxx适用于大多数复合JC组件(例如JComboBox,可编辑和不可编辑之间又有巨大差异)@mKorbel但是我有一个NumberEditor。所以我不能改变背景色,或者我可以绕过它?有效(假设它不适用于
DateEditor/Model
),例如,可以直接从
JSpinner.NumberEditor jsEditor=(JSpinner.NumberEditor)spinner.getEditor()访问
JFormattedTextField textField=jsEditor.getTextField();
@mKorbel
JSpinner.NumberEditor jsEditor=(JSpinner.NumberEditor)spinner.getEditor();和JFormattedTextField textField=jsEditor.getTextField().setBackground(颜色.红色);
应该可以工作。这是swing的一个bug吗?@Widea的一个bug是JSpinner.DateEditor不响应标准设置,getEditorXxx适用于大多数复合JComboBox组件(例如,JComboBox,可编辑组件和非可编辑组件之间的巨大差异)@mKorbel但是我有一个数字编辑器。所以我不能改变背景颜色,或者我可以绕过它?为了更快地获得更好的帮助,发布一个or。为了更快地获得更好的帮助,发布一个or。