【问题标题】:Java - Sending values from SubclassJava - 从子类发送值
【发布时间】:2013-04-28 19:09:33
【问题描述】:

我需要一些帮助,将值从我的子类发送到我的超类。

Public class A {

protected int GameSize;

public void setButtons(){   
        for(int row = 0; row < GameSize; row++) {
            for(int col = 0; col < GameSize; col++) {       
                buttons[row][col] = new PlayerButton();
                buttons[row][col].button.addActionListener((ActionListener) this);
                buttons[row][col].player = row+""+col;
                buttons[row][col].button.setIcon(new ImageIcon("src/img/empty.png"));
                box.add(buttons[row][col].button);
            }
        }   

        box.setVisible(true);   

    }

}



public class B extends A {

    public void actionPerformed(ActionEvent a) {
      Object source = a.getSource();
      JButton pressedButton = (JButton)source;  
      if(pressedButton.getText() == "Start Game") {

       GameSize = Integer.parseInt(GameSizeBox.getSelectedItem().toString().replaceAll("x.*","")); 
       if((setplayername1.getText().length() > 0) && (setplayername2.getText().length() > 0)){
        StartNewGame(setplayername1.getText(), setplayername2.getText(), GameSize);
       }
      }
      if(pressedButton.getText() == "Exit") {
       System.exit(0);
      }

     } 
  }

我希望能够在 A 类中使用我在 B 类中更改的 GameSize。如何解决这个问题?澄清一下,我在 A 类中有一个受保护的变量 ( GameSize ),我在 B 类中更改了这个变量,我想在 A 类的 forloops 中“重用”更改后的 GameSize。

谢谢。

【问题讨论】:

  • B 类中更改 GameSize 后,在 A 类中调用 setButtons 应该反映修改后的 GameSize。这不是你看到的吗?
  • 如果我尝试调用 GameSize,则它为空。
  • int 不能为空
  • 向我们展示 SSCCE。您那里的代码无法编译,并且无法清楚地向您解释它的行为方式。我唯一能做的是在调用 actionPerformed() 方法之前调用 setButtons() 方法,从而看到 GameSize 的初始值。此外,请尊重 Java 命名约定。
  • 抱歉代码不清楚。但你完全正确,setButtons 在 actionPerformed 之前被调用。谢谢你:)

标签: java subclass superclass


【解决方案1】:

如果我理解,您想在 B 类更改后更改 A 类的值。 在创建对象 A 之后:

A Class_a = new A();
Class_a.GameSize= /value from B/

您还可以在 A 类中构建构造函数,在 GameSize 中设置值,并使用 super() 在 B 类中调用 A类

A(int a){
GameSize=a;
}

在B级

super(/* here new value */)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-10-26
    • 2016-03-16
    • 1970-01-01
    • 1970-01-01
    • 2019-04-24
    • 1970-01-01
    • 1970-01-01
    • 2020-01-17
    相关资源
    最近更新 更多