【发布时间】: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