【问题标题】:Java GUI Accessing Buttons From showInputDialogJava GUI 从 showInputDialog 访问按钮
【发布时间】:2013-03-23 15:29:29
【问题描述】:

基本上,我的代码会显示一个对话框并允许用户在 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);
        }
}

我对 Java 中的 GUI 内容还很陌生,因此我们将不胜感激。谢谢

【问题讨论】:

    标签: java user-interface button dialog


    【解决方案1】:

    javadoc 是这样说的:

    返回:

    用户的输入,或null表示用户取消输入

    因此,如果返回值为空,则表示用户单击了取消或关闭了对话框。如果结果不为空,则表示用户点击了确定。

    【讨论】:

    • 不知道我是怎么错过的,我阅读了整个页面,但是它仍然没有解释我如何控制单击“确定”时发生的事情。
    • 点击OK时,执行showInputDialog之后的代码。所以你只需要检查返回的值并进行相应的处理。
    【解决方案2】:

    你可以这样做:

    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);
            }
        }
    

    【讨论】:

    • 谢谢你,我觉得有点傻,我现在没有意识到这一点:/
    猜你喜欢
    • 1970-01-01
    • 2013-05-02
    • 2014-01-21
    • 1970-01-01
    • 2022-01-20
    • 1970-01-01
    • 2011-05-12
    • 1970-01-01
    • 2014-06-19
    相关资源
    最近更新 更多