我创建了一个带有str 1和str 2作为StringItem的Form,并将它们添加到Form上 然后我向str1和str2添加了addCommand()方法,当我点击Next按钮时,它应该在单击类别1时显示类别1,当单击类别2时显示类别2 StringItem。 请提出解决方案 我应该在Command Action()方法的循环中写什么,这样当我点击str1时它应该显示类别1,何时显示在str2 ...类别2?
代码如下,上面的问题是commandAction
方法
import javax.microedition.lcdui.Alert;
import javax.microedition.lcdui.AlertType;
import javax.microedition.lcdui.Command;
import javax.microedition.lcdui.CommandListener;
import javax.microedition.lcdui.Display;
import javax.microedition.lcdui.Displayable;
import javax.microedition.lcdui.Form;
import javax.microedition.lcdui.StringItem;
import javax.microedition.midlet.MIDlet;
import javax.microedition.midlet.MIDletStateChangeException;
public class Menu extends MIDlet implements CommandListener {
Command Next ;
Display display;
Form form;
StringItem str1,str2;
public Menu() {
// TODO Auto-generated constructor stub
str1=new StringItem("1. ", "Category 1");
str2=new StringItem("2.", "Category 2");
form=new Form("Menu");
form.append(str1);
form.append(str2);
Next=new Command("Next",Command.SCREEN, 1);
str1.addCommand(Next);
str2.addCommand(Next);
form.addCommand(Next);
form.setCommandListener(this);
}
protected void destroyApp(boolean arg0) throws MIDletStateChangeException {
// TODO Auto-generated method stub
}
protected void pauseApp() {
// TODO Auto-generated method stub
}
protected void startApp() throws MIDletStateChangeException {
// TODO Auto-generated method stub
display=Display.getDisplay(this);
display.setCurrent(form);
}
public void commandAction(Command c, Displayable d) {
// TODO Auto-generated method stub
if(c==Next)
{
if(/* What should I write here? */)
{
Alert alert=new Alert(null, "This is ", null, AlertType.INFO);
display.setCurrent(alert, form);
}
}
}
}
答案 0 :(得分:1)
只有Form需要Next命令,str1和str2不需要。实际上,您可以拥有一个包含类别的列表。所以在你的Menu()构造函数
中Public Menu() {
display = Display.getDisplay(this);
// Create a multiple choice list
lsPrefs = new List("Categories", List.MULTIPLE);
// Append options, with no associated images
lsPrefs.append("Category-1", null);
lsPrefs.append("Category-2", null);
cmNext = new Command("Next", Command.SCREEN,2);
// Add commands, listen for events
lsPrefs.addCommand(cmNext);
lsPrefs.setCommandListener(this);
}
并且在commandAction类中,您可以访问由
选择的类别 public void commandAction(Command c, Displayable s){
if (c == cmNext)
{
boolean selected[] = new boolean[lsPrefs.size()];
// Fill array indicating whether each element is checked
lsPrefs.getSelectedFlags(selected);
for (int i = 0; i < lsPrefs.size(); i++){
if(selected[i])
Alert(....);
}
}
答案 1 :(得分:0)
尝试使用ChoiceGroup - 以下是如何使用它的示例http://www.java-tips.org/java-me-tips/midp/how-to-use-choicegroup-in-j2me.html