I have a JPanel that implements custom drawing to draw a background. Over this, the application can place JButtons to detect clicks on certain areas of the JPanel. However, when highlighting the (non-opaque) buttons with the mouse, the underlying JPanel’s graphics become all glitchy.

These are 9 JPanels with the custom drawing, each of them with 2 filling JButtons (R and L). The top right block and the ones looking like it are ‘fresh’. The bottom right has both buttons highlighted, the middle one only the ‘R’, etc.
I create my buttons like this:
rotatePanel = new JPanel();
rotatePanel.setOpaque(false);
GridLayout rotateLayout = new GridLayout(1, 2);
rotatePanel.setLayout(rotateLayout);
rotateRight = new JButton("R");
rotateRight.addActionListener(this);
rotateRight.setOpaque(false);
rotateRight.setContentAreaFilled(false);
rotateRight.setBorderPainted(false);
rotatePanel.add(rotateRight);
rotateLeft = new JButton("L");
rotateLeft.addActionListener(this);
rotateLeft.setOpaque(false);
rotateLeft.setContentAreaFilled(false);
rotateLeft.setBorderPainted(false);
rotatePanel.add(rotateLeft);
and this is my drawing code:
public void paintComponent(Graphics g) {
super.paintComponent(g);
Rectangle clipRect = g.getClipBounds();
clipRect.grow(-4, -4);
int thirdWidth = clipRect.width/3;
int thirdHeight = clipRect.height/3;
for (int x = 0; x < Board.DIM; x++) {
//Draw the columns
for (int y = 0; y < Board.DIM; y++) {
//Draw the rows
g.drawRect(thirdWidth * x, thirdHeight * y, thirdWidth, thirdHeight);
}
}
g.setColor(Color.BLACK);
g.drawRect(0, 0, clipRect.width, clipRect.height);
}
When changes to a child component require part of your panel to be redrawn, only the area overlapped by that component needs to be drawn. When you do
g.getClipBounds(), you are getting the region to be painted, not the bounds of your whole panel. You probably just want to usegetWidth()andgetHeight().