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

时间:2012-01-11 11:05:31

标签: java-me key lwuit lwuit-form

我用LWUIT包编写了简单的j2me程序。我在MIDLET类文件中添加了一个Form。假设,用户按一个键然后我想显示另一个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) {}
}

1 个答案:

答案 0 :(得分:5)

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

使用Canvas来映射密钥,例如Canvas.FIRE

尝试这样做。