i need to create a domino-like game that has Tiles with each of it’s sides containing 3 integers, and, given a random tile, i can place a new square next to it only if the integers match. I use a grid of tiles, gamePanel, to represent the game.
In a class that extends JFrame, i have a nested class that extends JPanel and uses a square GridLayout , i also have a grid of JPanels that will associate each JPanel with a tile from gamePanel that will display it. since gamePanels is bigger i will start from a (x,y) and finish in (x+n,y+n). I also added a mouseListner to each tile that has a non-null neighbor.
here is the code to show the grid of panels.
public void update(){
game.afficher();
reset();
for(int i=0;i<gamePanels.length;i++){
for (int j =0 ; j < gamePanels[i].length; j++) {
if(!game.valid(i+x))throw new ArrayIndexOutOfBoundsException(i+x);
if(!game.valid(j+y))throw new ArrayIndexOutOfBoundsException(j+y);
if(game.table[i+x][j+y]!=null){
gamePanels[i][j]=affiche(game.table[i+x][j+y]);
}else if(game.voisin( i+x,j+y)){
gamePanels[i][j]=addVoisin(i+x,j+y);
}else {
JPanel carre=new JPanel();
// Border blackline = BorderFactory.createLineBorder(Color.black);
carre.setSize(bigSquare());
gamePanels[i][j]=carre;
}
this.add(gamePanels[i][j]);
}
}
}
public JPanel addVoisin(int x, int y){
Border shadow = BorderFactory.createLineBorder(Color.GRAY, 5);
JPanel panel=new JPanel();
panel.setSize(bigSquare());
panel.setBorder(new CompoundBorder(shadow, new EmptyBorder(1, 1,1,1)));
panel.addMouseListener(new MouseInputListener() {
@Override
public void mouseClicked(MouseEvent e) {
try {
System.out.println("("+x+","+y+"))");
Grid.this.game.place(x, y, Grid.this.players.get(Grid.this.playerIndex), Grid.this.players.get(Grid.this.playerIndex).current);
if(game.gameFinished()){
endGame();
}
players.get(playerIndex).give(null);
playerIndex=(playerIndex+1) % players.size();
players.get(playerIndex).give(game.pop());
update();
menu.update(players.get(playerIndex));
} catch (Exception exception) {
exception.printStackTrace();
JOptionPane.showMessageDialog(null, "Placement Invalide");
}
}
@Override
public void mousePressed(MouseEvent e) {}
@Override
public void mouseReleased(MouseEvent e) {}
@Override
public void mouseEntered(MouseEvent e) {}
@Override
public void mouseExited(MouseEvent e) {}
@Override
public void mouseDragged(MouseEvent e) {}
@Override
public void mouseMoved(MouseEvent e) {}
});
return panel;
}
And this is the code to
it seemes that instead of updating the main JPanel, it adds a new one next to it:
initial JPanel, i clicked on the left square, and this is what happens.
i wanted this to happen this
Fares Boudelaa is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
1