Basically I have code that displays a dialog box and allows the user to choose between 2 and 4 players. It works fine however I want to be able to control what the 'OK' and 'Cancel' buttons do but I can't figure out how to access them. When the 'OK' button is clicked I want to call a method and if cancel is clicked I will terminate the program (System.exit(0)). Also how do I check if the user clicks the 'x' in the top corner of the dialog box?
基本上我有代码显示一个对话框,允许用户选择2到4个玩家。它工作正常,但我希望能够控制“确定”和“取消”按钮的功能,但我无法弄清楚如何访问它们。单击“确定”按钮时,我想调用一个方法,如果单击“取消”,我将终止程序(System.exit(0))。另外,如何检查用户是否单击对话框顶角的“x”?
public void numPlayersDialog()
{
Object[] possibilities = {"Two Players", "Three Players", "Four Players"};
String s = (String)JOptionPane.showInputDialog(
null,
"Enter the number of Players\n",
"Initial Dialog",
JOptionPane.PLAIN_MESSAGE,
null,
possibilities,
"Two Players");
if(s.equals("Two Players"))
{
setNumOfPlayers(2);
}
else if (s.equals("Three Players"))
{
setNumOfPlayers(3);
}
else
{
setNumOfPlayers(4);
}
}
I'm fairly new to the GUI stuff in Java so any help would be appreciated. Thanks
我对Java中的GUI内容很新,所以任何帮助都会受到赞赏。谢谢
2 个解决方案
#1
0
Here's what the javadoc says:
以下是javadoc所说的内容:
Returns:
user's input, or null meaning the user canceled the input
用户的输入,或null表示用户取消了输入
So, if the returned value is null, it means the user clicked Cancel or closed the dialog box. If the result isn't null, it means the user clicked OK.
因此,如果返回的值为null,则表示用户单击“取消”或关闭对话框。如果结果不为null,则表示用户单击了“确定”。
#2
0
You can do Like that :
你可以这样做:
if (s == null) {/////////////mean you click on the Cancel button
System.exit(0);
} else {////////////mean you click on OK button
if (s.equals("Two Players")) {
setNumOfPlayers(2);
} else if (s.equals("Three Players")) {
setNumOfPlayers(3);
} else {
setNumOfPlayers(4);
}
}
#1
0
Here's what the javadoc says:
以下是javadoc所说的内容:
Returns:
user's input, or null meaning the user canceled the input
用户的输入,或null表示用户取消了输入
So, if the returned value is null, it means the user clicked Cancel or closed the dialog box. If the result isn't null, it means the user clicked OK.
因此,如果返回的值为null,则表示用户单击“取消”或关闭对话框。如果结果不为null,则表示用户单击了“确定”。
#2
0
You can do Like that :
你可以这样做:
if (s == null) {/////////////mean you click on the Cancel button
System.exit(0);
} else {////////////mean you click on OK button
if (s.equals("Two Players")) {
setNumOfPlayers(2);
} else if (s.equals("Three Players")) {
setNumOfPlayers(3);
} else {
setNumOfPlayers(4);
}
}