从 KeyListener 访问在另一个 class 中创建的对象
Access an object created in another class from a KeyListener
我正在尝试弄清楚如何从密钥侦听器 class 更改在我的主程序 class 中创建的对象的字段。我制作了一个名为 KeyMaster 的 class,它所做的只是通过在主 class 中创建的事件队列监听键盘输入。当我向上、向左、向下、向右推时,我希望能够通过 KeyMaster class 更改 x 和 y 坐标。问题是我无法从 KeyListener class 访问 Ship 对象。请帮忙。 :)
public class TheMage extends JFrame
{
public static void main(String[] args)
{
TheMage Main = new TheMage();
Player Ship = new Player(50,50);
KeyMaster KeyEvnt = new KeyMaster();
EventQueue.invokeLater
(new Runnable()
{
@Override
public void run()
{
Main.addKeyListener(KeyEvnt);
Main.setFocusable(true);
Main.setVisible(true);
}
}
);
}
}
public class Player {
int x;
int y;
public Player(int x, int y) {
this.x = x;
this.y = y;
}
}
public class KeyMaster implements KeyListener {
public KeyMaster() {
}
@Override
public void keyTyped(KeyEvent ke) {
System.out.println("Hello - Type");
}
@Override
public void keyPressed(KeyEvent ke) {
System.out.println("Hello - Press");
}
@Override
public void keyReleased(KeyEvent ke) {
System.out.println("Hello - Rel");
}
}
您可以使飞船静止。
public class TheMage extends JFrame {
private static Player Ship = new Player(50,50);
...
@Override
public void keyPressed(KeyEvent ke) {
TheMage.Ship //blah blah blah
}
此外,请遵循 Java 命名约定。
在KeyMaster
class中创建一个Player
字段,通过构造函数将当前玩家注入到该字段中:
private Player player;
KeyMaster(Player player) {
this.player = player;
}
然后在main
方法中你可以创建KeyMaster
如下:
KeyMaster KeyEvnt = new KeyMaster(Ship);
我正在尝试弄清楚如何从密钥侦听器 class 更改在我的主程序 class 中创建的对象的字段。我制作了一个名为 KeyMaster 的 class,它所做的只是通过在主 class 中创建的事件队列监听键盘输入。当我向上、向左、向下、向右推时,我希望能够通过 KeyMaster class 更改 x 和 y 坐标。问题是我无法从 KeyListener class 访问 Ship 对象。请帮忙。 :)
public class TheMage extends JFrame
{
public static void main(String[] args)
{
TheMage Main = new TheMage();
Player Ship = new Player(50,50);
KeyMaster KeyEvnt = new KeyMaster();
EventQueue.invokeLater
(new Runnable()
{
@Override
public void run()
{
Main.addKeyListener(KeyEvnt);
Main.setFocusable(true);
Main.setVisible(true);
}
}
);
}
}
public class Player {
int x;
int y;
public Player(int x, int y) {
this.x = x;
this.y = y;
}
}
public class KeyMaster implements KeyListener {
public KeyMaster() {
}
@Override
public void keyTyped(KeyEvent ke) {
System.out.println("Hello - Type");
}
@Override
public void keyPressed(KeyEvent ke) {
System.out.println("Hello - Press");
}
@Override
public void keyReleased(KeyEvent ke) {
System.out.println("Hello - Rel");
}
}
您可以使飞船静止。
public class TheMage extends JFrame {
private static Player Ship = new Player(50,50);
...
@Override
public void keyPressed(KeyEvent ke) {
TheMage.Ship //blah blah blah
}
此外,请遵循 Java 命名约定。
在KeyMaster
class中创建一个Player
字段,通过构造函数将当前玩家注入到该字段中:
private Player player;
KeyMaster(Player player) {
this.player = player;
}
然后在main
方法中你可以创建KeyMaster
如下:
KeyMaster KeyEvnt = new KeyMaster(Ship);