Hey guys!
I have coded an applet that will show something like this (mines a different color):
The code below does WORK. The mouseListener part doesn't.
public class ColoredSquares extends JApplet implements MouseListener { Random rand = new Random(); private MouseEvent evt = null; private boolean isClicked; // declare instance variables // initialize instance variable with an array of Color objects Color [][] a; Color randC; int x, y; int myClickX; int myClickY; // generates a color public Color Color(Color randC) { // huge method, omitted to make code shorter } public void init () { // sets window size of the applet viewer setSize(800,800); // fill entire applet with background color setBackground(Color.BLACK); // fill array with 8x8 color objects a = new Color[8][8]; for (int x = 0; x < a.length; x++) for (int y = 0; y < a.length; y++) a[x][y] = Color(randC); // implement MouseListener interface this.addMouseListener(this); <--- I think this line is WRONG } // end init method public void paint(Graphics g) { // rectangle size is determined by applet size // leave space at the bottom to draw a string int rowHeight = (getHeight() / 8) - 5; int colWidth = (getWidth() / 8); // loop through each array object and paint a rectangle for (int row = 0; row < a.length; row++) { for (int col = 0; col < a.length; col++) { g.setColor(a[row][col]); g.fillRect(col*colWidth, row*rowHeight, colWidth, rowHeight ); } } // if mouseClicked is true, then change the color of the square that was clicked on if (evt != null && isClicked == true) { // if a square is clicked on // the square turns red g.setColor(Color.red); int col = 0; int row = 0; g.fillRect(col*colWidth, row*rowHeight, colWidth, rowHeight ); } } // end paint method public void mouseClicked(MouseEvent evt) { // save the evt pointer in my global variable this.evt = evt; // stores the current click of the mouse, X and Y position myClickX = evt.getX(); myClickY = evt.getY(); NOT sure what to do HERE V V below V V // if an array element is clicked // return isClicked = true // else // return isClicked = false repaint(); } // end mouseClicked method public void mouseExited(MouseEvent evt) {} public void mouseEntered(MouseEvent evt) {} public void mouseReleased(MouseEvent evt) {} public void mousePressed(MouseEvent evt) {} } // end class
What I want to happen is when I click on one of the squares in the applet, I want to change the color of the array element corresponding to that square to RED.
I don't believe any other method is to be added-- use the methods already stated. No JPanel recommendations please. I'm not supposed to use that.
I know that in my mouseListener I want to find WHICH index of the array was clicked. Then return that the click is true. In my paint, I want "if click is true, then set color to red, and paint that index". Or something like that...
Please at least give me an example of a mouseListener with a multidimensional array. >_<
Any help would be much appreciated.