Sunday, January 15, 2012

J2ME with LWUIT (Commands)

Definitely we may need to use commands because users must have a simple way to command our app. Though we can use buttons to get user commands, it may not be the best options. By using commands we can easily place the frequently used commands in our app.



Example :

package hello;

import com.sun.lwuit.Command;
import com.sun.lwuit.Display;
import com.sun.lwuit.Form;
import com.sun.lwuit.Image;
import com.sun.lwuit.Label;
import com.sun.lwuit.events.ActionEvent;
import com.sun.lwuit.events.ActionListener;
import com.sun.lwuit.layouts.BorderLayout;
import java.io.IOException;
import javax.microedition.midlet.*;

/**
 * @author Kanishka
 */
public class DemoUI extends MIDlet implements ActionListener{

    Label centerLabel;
    public void startApp() {
        Display.init(this);
        Form f = new Form("My LWUIT Demo");
        f.setLayout(new BorderLayout());

        Image img;
        Image imgSave;
        Image imgEdit;
        try {
            img = Image.createImage("/img/img.png");
            imgSave = Image.createImage("/img/save.png");
            imgEdit = Image.createImage("/img/edit.png");

            centerLabel = new Label("Center Label");
            centerLabel.setIcon(img);
            f.addComponent(BorderLayout.CENTER, centerLabel);
            f.addComponent(BorderLayout.NORTH, new Label("North Label"));

            f.addCommand(new Command("Exit",1));
            f.addCommand(new Command("Command2",2));
            f.addCommand(new Command("Command3",3));
            f.addCommand(new Command("Command4",4));
            f.addCommand(new Command("Command5",5));
            f.addCommand(new Command("Command6",imgEdit,6));
            f.addCommand(new Command("Command7",imgSave,7));
            f.show();

            f.setCommandListener(this);
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }

    public void pauseApp() {
    }

    public void destroyApp(boolean unconditional) {
    }

    public void actionPerformed(ActionEvent arg0) {
        int cmdId = arg0.getCommand().getId();
        switch(cmdId){
            case 1 : exit(); break;
            case 2 : sampleAction(); break;
        }
    }

    private void sampleAction(){
        this.centerLabel.setText("Command2 Acknowledged!");
    }

    private void exit() {
        destroyApp(true);
        notifyDestroyed();
    }
}
Screenshot :
Applet :

0 comments:

Post a Comment

 
© Copyright 2035 kani.stack.notez
Theme by Yusuf Fikri