J2ME学习札记:TextBox与List综合应用,getSelectedIndex()和display.setCurrent(tb)用法
此前已经讲解了TextBox与List的应用,那么现在将有一个综合它们两个的程序,功能是选择了相应的list选项就能把当前的屏幕切换成对应的TextBox基本文本屏幕,其实用到的切换结束就是这个语句:display.setCurrent(想要实现的屏幕对象);然而怎样然按钮监听器知道你选择的是哪个候选项呢,可以用getSelectedIndex()来获得选择的选项序号:switch (((List)d).getSelectedIndex()),以下便给出源代码import javax.microedition.midlet.MIDlet;
import javax.microedition.midlet.MIDletStateChangeException;
import javax.microedition.lcdui.*;
public class ListControl extends MIDlet implements CommandListener {
private final static Command exitCommand = new Command("Exit",Command.EXIT,1);
private final static Command backCommand = new Command("back",Command.BACK,1);
private Display display;
private List mainList;
private TextBox tb;
public ListControl()
{
display = Display.getDisplay(this);
tb = new TextBox("Terry","9prior",15,0);
tb.addCommand(exitCommand);
tb.addCommand(backCommand);
tb.setCommandListener(this);
}
protected void startApp() throws MIDletStateChangeException
{
Image[] imageArray = null;
try{
Image icon = Image.createImage("/1.png");
imageArray = new Image[]{
icon,
icon,
icon
};
}catch (java.io.IOException err)
{
System.out.println("loan ...");
}
String[] stringArray = {
"choice 1",
"choice 2",
"choice 3"
};
mainList = new List("katrina",Choice.IMPLICIT,stringArray,imageArray);
mainList.addCommand(exitCommand);
mainList.setCommandListener(this);
display.setCurrent(mainList);
}
protected void destroyApp(boolean arg0) throws MIDletStateChangeException {
}
protected void pauseApp() {
}
public void commandAction(Command c, Displayable d)
{
if (d.equals(mainList)){ //用equals来判断当前display是什么
if (c == List.SELECT_COMMAND){
if (d.equals(mainList)){
switch (((List)d).getSelectedIndex()){/*用getSelectedIndex()来获得选择的选项序号*/
case 0:
tb.setString("Text A");
display.setCurrent(tb);
break;
case 1:
tb.setString("Text B");
display.setCurrent(tb);
break;
case 2:
tb.setString("Text C");
display.setCurrent(tb);
break;
}
}
}
}else
if(c == backCommand){
display.setCurrent(mainList);
}
}
}