import java.util.*; import javax.swing.*; import java.awt.*; import java.awt.event.*; @SuppressWarnings("serial") public class CellTester extends JPanel implements MouseListener, MouseMotionListener { private ArrayList cells; private String message, message2; public static final int SIZE = 75; public static final int WIDTH = 500; public static final int HEIGHT = 500; public static final int GAP =3; private Font font; public void resetCells() { int n = 5 ; cells = new ArrayList(n); int r = 50+(int)(Math.random()*205); int g = 50+(int)(Math.random()*205); int b = 50+(int)(Math.random()*205); message ="Try clicking on a cell to switch it on, click off a cell to reset them"; message2 = " Color is " + r + ", " + g + ", "+b; for (int i = 0; i < n; i++) { Cell c = new Cell(n*SIZE+(n*GAP), 120, SIZE , new Color(r,g,b) ); cells.add(c); } repaint(); } public CellTester() // constructor { message = ""; font = new Font("NewTimesRoman", Font.BOLD, 12); resetCells(); addMouseListener(this); addMouseMotionListener(this); } public void paintComponent(Graphics g) { setBackground(new Color(24,24,25) ); super.paintComponent(g); // Adjust location of boxes according to the current panel size int width = this.getWidth() - SIZE; for( int i = 0; i < cells.size(); i++ ) { Cell c = cells.get(i); int x = (i) % (width/SIZE); //column int y = (i) / (width/SIZE); //row c.setLocation(SIZE/2 + x*SIZE+x*GAP, SIZE/2 + y*SIZE+y*GAP); } for( Cell c:cells) { c.draw(g); } g.setColor(Color.WHITE); g.setFont(font); g.drawString(message, 20, 20); g.drawString(message2, 20, 220); } public static void main(String[] args) { JFrame window = new JFrame(); window.setSize(WIDTH, HEIGHT); Container c = window.getContentPane(); c.add(new CellTester()); window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); window.setVisible(true); } public void mouseReleased(MouseEvent e) { int x = e.getX(); int y = e.getY(); for(Cell c:cells) { if (c.contains(x,y)) { // This cell has been clicked. c.click(); repaint(); return; } } // If user didn't click on a tile, we reset the game resetCells(); repaint(); } public void mousePressed(MouseEvent e) { } public void mouseEntered(MouseEvent e) { } public void mouseExited(MouseEvent e) { } public void mouseClicked(MouseEvent e) { } public void mouseDragged(MouseEvent e) {} public void mouseMoved(MouseEvent e) { // hilight a tile if mouse is hovering int x=e.getX(); int y=e.getY(); //message = "("+x+", "+y+")"; for(Cell c: cells) c.setHighlight(c.contains(x, y)) ; repaint(); } }