import java.util.*; import javax.swing.*; import java.awt.*; import java.awt.event.*; public class ClickBoxes extends JPanel implements MouseListener { private ArrayList boxes; private String message; public static final int SIZE = 50; public static final int WIDTH = 500; public static final int HEIGHT = 500; public void remove(Color color) { int count = 0; // initialize the removed boxes counter // your code here: write a loop to eliminate // all the boxes that have the same color // and increase count by one for every box removed ... // update the message: message = "removed "+count+ " "+ Box.colorName(color) +" boxes. "+ boxes.size() + " remain"; } public void resetBoxes() { boxes = new ArrayList(); int n = (int)(18 + 200*Math.random()) ; message ="Click any of these " + n + " boxes to remove that color, anywhere else to reset"; for (int i = 0; i < n; i++) { boxes.add(new Box(SIZE) ); } repaint(); } public ClickBoxes() // constructor { ArrayList boxes = new ArrayList(); message = ""; resetBoxes(); addMouseListener(this); } public void paintComponent(Graphics g) { setBackground(new Color(255,220,200) ); super.paintComponent(g); // Adjust location of boxes according to the current panel size int width = this.getWidth() - SIZE; for( int i = 0; i < boxes.size(); i++ ) { int x = (i) % (width/SIZE); //column int y = (i) / (width/SIZE); //row boxes.get(i).setLocation(SIZE/2 + x*SIZE, SIZE/2 + y*SIZE); } for( Box b:boxes) { b.draw(g); } g.setColor(Color.BLACK); g.drawString(message, 20, 20); } public static void main(String[] args) { JFrame window = new JFrame(); window.setSize(WIDTH, HEIGHT); Container c = window.getContentPane(); c.add(new ClickBoxes()); window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); window.setVisible(true); } public void mouseReleased(MouseEvent e) { int x = e.getX(); int y = e.getY(); for(Box b:boxes) { if (b.contains(x,y)) { remove(b.getColor()); repaint(); return; } } resetBoxes(); repaint(); } public void mousePressed(MouseEvent e) { } public void mouseEntered(MouseEvent e) { } public void mouseExited(MouseEvent e) { } public void mouseClicked(MouseEvent e) { } }