I have a 2D Array of JButton 14x14 size. I painted the JButtons with random colors and I need to find the adjacent cells with the same color everytime I click on a JButton. Do you guys have any idea how to get the neighbors of a JButton cell with the same color? (Keep in mind,once it finds the neighbors, it should look for the neighbors' adjacents too).
Sounds like a simple recursion problem to me. I'm not familiar with Java, but since it's very similar to C#, so you should be able to understand it quite well.
List<Button> answer=new List<Button>();
private void ButtonClickEventHandler(object sender,EventArgs e)
{
//I'm assuming you have a location property in each individual button,
//and of course, the color.
search(sender);
}
private void search(Button bt)
{
int x=bt.x;
int y=bt.y;
bt.Visited=true;
answer.Add(bt);
if(x>0 && br[x-1][y].getColor()==bt.getColor() && !br[x-1][y].Visited) search(br[x-1,y]);
if(x<14 && br[x+1][y].getColor()==bt.getColor() && !br[x+1][y].Visited) search(br[x+1,y]);
if(y>0 && br[x][y-1].getColor()==bt.getColor() && !br[x][y-1].Visited) search(br[x,y-1]);
if(y<14 && br[x][y+1].getColor()==bt.getColor() && !br[x][y+1].Visited) search(b[x,y+1]);
}
The answer will be your answer! Excuse the pun!
public HashSet<JButton> lookForAdjancentButtons(int i, int j) {
HashSet<JButton> set = new HashSet<>();
set.add(board.getIndex(i, j));
adjacentButtons(board.getColor(i, j), set, i, j);
return set;
}
private void adjacentButtons(Color c, HashSet<JButton> set, int i, int j) {
helperMethod(c, set, i - 1, j);
helperMethod(c, set, i + 1, j);
helperMethod(c, set, i, j - 1);
helperMethod(c, set, i, j + 1);
}
private void helperMethod(Color c, HashSet<JButton> set, int i, int j) {
if(i < 0 || j < 0 || i >= 14 || j >= 14) {
return;
}
JButton b = board.getIndex(i, j);
if(board.getColor(i, j) != c) {
return;
}
if(!set.add(b)) {
return;
}
adjacentButtons(c, set, i, j);
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.