简体   繁体   English

如何使用键侦听器调用类?

[英]How do I call a class using a key listener?

I am trying to have a window pop up when key 1 is pressed and a separate window when key 2 is pressed. 我试图在按下键1时弹出一个窗口,并在按下键2时弹出一个单独的窗口。

    public void keyPressed(KeyEvent e)
    {

          if(e.getKeyCode() == KeyEvent.VK_1)
        {
          TicTacToeDriver tic = new TicTacToeDriver();
          PointCounter();
        }

        else if(e.getKeyCode() == KeyEvent.VK_2)
        {
            HangmanDriver hang = new HangmanDriver();
            PointCounter();
        }
    }

    public void keyReleased(KeyEvent e)
    {
        //do nothing
    }

    public void keyTyped(KeyEvent e)
    {
        //do nothing
    }

The tic tac toe and hangman games were created by two separate people and the programmers created their own driver. 井字游戏和子手游戏由两个不同的人创建,程序员创建了自己的驱动程序。

Solution: 解:

I am assuming that the programmers are familiar with java oriented programming... 我假设程序员熟悉面向Java的编程...

Thus, You would just create a new object of one of the games. 因此,您只需创建其中一个游戏的新对象。

Hangman h = new Hangman();
or
Tick h = new Tick();
Tick.start() //depending on their code.

If you are running a Jframe... you would need to 如果您正在运行Jframe ...,则需要

(insert object name).setVisible(true);

Since you mentioned that they have drivers I assume that they use main methods instead of constructors even though the code you provided creates objects of the classes. 自从您提到它们具有驱动程序以来,即使您提供的代码创建了类的对象,我也假定它们使用主方法而不是构造函数。

Thus, when the button is clicked or key is pressed.. Just call the main method of the driver class. 因此,当单击按钮或按下键时。只需调用驱动程序类的main方法。

   hangman.main(null); //this is a terrible way to do it btw.

I also recommend using KeyBindings API instead of keylistener as keybindings does not require focus... which could also be problem. 我还建议使用KeyBindings API而不是keylistener,因为键绑定不需要关注...这也可能是问题。

Another problem would be.. 另一个问题是

this.addKeyListener(this); this.addKeyListener(this);

You have to add the keylistener to the component. 您必须将侦听器添加到组件。 But, this is where problems arise as you are using keylistener.. Your JComponent that you added the KeyListener to might not have focus. 但是,这就是您使用keylistener时出现问题的地方。您添加了KeyListener的JComponent可能没有焦点。 Thus, the action wont fire till the component has focus and an action is triggered. 因此,在组件获得焦点并触发动作之前,不会触发该动作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM