7

In an actionListener for a button we would like to create a Form on the fly.

Eg Something like

Button b = new Button("Clickme");
b.setActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent evt) {
        Form f = new Form();
        Container c = new Container();
        ...
        f.addComponent(c);
        f.show();
    }
});

Which works fine..... but "back" button will not work

Does anyone know the correct way of implementing a dynamic form in an actionListener, or jumping to a predefined form through and action Listener?

Thanks

James

Megachip
  • 319
  • 3
  • 11
jamesarbrown
  • 213
  • 3
  • 7

2 Answers2

4

You need to create a back command and associate it with the form:

Command back = new Command("Back") {
     public void actionPerformed(ActionEvent ev) {
         // notice that when showing a previous form it is best to use showBack() so the 
         // transition runs in reverse
         showPreviousForm();
     }
};
f.setBackCommand(back);

You can see this in the kitchen sink demo which is entirely hand coded.

Shai Almog
  • 49,879
  • 5
  • 30
  • 57
  • 1
    Hi Shai, Thanks for reply. Not having much luck. I have a list in a form. Each list item has a button, that button has an actionListener which generates a form on the fly. I can drill back to the listrenderer class, but calling getComponentForm() at that point gets an NPE..... so not sure how to get the parentForm to set the parentForm.showBack(). – jamesarbrown Sep 04 '12 at 20:31
  • 1
    You need to generate the previous form again, that's exactly what we do in the GUI builder. Alternatively you can keep form instances in RAM with the obvious memory cost implications. – Shai Almog Sep 05 '12 at 06:17
  • Ok, did not realise the old form object is released from memory when a new one is generated. Will have a think how to restructure in a cyclic way. – jamesarbrown Sep 06 '12 at 18:59
0

You could also giving the form as Parameter

chooseDB(c.getComponentForm());

private void chooseDB(final Form main) {
    Form f = new Form("Choose a Database");
    ...
    Command backCommand = new Command("Back") {
        public void actionPerformed(ActionEvent ev) {
            main.showBack();
        }};
    f.addCommand(backCommand);
    f.setBackCommand(backCommand);
    f.show();
}

So for your example:

Button b = new Button("Clickme");
b.setActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent evt) {
        Form f = new Form();
        Container c = new Container();
        Command backCommand = new Command("Settings") {
        public void actionPerformed(ActionEvent ev) {
            b.getComponentForm().showBack();
        }};
    f.addCommand(backCommand);
    f.setBackCommand(backCommand);
        f.addComponent(c);
        f.show();
    }
});

Shai, please correct this, if i did anything wrong. Thx.

Megachip
  • 319
  • 3
  • 11