4

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) {}
}
Mun0n
  • 4,438
  • 4
  • 28
  • 46
Saravanan
  • 11,372
  • 43
  • 143
  • 213

1 Answers1

5

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.

Mun0n
  • 4,438
  • 4
  • 28
  • 46
  • We need to add game key listener for each and every key that we pressed right... In LCDUI,we just overridding keyPressed(int key) and within that method,we are checking the key code to know which key is pressed.So, Is there any generic mechanism in LWUIT like in LCDUI? – Saravanan Jan 12 '12 at 04:04
  • 3
    You can override keyPressed/release in the form and get the same effect. We suggest always using keyReleased for actions and not keyPressed. – Shai Almog Jan 12 '12 at 06:46
  • Any particular reason for this suggestion? – Nitesh Verma Oct 29 '13 at 11:47