I am not sure about the cause of your problem, since I cannot reproduce the wrong behavior with your code , but your paintComponent override neglects to call the super paintComponent method. Paste this and see what happens.
@Override // method should be protected, not public protected void paintComponent(Graphics g) { // ******* add super.paintComponent(g); g.setColor(color); g.fillRect(0, 0, 100, 100); }
Please note that if this was my program, and this was the only behavior I recommended, I would simplify my program by not overriding paintComponent, but simply by calling setBackground(color); , I would also create an array of Color or List and iterate through it:
public static final Color[] COLORS = {Color.RED, Color.Blue, Color.Green}; private int colorIndex = 0;
I would also override the getPreferredSize method.
eg.
import java.awt.*; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import javax.swing.*; @SuppressWarnings("serial") public class MyColorsPanelDemo extends JPanel { private static final int GAP = 20; public MyColorsPanelDemo() { setLayout(new GridLayout(1, 0, GAP, GAP)); setBorder(BorderFactory.createEmptyBorder(GAP, GAP, GAP, GAP)); add(new ColorPanel()); add(new ColorPanel()); } private static class ColorPanel extends JPanel { public static final Color[] COLORS = {Color.red, Color.green, Color.blue}; private static final int PREF_W = 100; private static final int PREF_H = PREF_W; private static final Color INIT_BACKGROUND = Color.black; private int colorIndex = 0; public ColorPanel() { setBackground(INIT_BACKGROUND); addMouseListener(new MouseAdapter() { @Override public void mousePressed(MouseEvent mEvt) { setBackground(COLORS[colorIndex]); colorIndex++; colorIndex %= COLORS.length; } }); } @Override public Dimension getPreferredSize() { return new Dimension(PREF_W, PREF_H); } } private static void createAndShowGui() { MyColorsPanelDemo mainPanel = new MyColorsPanelDemo(); JFrame frame = new JFrame("MyColorsPanelDemo"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.getContentPane().add(mainPanel); frame.pack(); frame.setLocationByPlatform(true); frame.setVisible(true); } public static void main(String[] args) { SwingUtilities.invokeLater(new Runnable() { public void run() { createAndShowGui(); } }); } }
source share