-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