ChoiceGroup的功能与List相近,只不过是多了个Item控件,其构造方法:ChoiceGroup(标题,类型,String[],Image[]),在此程序中有个值得主题的地方:textfield.setString(group.getString(group.getSelectedIndex())); ,此句group.getSelectedIndex()取得group第几个内容,然后group.getString转成文字并且textfield.setString显示出来,够详细了吧呵呵,以下给出完整程序:
import javax.microedition.midlet.MIDlet;
import javax.microedition.midlet.MIDletStateChangeException;
import javax.microedition.lcdui.*;
public class ChoiceGroupDemo extends MIDlet implements CommandListener,ItemStateListener {
private Command exitCommand = new Command("Eixt",Command.EXIT,1);
private Display display;
private Form mainForm;
private TextField textfield;
private ChoiceGroup group;
public ChoiceGroupDemo() {
mainForm = new Form("Choice Group");
//图片数组
Image[] imageArray = null;
try{
Image icon = Image.createImage("/1.png");
imageArray = new Image[]{icon,icon,icon,icon};
}catch(java.io.IOException err){System.out.println("Image err...");}
String[] stringArray ={"选项A","选项B","选项C","选项D"};
//创建Pop-Up类型
group = new ChoiceGroup("Pop-Up",ChoiceGroup.POPUP,stringArray,imageArray);
textfield = new TextField("当前的选项为:","选项A",20,TextField.ANY);
//可以添加控件了
mainForm.append(group);
mainForm.append(textfield);
mainForm.addCommand(exitCommand);
mainForm.setCommandListener(this);
mainForm.setItemStateListener(this); //设置了监听器
}
protected void destroyApp(boolean arg0) throws MIDletStateChangeException {
}
public void commandAction(Command c, Displayable d) { //处理Command事件
if(c == exitCommand)
{
try {
destroyApp(false);
} catch (MIDletStateChangeException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
notifyDestroyed();
}
}
public void itemStateChanged(Item item) {
if (item instanceof ChoiceGroup)
{
textfield.setString(group.getString(group.getSelectedIndex())); //本程序重点!取得并更新内容
/*TextBox tb = new TextBox("new","superise",15,0);
display.setCurrent(tb);*/ //这个是可以触发屏幕的更新
}
}
protected void pauseApp() {
}
protected void startApp() throws MIDletStateChangeException {
display = Display.getDisplay(this);
display.setCurrent(mainForm);
}
}
