1
我有兩個類叫做Game.java
和KeyInput.java
。如何從Game.java
訪問int x和int y並在KeyInput.java
中使用?如何訪問不同類別的變量
Game.java
public class Game extends JFrame {
int x, y;
//Constructor
public Game(){
setTitle("Game");
setSize(300, 300);
setResizable(false);
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.addKeyListener(new KeyInput());
x = 150;
y = 150;
}
public void paint(Graphics g){
g.fillRect(x, y, 15, 15);
}
public static void main(String [] args){
new Game();
}
}
KeyInput.java
public class KeyInput extends KeyAdapter {
public void keyPressed(KeyEvent e) {
int keyCode = e.getKeyCode();
if(keyCode == e.VK_W)
y--; //Error here saying "y cannot be resolved to a variable"
}
}
非常感謝你! – Sean
嘿,沒問題! :) – ldmtwo