我学会了使用 NotifyDescriptor 创建弹出对话框。我设计了一个带有两个大按钮的 JPanel,上面写着 PURCHASE
和 CASHOUT
我使用的代码在底部显示了另外两个按钮,上面写着 Yes
和 No
.我不希望 NotifyDescriptor 在屏幕上放置自己的按钮。我只希望我的按钮在那里,当我的自定义按钮之一被单击时,弹出窗口将关闭并存储值。(就像单击 yes
或 no
时关闭窗口的方式一样)。我使用的代码如下
// Create instance of your panel, extends JPanel... ChooseTransactionType popupSelector = new ChooseTransactionType(); // Create a custom NotifyDescriptor, specify the panel instance as a parameter + other params NotifyDescriptor nd = new NotifyDescriptor( popupSelector, // instance of your panel "Title", // title of the dialog NotifyDescriptor.YES_NO_OPTION, // it is Yes/No dialog ... NotifyDescriptor.QUESTION_MESSAGE, // ... of a question type => a question mark icon null, // we have specified YES_NO_OPTION => can be null, options specified by L&F, // otherwise specify options as: // new Object[] { NotifyDescriptor.YES_OPTION, ... etc. }, NotifyDescriptor.YES_OPTION // default option is "Yes" ); // let's display the dialog now... if (DialogDisplayer.getDefault().notify(nd) == NotifyDescriptor.YES_OPTION) { // user clicked yes, do something here, for example: System.out.println(popupSelector.getTRANSACTION_TYPE()); }
最佳答案
为了替换 options
按钮上的文本,您可以为 options
参数传入一个 String[]
或者,如果你需要更多的控制,你可以传入一个JButton[]
。因此,在您的情况下,您需要从 message
面板中删除按钮,并为 options
参数传入一个 String[]
。
对于 initialValue
(最后一个参数),您可以使用 String[]
值(购买或兑现)。 DialogDisplayer.notify()
方法将返回所选择的任何值。因此,在这种情况下,它将返回一个 String
,但如果您传入一个 JButton[]
,则返回值将是一个 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
}
关于java - 在 Netbeans 平台中使用自定义 NotifyDescriptor,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10306967/