3

I want to set the inactive background color of a JTextField on a per-component basis. (The inactive colors are shown when calling setEditable(false)).

Calling
UIManager.put("TextField.inactiveBackground", new ColorUIResource(Color.YELLOW));
sets the inactive color application-wide.

It can be done under Nimbus LAF like documented here: http://docs.oracle.com/javase/7/docs/api/javax/swing/plaf/nimbus/package-summary.html. Can a similar thing be done when using Windows LAF?

CleanUp
  • 410
  • 4
  • 12
  • 1
    I can't find the `inactiveBackground` property in the [Nimbus doc](http://docs.oracle.com/javase/tutorial/uiswing/lookandfeel/_nimbusDefaults.html#primary). Are you sure about the name of the property? Don't you mean `disabled`? – Eric Leibenguth Jul 15 '15 at 12:16
  • `inactiveBackground` is the name of the Windows LAF property (see http://www.duncanjauncey.com/java/ui/uimanager/UIDefaults_Java1.7.0_45_Windows_7_6.1_Windows.html). You can find an example of setting the inactive background when using Nimbus here: http://stackoverflow.com/questions/22927451/set-text-fields-disabled-background-color. – CleanUp Jul 15 '15 at 12:22
  • inactiveBackground == setDisabledColor, as aside, btw I'm never changed color theme in Win7 and have TextField.selectionBackground with yellow color instead of blue (seems like as those value are valid for WinXP:-) – mKorbel Jul 15 '15 at 14:43
  • The yellow color is really just a random color I choose for the sake of this question. In the application, the color isn't hard-coded like this. – CleanUp Jul 16 '15 at 07:06

1 Answers1

0

I found a solution. Not really a beautiful solution, but a solution nonetheless:

Extend the JTextField class and override the paintComponent method to draw a rectangle in the desired color.

class CustomTextField extends JTextField {
  private Color inactiveColor = UIManager.getColor("TextField.inactiveBackground");

  public void setDisabledBackgroundColor(Color inactiveColor) {
    this.inactiveColor = inactiveColor;
    repaint();
  }

  @Override
  protected void paintComponent(Graphics g) {
    if (!isEditable() || !isEnabled()) {
      setOpaque(false);
      g.setColor(inactiveColor);
      g.fillRect(0, 0, getWidth(), getHeight());
    } else {
      setOpaque(true);
    }
    super.paintComponent(g);
  }
}
CleanUp
  • 410
  • 4
  • 12