Search code examples
javamacosswingjtextfieldbackground-color

Set background of Swing JTextField


I have the following the Java code for the window with two text fields: one editable, the other - not. I would like to gray out the non-editable text field. I use setBackground() function and it seems to work in the Eclipse design viewer:

enter image description here

However, when I export it to jar, the resulting application looks like this:

enter image description here

I am using Eclipse 4.4.1 under MacOS 10.9.3.

My code:

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();
    }
}

Therefore, I have two questions:

  1. Why the behavior is different in the viewer and jar?
  2. How to 'gray out' a text field in jar?

Solution

  • It turned out that there is actually a difference between getBackground() and getContentPane().getBackground(). However, neither of them is responsible the actually seen grayish default window background. getForeground() also does not code for this color; however, for some reason it is initialized to the coinciding value in the viewer.

    Nevertheles, it is possible to override the default background color through getContentPane().setBackground() (though its initial value does not match):

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

    This generates the desirable effect both in the design viewer and jar:

    enter image description here