Reputation: 319
I am currently building a simple minesweeper game for a school project, in which every field is an instance of the Field class which inherits JButton. Here's (most of) the class in its current state:
public class Field extends JButton implements MouseListener {
public Field() {
super(" ");
setFocusable(false);
addMouseListener(this);
setFont(new Font("sans serif", Font.PLAIN, 20));
}
@Override
public void mouseClicked(MouseEvent me) {
//...
}
}
These fields then basically get added to a MineField object, which inherits JPanel. Here's the code for that, too:
class MineField extends JPanel {
Field[][] fields;
public MineField(int x, int y, int m) {
fields = new Field[x][y];
setLayout(new GridLayout(x, y));
for (int i = 0; i < x; i++) {
for(int j = 0; j < y; j++) {
fields[i][j] = new Field();
add(fields[i][j]);
}
}
//...
}
}
The size of the minefields are arbitrary, and are generated according the what difficulty the user chooses from the JMenuBar, with these methods:
private void startBeginner() { startGame(8, 8, 10); }
private void startIntermediate() { startGame(16, 16, 40); }
private void startAdvanced() { startGame(16, 30, 99); }
private void startGame(int x, int y, int m) {
if(mineField != null) {
remove(mineField);
}
mineField = new MineField(x, y, m);
add(mineField, BorderLayout.CENTER);
// ...
}
Most of what I created for now seems to work, with one exception. That being when I want to start a new game of the same difficulty of my current one. What happens is that all the fields disappear form the window, which has a blank MineField (although I'm not sure, that might not even be there, too). How could I solve this issue?
Upvotes: 0
Views: 50
Reputation: 1627
This works for me:
When you want to remove the old board JPanel, and create a new one. First, remote it by calling the container panel (its parent)
parent.removeAll()
Now, addyour new board JPanel to parent JPanel like you did:
parent.add(mineField, BorderLayout.CENTER);
Then, by using the JFrame methods, refresh GUI by 2 methods one by one:
this.revalidate();
this.repaint();
Upvotes: 1