Search code examples
javaswingjbuttonfill

How do I change the color of an actual JButton in Java? Not the background and not the text


button[currRow][currCol].setBackground(Color.RED);
button[currRow][currCol].setContentAreaFilled(true);
button[currRow][currCol].setOpaque(true);

That's what I have right now for my connect four game to denote a red player's move.

https://i.sstatic.net/E12ZI.png

At the moment, it only colors the background and if I change my code to button[currRow][currCol].setForeground(Color.RED) then the whole thing just appears to not change. How would I fix this?


Solution

  • This is not easily achievable. The problem is that the pluggable look and feel paints the button content, and it does so in whatever way it sees fit. For instance, some L&F might paint a gradient which does not use the background color.

    I suggest for a case such as yours to use a custom image (JButton.setIcon()) and no content area (JButton.setContentAreaFilled(false)).

    Alternatively, you could create a custom component which draws the element itself, overriding JComponent.paintComponent().