Java ME中的是/否对话框

时间:2020-03-05 18:51:36  来源:igfitidea点击:

我正在寻找在Java ME midlet中使用的yes / no对话框的简单解决方案。我想这样使用它,但是其他方法也不错。

if (YesNoDialog.ask("Are you sure?") == true) {
  // yes was chosen
} else {
  // no was chosen
}

解决方案

回答

我没有用Java ME编程,但是我在它的可选包参考中找到了
高级图形和用户界面API,它与Java SE API一样,用于通过JOptionPane类创建这些对话框

int JOptionPane.showConfirmDialog(java.awt.Component parentComponent, java.lang.Object >message, java.lang.String title, int optionType)

回报可能是
JOptionPane.YES_OPTION,JOptionPane.NO_OPTION,JOptionPane.CANCEL_OPTION ...

回答

我们需要一个警报:

An alert is a screen that shows data to the user and waits for a certain period of time before proceeding to the next Displayable. An alert can contain a text string and an image. The intended use of Alert is to inform the user about errors and other exceptional conditions.

使用2条命令(情况为"是" /"否"):

If there are two or more Commands present on the Alert, it is automatically turned into a modal Alert, and the timeout value is always FOREVER. The Alert remains on the display until a Command is invoked.

这些是MIDP 1.0及更高版本支持的内置类。同样,代码段将永远无法使用。这样的API将需要阻塞调用线程,以等待用户选择并应答。这恰好与基于回调和委托的MIDP的UI交互模型相反。我们需要提供自己的类,实现CommandListener,并准备用于异步执行的代码。

这是一个基于Alert的(未经测试!)示例类:

public class MyPrompter implements CommandListener {

    private Alert yesNoAlert;

    private Command softKey1;
    private Command softKey2;

    private boolean status;

    public MyPrompter() {
        yesNoAlert = new Alert("Attention");
        yesNoAlert.setString("Are you sure?");
        softKey1 = new Command("No", Command.BACK, 1);
        softKey2 = new Command("Yes", Command.OK, 1);
        yesNoAlert.addCommand(softKey1);
        yesNoAlert.addCommand(softKey2);
        yesNoAlert.setCommandListener(this);
        status = false;
    }

    public Displayable getDisplayable() {
        return yesNoAlert;
    }

    public boolean getStatus() {
        return status;
    }

    public void commandAction(Command c, Displayable d) {
        status = c.getCommandType() == Command.OK;
        // maybe do other stuff here. remember this is asynchronous
    }

};

要使用它(再次,未经测试,在我的头上):

MyPrompter prompt = new MyPrompter();
Display.getDisplay(YOUR_MIDLET_INSTANCE).setCurrent(prompt.getDisplayable());

此代码将使提示成为我们应用中当前显示的表单,但不会像我们发布的示例那样阻塞线程。我们需要继续运行并等待commandAction调用。