[英]Java Swing JOptionPane Button Options
So this is my first time working with the JOptionPane and I was wondering if someone could help explain how I could make both of my buttons do certain actions? 所以这是我第一次使用JOptionPane,我想知道是否有人可以帮助解释如何使两个按钮都执行某些操作? For all intent and purposes have it just print out "Hi".
出于所有目的和目的,只打印“ Hi”即可。 Here is my code.
这是我的代码。 So far it only prints out "Hi" if I click the "Uhh...." button but I want it to do the same when I click the "w00t!!"
到目前为止,仅当我单击“呃...”按钮时,它才打印出“嗨”,但是当我单击“ w00t !!”时,我希望它执行相同的操作! button as well.
按钮。 I know it has something to do with the parameter "JOptionPane.YES_NO_OPTION" but I'm not sure what exactly I have to do with it.
我知道它与参数“ JOptionPane.YES_NO_OPTION”有关,但是我不确定我到底需要做什么。 Thanks for the help in advance!
我在这里先向您的帮助表示感谢!
Object[] options = {"Uhh....", "w00t!!"};
int selection = winnerPopup.showOptionDialog(null,
"You got within 8 steps of the goal! You win!!",
"Congratulations!", JOptionPane.YES_NO_OPTION,
JOptionPane.INFORMATION_MESSAGE, null,
options, options[0]);
if(selection == JOptionPane.YES_NO_OPTION)
{
System.out.println("Hi");
}
From the javadocs , 从javadocs中 ,
When one of the showXxxDialog methods returns an integer, the possible values are:
当showXxxDialog方法之一返回整数时,可能的值为:
YES_OPTION NO_OPTION CANCEL_OPTION OK_OPTION CLOSED_OPTION
So, your code should look something like, 因此,您的代码应类似于
if(selection == JOptionPane.YES_OPTION){
System.out.println("Hi");
}
else if(selection == JOptionPane.NO_OPTION){
System.out.println("wOOt!!");
}
But regardless, this logic is a bit bizarre so I would probably just roll my own dialog. 但是不管怎么说,这种逻辑有点奇怪,所以我可能只会滚动自己的对话框。
In JOPtionPane class there are some constants that represent the values of the buttons. 在JOPtionPane类中,有一些常量表示按钮的值。
/** Return value from class method if YES is chosen. */
public static final int YES_OPTION = 0;
/** Return value from class method if NO is chosen. */
public static final int NO_OPTION = 1;
/** Return value from class method if CANCEL is chosen. */
public static final int CANCEL_OPTION = 2;
You changed the names of the buttons, and consequently, your first button "Uhh" has the value 0, and its button "w00t!" 您更改了按钮的名称,因此,第一个按钮“ Uhh”的值为0,其按钮为“ w00t!”。 assumed a value of 1.
假设值为1。
So, you can use this: 因此,您可以使用以下代码:
if(selection == JOptionPane.YES_OPTION)
{
System.out.println("Hi");
}
else if(selection == JOptionPane.NO_OPTION){
// do stuff
}
or maybe could be better use the swicht/case function: 或者使用swicht / case函数可能更好:
switch (selection )
{
case 0:
{
break;
}
case 1:
{
break;
}
default:
{
break;
}
}
int selection = 0;
JOptionPane.showOptionDialog(null,
"You got within 8 steps of the goal! You win!!",
"Congratulations!", JOptionPane.YES_NO_OPTION,
JOptionPane.INFORMATION_MESSAGE, null,
options, options[0]);
if(selection == JOptionPane.YES_NO_OPTION)
{
System.out.println("Hi");
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.