Search code examples
javaswingjbutton

How do I change the color of a button, not just the border around it?


I want to change both the background and foreground color of my button. I used setBackground and setForeground and setOpaque(true), and it worked for the foreground, but not for the background of the button. There is kind of like a black border around the button, but I want the button itself to be black. How do I fix it?

this.closeButton = new JButton ("Close");
    this.closeButton.setBackground(Color.BLACK);
    this.closeButton.setForeground(Color.PINK);
    this.closeButton.setOpaque(true);

This is what I have


Solution

  • The "border" is provided by the look and feel delegate. You can "disable" it by calling button.setBorderPainted

    This may or may not meet your expecations

    Close button

    JButton button = new JButton("Close");
    button.setBackground(Color.BLACK);
    button.setForeground(Color.PINK);
    button.setBorderPainted(false);
    button.setOpaque(true);