如何以LWUIT形式检测按键事件?

Sar*_*nan 4 lwuit key java-me lwuit-form

我用LWUIT包编写了简单的j2me程序.Form我在MIDLET类文件中添加了一个.假设,用户按一个键然后我想显示另一个Form.但是我无法在我的LWUIT中捕获关键事件Form.

这是我的代码snippt

import javax.microedition.midlet.*;
import com.sun.lwuit.*;
import com.sun.lwuit.events.*;


public class MultipleForm extends MIDlet  implements ActionListener{

    private Form mFirstForm, mSecondForm;

    public void startApp()
 {
      if (mFirstForm == null) 
     {
         Display.init(this);

        mFirstForm = new Form("First Form");
        Button button = new Button("Switch");
        button.addActionListener(this);        
        mFirstForm.addComponent(button);

        mSecondForm = new Form("Second Form");
        Button button2 = new Button("Switch");
        button2.addActionListener(this);
        mSecondForm.addComponent(button2);

        mFirstForm.show();

      }
    }

    protected void keyPressed(int key)
    {
        System.out.println("Key Pressed");

        if(key==52)
        {
          Form current = Display.getInstance().getCurrent();
          if (current == mFirstForm)
          {
             mSecondForm.show();
          }
          else if(current==mSecondForm)
          {
             mFirstForm.show();
          }
        }
    }

    public void pauseApp() {}

    public void destroyApp(boolean unconditional) {}
}
Run Code Online (Sandbox Code Playgroud)

Mun*_*n0n 5

要在LWUIT中捕获事件密钥,Form您需要使用Form.addGameKeyListener(here the key, here actionListener)

例如,使用Canvas类似地映射键Canvas.FIRE.

试着这样做.

  • 您可以覆盖表单中的keyPressed/release并获得相同的效果.我们建议始终使用keyReleased进行操作而不是keyPressed. (3认同)