user4010555
user4010555

Reputation:

How to intercept paintComponent from Custom JButton

I created a Custom JButton with transparent background and a drawn line from graphics.drawRoundRect() but when I start my program for testing, my JCheckbox keeps appearing on top of the button.

It looks like this at the beginning

enter image description here

And this is after I hover over the Button with the mousecursor

enter image description here

Here is the Code from the paintComponent Method

    @Override
public void paintComponent(Graphics graphics) {
    graphics.setColor(this.getForeground());
    graphics.drawRoundRect(2, 2, this.getWidth() - 4, this.getHeight() - 4, 30, 30);
    graphics.setFont(this.getFont());

    int centerX = getWidth() / 2;
    int centerY = getHeight() / 2;

    FontMetrics fontMetrics = graphics.getFontMetrics();
    Rectangle stringBounds = fontMetrics.getStringBounds(this.getText(), graphics).getBounds();

    int textX = centerX - stringBounds.width / 2;
    int textY = centerY + fontMetrics.getAscent() / 2;

    graphics.setColor(this.getForeground());
    graphics.drawString(this.getText(), textX, textY);

}

I do not have any other methods in my button class except the Constructor with super() in it. The Class inherits from the JButton class and I set the foreground attribute to Color.white in the testing program and added the button via

frame.getContentPane().add(button);

Because my reputation is not high enough I could not insert the screenshots into the question I am using the imgur links instead. If I am not allowed to post the links in my question I will delete them immediately

Upvotes: 1

Views: 259

Answers (1)

MadProgrammer
MadProgrammer

Reputation: 347314

You've broken the paint chain, you MUST call super.paintComponent

public void paintComponent(Graphics graphics) {
    super.paintComponent(graphics);

Essentially, Graphics is a shared resource, each component painted will use the same Graphics context, meaning that unless you clear it first, you may still have what was previously painted to it still there. One of the jobs for paintComponent is to clear the Graphics context with the background color of the component...

See Painting in AWT and Swing and Performing Custom Painting for more details

Make sure you are using setOpaque(false) to make the component transparent, otherwise you could end up with other issues. You may also want to use setBorderPaint, setFocusPainted and setContentAreaFilled to change the way that the default look and feel delegates paint the button

Upvotes: 2

Related Questions