设置 Swing JTextField 的背景

Set background of Swing JTextField

我有以下用于 window 的 Java 代码,其中包含两个文本字段:一个可编辑,另一个 - 不可编辑。我想将不可编辑的文本字段变灰。我使用 setBackground() 函数,它似乎在 Eclipse 设计查看器中工作:

但是,当我将其导出到 jar 时,生成的应用程序如下所示:

我在 MacOS 10.9.3 下使用 Eclipse 4.4.1

我的代码:

import java.awt.Container;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;

import javax.swing.JFrame;
import javax.swing.JTextField;

@SuppressWarnings("serial")
public class TestFrame extends JFrame {
    GridBagConstraints constraints;
    JTextField text0;

    public TestFrame() {
        super("Test window");
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setVisible(true);
        Container container = getContentPane();
        container.setLayout(new GridBagLayout());
        JTextField editableTextField, nonEditableTextField;

        constraints = new GridBagConstraints();
        editableTextField = new JTextField("Enter text here");
        constraints.gridx=0;
        constraints.gridy=0;
        container.add(editableTextField, constraints);

        constraints = new GridBagConstraints();
        nonEditableTextField = new JTextField("See result here");
        nonEditableTextField.setBackground(getForeground());
        nonEditableTextField.setEditable(false);
        constraints.gridx=0;
        constraints.gridy=1;
        container.add(nonEditableTextField, constraints);

        pack();
    }

    public static void main(String args[]) {
        new TestFrame();
    }
}

因此,我有两个问题:

  1. 为什么查看器和 jar 中的行为不同?
  2. 如何 'gray out' jar 中的文本字段?

如果您将背景颜色设置为前景色(此处为黑色),您将获得相同颜色的所有内容。

setBackground(getForeground());

尝试设置一些其他颜色。

setBackground(UIManager.getColor("TextField.inactiveBackground"));

第一个问题:
正如上面有人所说 It could have something to do with the look and feel and or the UI Defaults been installed

关于第二个问题:

  1. 您可以使用 UIManager.getColor
  2. 您可以使用 Color class 为 non editable 文本字段设置 gray 颜色。只需使用 Color.LIGHT_GRAYColor.GRAY 或您想要使用的任何其他常量。

这两种方法在 Eclipse IDE 和 JAR 文件中的工作方式相同。

修改:

1) nonEditableTextField.setBackground(UIManager.getColor(Color.lightGray));

2) nonEditableTextField.setBackground(UIManager.getColor(Color.LIGHT_GRAY));

nonEditableTextField.setBackground(Color.LIGHT_GRAY);

但是,第一种方法比第二种方法更可取。

原来getBackground()getContentPane().getBackground()其实是有区别的。然而,他们都不对实际看到的灰色默认 window 背景负责。 getForeground() 也不对这种颜色进行编码;然而,出于某种原因,它在查看器中被初始化为一致的值。

然而,可以通过 getContentPane().setBackground() 覆盖默认背景颜色(尽管其初始值不匹配):

    ...
    Container container = getContentPane();
    container.setBackground(new Color(240,240,240));
    ...
    nonEditableTextField.setBackground(container.getBackground());
    ...

这会在设计查看器和 jar 中产生理想的效果: