我正在创建一个带有GUI的连接四游戏,我一直在重启游戏。我的目标是当用户按下MyBoard JPanel上的重启按钮时,游戏将重启。我正在使用mouseListener,我想从子类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
}
答案 0 :(得分:1)
创建MyBoard时使用对Mediator的引用
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;
...
此外,您可能必须将新板的构造移至方法重启,而不是在Mediator构造函数中执行。