How to detect key pressed event in LWUIT form?

2.4k views Asked by At

I have written simple j2me program with LWUIT package.I have added one Form in my MIDLET class file. Suppose,user press a key then I want to show another Form.But I couldn't be able to capture key event in my LWUIT Form.

This is my code 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

There are 1 answers

3
Mun0n On BEST ANSWER

To capture the event key in a LWUIT Form you need to use Form.addGameKeyListener(here the key, here actionListener)

The keys are mapped using Canvas like Canvas.FIRE for example.

Try to do that.