I'm creating a connect Four Game with GUI and I got stuck on Restarting the game. My goal is that when the user presses the Restart Button on MyBoard JPanel the game will restart. I'm using the mouseListener and I want to access the object panel from the child class MyBoard.
public class Mediator(){
public Mediator(){
MyBoard panel = new MyBoard();
JFrame board = new JFrame("Connect4");
board.setSize(728, 728);
board.setLocationRelativeTo(null);
board.add(panel);
board.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
board.setVisible(false);
board.setFocusable(true);
board.setResizable(false);
}
}
public class MyBoard extends JPanel implements MouseListener, MouseMotionListener {
public MyBoard( ) {}
@Override
public void mouseClicked(MouseEvent e) {
startX = e.getX();
startY = e.getY();
//Restart Button
if (startX > rectButton1.x && startX < rectButton1.x + rectButton1.width && startY > rectButton1.y
&& startY < rectButton1.y + rectButton1.height) {
//I'm stuck here
}
Use a reference to Mediator when you create MyBoard
public class Mediator(){
public Mediator(){
MyBoard panel = new MyBoard(this);
...
public class MyBoard extends JPanel implements MouseListener, MouseMotionListener {
private Mediator mediator;
public MyBoard(Mediator mediator) {
this.mediator = mediator;
...
Also you may have to move the construction of a new board to a method restart instead of doing it in Mediator constructor.
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.