【问题标题】:How to change the background color of a JSpinner (Number model)?如何更改 JSpinner(数字模型)的背景颜色?
【发布时间】:2017-02-16 17:51:25
【问题描述】:

我想将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);

但事实并非如此。有人知道为什么吗?

【问题讨论】:

标签: java swing colors background jspinner


【解决方案1】:

这是更改 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

【讨论】:

    【解决方案2】:
    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);
                }
            }
    

    【讨论】:

    • 有效(AFAIK 它不适用于DateEditor/Model),例如可直接从JSpinner.NumberEditor jsEditor = (JSpinner.NumberEditor) spinner.getEditor();JFormattedTextField textField = jsEditor.getTextField(); 访问
    • @mKorbel JSpinner.NumberEditor jsEditor = (JSpinner.NumberEditor) spinner.getEditor(); and JFormattedTextField textField = jsEditor.getTextField().setBackground(Color.red); 应该可以。是swing的bug吗?
    • @Widea 错误是 JSpinner.DateEditor 不对标准设置做出反应,getEditorXxx 适用于大多数复合 JComponent(例如 JComboBox,可编辑与不可编辑之间的差异也很大)
    • @mKorbel 但我有一个 NumberEditor。所以我不能改变背景颜色或者我可以绕过它?
    猜你喜欢
    • 2023-03-05
    • 1970-01-01
    • 2011-11-11
    • 1970-01-01
    • 1970-01-01
    • 2016-04-08
    • 2018-02-13
    • 2012-01-02
    • 2022-01-21
    相关资源
    最近更新 更多