Sunday, June 20, 2010

LWUIT: Button

Example of using Button of LWUIT.

In order to handle the action trigged by a button, a class(it is "this" in this case) implements actionPerformed() have to be set as listener by the method addActionListener().

LWUIT: Button

import java.io.IOException;
import javax.microedition.midlet.*;

import com.sun.lwuit.*;
import com.sun.lwuit.events.*;
import com.sun.lwuit.plaf.Border;

public class HelloMIDlet extends MIDlet implements ActionListener {

Form f;
Command exitCommand;
Button buttonTextOnly, buttonImage, buttonTextAndImage;

public void startApp() {
Display.init(this);

f = new Form("Hello, MIDlet in LWUIT!");



buttonTextOnly = new Button("I'm Button");
buttonTextOnly.getStyle().setBorder(Border.createEtchedRaised());
buttonTextOnly.getSelectedStyle().setBgColor(0xC0C0C0);
f.addComponent(buttonTextOnly);

buttonImage = null;
try {
buttonImage = new Button(Image.createImage("/java.png"));
}
catch (IOException ex) {
ex.printStackTrace();
}
buttonImage.getStyle().setBorder(Border.createLineBorder(5, 0xA0A0A0));
buttonImage.getSelectedStyle().setBgColor(0xC0C0C0);
f.addComponent(buttonImage);

buttonTextAndImage = new Button();
buttonTextAndImage.setText("Button with Text and Image");
try {
buttonTextAndImage.setIcon(Image.createImage("/java.png"));
} catch (IOException ex) {
ex.printStackTrace();
}
buttonTextAndImage.getSelectedStyle().setBgColor(0xC0C0C0);
f.addComponent(buttonTextAndImage);

f.show();

exitCommand = new Command("Exit");
f.addCommand(exitCommand);
f.setCommandListener(this);

buttonTextOnly.addActionListener(this);
buttonImage.addActionListener(this);
buttonTextAndImage.addActionListener(this);

}

public void pauseApp() {}

public void destroyApp(boolean unconditional) {}

public void actionPerformed(ActionEvent ae) {
//notifyDestroyed();

Command aeCommand = ae.getCommand();
Object aeSource = ae.getSource();

if (aeCommand == exitCommand){
notifyDestroyed();
}

if(aeSource == buttonTextOnly){
buttonTextOnly.setText("I have been Pressed");
f.repaint();
}
else if(aeSource == buttonImage){
buttonImage.setText("I have been Pressed");
f.repaint();
}
else if(aeSource == buttonTextAndImage){
buttonTextAndImage.setText("I have been Pressed");
f.repaint();
}
}
}