在我的 J2ME 应用程序中,我只想在用户更改任何控件的状态时显示一个警告对话框,即当用户使用表单的任何控件然后尝试取消表单而不保存键入的数据时。
例如,如果用户在 1-2 个文本字段中键入并尝试取消表单而不将键入的数据保存到数据库中,则在所有 5-6 个表单控件中。然后应显示一个警告框,并显示消息“保存更改?” 用Yes, No
命令。
这个怎么做?
这是我的代码,它没有给出预期的结果:
import javax.microedition.lcdui.*;
import javax.microedition.midlet.*;
public class InformAboutStatechange extends MIDlet implements CommandListener
{
Display d;
Form frm;
Command Save, Cancel, CancelAlrtYes, CancelAlrtNo, CancelAlrtBack;
TextField Name, Age;
Alert CancelAlrt;
boolean StateChange = false;
public InformAboutStatechange()
{
d = Display.getDisplay(this);
frm = new Form("");
Save = new Command("Save", Command.SCREEN, 1);
Cancel = new Command("Cancel", Command.CANCEL, 2);
Name = new TextField("Name", "", 10, 0);
Age = new TextField("Age", "", 10, 0);
frm.addCommand(Save);
frm.addCommand(Cancel);
frm.append(Name);
frm.append(Age);
frm.setCommandListener(this);
d.setCurrent(frm);
}
public void startApp()
{
}
public void pauseApp()
{
}
public void destroyApp(boolean unconditional)
{
}
public void commandAction(Command c, Displayable dispable)
{
if (c == Cancel) {
CancelAlrt = new Alert("Application Alert","Save Changes???",null,null);
CancelAlrtYes = new Command("Yes",Command.SCREEN, 1);
CancelAlrtNo = new Command("No", Command.SCREEN | Command.CANCEL, 2);
CancelAlrtBack = new Command("Back", Command.BACK, 3);
CancelAlrt.addCommand(CancelAlrtYes);
CancelAlrt.addCommand(CancelAlrtNo);
CancelAlrt.addCommand(CancelAlrtBack);
frm.setItemStateListener(new ItemStateListener()
{
public void itemStateChanged(Item item)
{
item.notifyStateChanged();
if (item == Name) {
if (item == Age) {
StateChange = true;
} else {
StateChange = false;
}
}
}
});
if (StateChange == true) {
d.setCurrent(CancelAlrt);
CancelAlrt.setCommandListener(new CommandListener()
{
public void commandAction(Command cmd, Displayable dispable)
{
if (cmd == CancelAlrtYes) {
d.setCurrent(frm);
} else if (cmd == CancelAlrtNo) {
d.setCurrent(frm);
} else if (cmd == CancelAlrtBack) {
d.setCurrent(frm);
}
}
});
} else {
destroyApp(true);
notifyDestroyed();
}
}
}
}