Java 问题设置实例变量
我使用以下代码将一些坐标从一个类传递到另一个类 **编辑以显示更多细节 在第1课开始时:Java 问题设置实例变量,java,variables,parameters,Java,Variables,Parameters,我使用以下代码将一些坐标从一个类传递到另一个类 **编辑以显示更多细节 在第1课开始时: public class BattleGui implements ActionListener { private int xCoordinate; private int yCoordinate; public void coordinateHandler(int xCoord, int yCoord) { xCoordinate=xCoord;
public class BattleGui implements ActionListener {
private int xCoordinate;
private int yCoordinate;
public void coordinateHandler(int xCoord, int yCoord) {
xCoordinate=xCoord;
yCoordinate=yCoord;
System.out.println("Coordinates Received "+xCoord + " " +yCoord);
System.out.println("Test "+xCoordinate + " " +yCoordinate);
}
public void actionPerformed(ActionEvent e) {
String classname = getClassName(e.getSource());
JComponent component = (JComponent)(e.getSource());
cellState cs = new cellState();
if (classname.equals("JMenuItem")) {
JMenuItem menusource = (JMenuItem)(e.getSource());
String menutext = menusource.getText();
// Determine which menu option was chosen
if (menutext.equals("Load Game")) {
/* BATTLEGUI Add your code here to handle Load Game **********/
System.out.println(cs.turnFeedback());
LoadGame();
}
else if (menutext.equals("Save Game")) {
/* BATTLEGUI Add your code here to handle Save Game **********/
SaveGame();
}
else if (menutext.equals("New Game")) {
/* BATTLEGUI Add your code here to handle Save Game **********/
NewGame();
}
}
// Handle the event from the user clicking on a command button
else if (classname.equals("JButton")) {
JButton button = (JButton)(e.getSource());
int bnum = Integer.parseInt(button.getActionCommand());
int row = bnum / GRID_SIZE;
int col = bnum % GRID_SIZE;
//col=yCoord;
//row=xCoord;
//System.out.println(e.getSource());
//System.out.println(bnum / GRID_SIZE);
fireShot(row, col);
if (row==xCoordinate){
if (col==yCoordinate){
button.setBackground(cellColour[cs.turnFeedback()]);
}
else {
//Remember to change the 1 to whatever is reported back from cell class cell state
//button.setBackground(cellColour[cs.turnFeedback()]);
button.setBackground(Color.BLUE);
}
}
else {
button.setBackground(Color.BLUE);
}
}
}
第2类:
public void shipDeploy() {
int gridLength;
int lengthDraw;
int winningNumbers = 0;
int xCoord;
int yCoord;
xCoord=99;
yCoord=100;
System.out.println(xCoord + "\n" + yCoord);
BattleGui bGui = new BattleGui();
//Passing the coordinates back to the battlegui coordinate handler class
bGui.coordinateHandler(xCoord, yCoord);
}
这会将这两个值传递给第一个类中的坐标处理程序方法
在这个类中,我有一个xCoordinate变量在各种方法中使用,问题是我似乎无法设置它,0总是在xCoordinate和yCoordinate的这个方法之外返回,我不明白为什么,因为它们在
System.out.println(“Test”+xCoordinate+”行中似乎是正常的+协调)上面的代码>。我自己刚刚解决了这个问题,非常简单,actionlistener基本上是在解释零值的每个“事件”上重新实例化变量,只要我将这个过程带到监听器之外,它就工作了,并按预期设置了值。谢谢大家的支持,希望这能对大家有所帮助 您需要显示更多的代码,因为这里没有什么看起来会立即出错的地方。当我稍后在另一个方法中尝试使用xCoordinate或yCoordinate时,它们将返回为0,我不明白如何返回:(@RST正如第一位评论者所说,你需要发布更多的代码。很可能你分配变量的方式会受到作用域的影响-但你没有向我们展示该代码,所以我们无法判断。我猜你有变量名阴影,但在我们看到代码之前,谁知道呢。你可能正在使用像C这样的语言where parameter这些是参考号吗?