-1
我传递从一个类中的一些坐标到另一个使用下面的代码问题设置实例变量
**编辑以显示更多细节
在class1的开始:
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);
}
}
}
从Class2中:
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 + " " +yCoordinate);
确定。
您需要展示更多的代码,因为这里没有什么看起来立刻就错了。 – 2012-04-12 01:21:41
当我尝试在另一个方法中使用xCoordinate或yCoordinate时,他们返回为0,我不明白如何: – JazziJeff 2012-04-12 01:32:43
@RST作为第一位评论者说,您需要发布更多代码。机会是您如何分配变量受范围的影响 - 但你没有向我们展示代码,所以我们不能告诉。 – 2012-04-12 01:34:12