I am trying to write a program in Java Swing that draws a grid of 10 x 10 geometric rectangles filled with randoms colors. However, when the user clicks on one of the rectangles in the display window, the rectangle should repaint () and change to a different color.
So far, I have run a rudimentary program, but I canβt understand how to implement a mouseListener for it to change the color of the rectangles when the user clicks inside. At this point, the rectangles only redraw when the display window expands and is minimized. Any advice / help would be greatly appreciated! Thanks!
Here is what I still have ...
import java.awt.*; import javax.swing.*; import java.awt.event.*; import java.awt.geom.*; public class ColorGrid extends JPanel { int w, x, y, z; Color c = new Color((int)(Math.random() * 0xFFFFFF)); public void paint(Graphics g){ Graphics2D g2 = (Graphics2D) g; setLayout(new GridLayout(10,10)); int w = x = y = z = 0; for(int i=0;i<100;i++){ Color c = new Color((int)(Math.random() * 0xFFFFFF)); w+=10; x+=10; y+=50; z+=15; g2.drawRect(w+10,x+30,y,z); g2.drawRect(w+10,x+30,y,z); g2.fillRect(w+10,x+30,y,z); g2.setPaint(c); } } public static void main(String[] args) { JFrame f= new JFrame(); f.setTitle("ColorGrid Display Window"); f.setSize(200,200); f.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { System.exit(0); } }); Container contentPane = f.getContentPane(); contentPane.add(new ColorGrid()); f.show(); } }
source share