2

我已经学会了使用 NotifyDescriptor 创建一个弹出对话框。我设计了一个带有两个大按钮的JPanel,它们读取PURCHASECASHOUT,我使用的代码在底部显示了另外两个按钮,读取YesNo。我不希望 NotifyDescriptor 将自己的按钮放在屏幕上。我只希望我的按钮在那里,并且当单击我的自定义按钮之一时弹出窗口会关闭并存储值。(就像单击yesno单击时它如何关闭窗口一样)。我正在使用的代码如下

       // 创建面板实例,扩展 JPanel...
        ChooseTransactionType popupSelector = new ChooseTransactionType();

        // 创建自定义NotifyDescriptor,指定面板实例为参数+其他参数
        NotifyDescriptor nd = 新的 NotifyDescriptor(
                popupSelector, // 面板实例
                "Title", // 对话框的标题
                NotifyDescriptor.YES_NO_OPTION, // 是/否对话框 ...
                NotifyDescriptor.QUESTION_MESSAGE, // ... 问题类型 => 一个问号图标
                null, // 我们已经指定 YES_NO_OPTION => 可以为空,选项由 L&F 指定,
                      // 否则将选项指定为:
                      // new Object[] { NotifyDescriptor.YES_OPTION, ... etc. },
                NotifyDescriptor.YES_OPTION //默认选项是“是”
        );

        // 现在让我们显示对话框...
        if (DialogDisplayer.getDefault().notify(nd) == NotifyDescriptor.YES_OPTION) {
            // 用户点击是,在这里做一些事情,例如:
                System.out.println(popupSelector.getTRANSACTION_TYPE());
        }
4

1 回答 1

5

为了替换options按钮上的文本,您可以传入 aString[]作为options参数,或者,如果您需要更多控制,可以传入 a JButton[]。因此,在您的情况下,您需要从面板中删除按钮并message传入 a参数。String[]options

对于initialValue(最后一个参数),NotifyDescriptor.YES_OPTION您可以使用您的任何一个String[]值(Purchase 或 Cashout),而不是使用。该DialogDisplayer.notify()方法将返回选择的任何值。所以,在这种情况下,它会返回 aString但如果你传入 aJButton[]那么返回的值将是 a JButton

String initialValue = "Purchase";
String cashOut = "Cashout";
String[] options = new String[]{initialValue, cashOut};

NotifyDescriptor nd = new NotifyDescriptor(
            popupSelector,
            "Title",
            NotifyDescriptor.YES_NO_OPTION,
            NotifyDescriptor.QUESTION_MESSAGE,
            options,
            initialValue
    );

String selectedValue = (String) DialogDisplayer.getDefault().notify(nd);
if (selectedValue.equals(initialValue)) {
    // handle Purchase
} else if (selectedValue.equals(cashOut)) {
    // handle Cashout   
} else {
    // dialog closed with top close button
}
于 2012-04-25T01:28:00.993 回答