简体   繁体   English

从子类访问父类对象

[英]Access Parent Class Object from a child class

I'm creating a connect Four Game with GUI and I got stuck on Restarting the game.我正在创建一个带有 GUI 的连接四游戏,但我被困在重新启动游戏上。 My goal is that when the user presses the Restart Button on MyBoard JPanel the game will restart.我的目标是当用户按下 MyBoard JPanel 上的重新启动按钮时,游戏将重新启动。 I'm using the mouseListener and I want to access the object panel from the child class MyBoard.我正在使用 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  
        }

Use a reference to Mediator when you create MyBoard创建 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;
        ...

Also you may have to move the construction of a new board to a method restart instead of doing it in Mediator constructor.此外,您可能必须将新板的构造移动到方法重新启动,而不是在 Mediator 构造函数中进行。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM