Search code examples
javaswingjtextfieldlook-and-feel

Set inactive background color on JTextField per-component under Windows LAF


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?


Solution

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