Search code examples
javaswingpaintcomponent

JPasswordField text color over written by paintcomponent


So I made my custom JPasswordField component and in it I change the background color to a color with alpha

this.setBackground( new Color(29, 29, 29, 150) );
this.setOpaque(false);

And I also make the button round so I need to use this:

@Override
protected void paintComponent(Graphics g) {
    super.paintComponent(g);
    g.setColor(getBackground());
    g.fillRoundRect(0, 0, getWidth(), getHeight(), radius, radius);
}

The problem is my text when i type is almost unreadable Field It requires me to highlight it so i can see it.

This is my foreground color:

this.setForeground(new Color(250,250,250, 250));

I changed the color a bit since the screenshot but i still have the same problem


Solution

  • Your basic logic is reversed.

    First you invoke super.paintComponent() which will paint the text.

    Then you invoke fillRoundRect(...) which will paint over top of the text.

    The logic should be reversed:

    1. paint the background
    2. invoke super.paintComponent(...)