1

So I have a large grid of 289 rectangles (17x17) and I need some way to change each one's color when they are clicked without having to make 289 different event methods. The retangles are colored based on a pattern:

if(y%2==0){
    if(x%2==0)
        g2.setColor(Color.WHITE)
    else
        g2.setColor(Color.BLUE)
}else{
    if(x%2!=0)
         g2.setColor(Color.WHITE)
    else
         g2.setColor(Color.RED)
}

I don't have any idea where I should start other than creating an big ArrayList of positions for each rectangle and their colors (such as {{0,0,Color.WHITE},{x,0,Color.BLUE}...etc};). I would use a for loop to create each of the rectangles using their parameters, but I don't know how I would create the ArrayList and Event method to detect which, if any, rectangle was clicked. How do I go about this?

EDIT: I'm saying, how would I know which rectangle was clicked so I can change it's color? If it makes it easier, it's for a game where there are two players, red and blue. The board is made using the script above. When a player of a certain color clicks a white space the board changes that rectangles color to the players color, and that's where I have the trouble. I never have anyway to know when a player clicked one of the rectangles. How would I know when a player clicked a rectangle and how would I change it's color when clicked?

jocopa3
  • 796
  • 1
  • 10
  • 29

1 Answers1

2

Add an instance of the same MouseListener to each component as it is constructed. There's an example here that changes a circle's color when the mouse is pressed.

Addendum: Based on your revised question, GridButtonPanel shows how a component may know its own coordinates, as well as how to reference a component based on its grid coordinates.

a grid of colored circles

Community
  • 1
  • 1
trashgod
  • 203,806
  • 29
  • 246
  • 1,045
  • Thank you for your help! I'm fairly new to Java and only had experience with weak and dynamic programming languages like JavaScript and Lua, so moving to Java is a bit of a jump for me. – jocopa3 Mar 26 '12 at 02:51