Java 对话框 - 确定是否单击了“确定"? [英] Java Dialog - Find out if OK is clicked?

查看:29
本文介绍了Java 对话框 - 确定是否单击了“确定"?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个用于客户端 GUI 的对话框,要求提供想要连接的服务器的 IP 和端口.我拥有其他所有东西,但是我将如何做到这一点,以便当用户在我的对话框中单击确定"时,它会运行一些东西?这是我到目前为止所拥有的:

I have a dialog for a client-GUI that asks for the IP and Port of the server one wants to connect to. I have everything else, but how would I make it so that when the user clicks "OK" on my dialog box, that it runs something? Here's what I have so far:

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JDialog;
import javax.swing.JOptionPane;
import javax.swing.JTextField;


public class ClientDialog {
    JTextField ip = new JTextField(20);
    JTextField port = new JTextField(20);
    GUI gui = new GUI();
    Client client = new Client();
    JOptionPane optionPane;

    public void CreateDialog(){

        Object msg[] = {"IP: ", ip, "
Port: ", port};

        optionPane = new JOptionPane();
        optionPane.setMessage(msg);
        optionPane.setMessageType(JOptionPane.INFORMATION_MESSAGE);
        JDialog dialog = optionPane.createDialog(null, "Connect to a server");
        dialog.setVisible(true);

        if(dialog == JOptionPane.OK_OPTION){
            System.out.println(ip);

            String ipMsg = ip.getText();
            int portMsg = Integer.parseInt(port.getText());

            gui.CreateConsole(client, ipMsg, portMsg);
        }

    }

}   //End class

我知道代码不正确,但我想要的是当用户在对话框上点击确定"时,我可以运行一些代码.谢谢!

I know that the code isn't correct, but what I want is that when the user hits "OK" on the dialog, I can run some code. Thanks!

推荐答案

我建议改用 showConfirmDialog

int result = JOptionPane.showConfirmDialog(myParent, "Narrative", 
       "Title", JOptionPane.INFORMATION_MESSAGE);

然后你可以从 JDialog/JOptionPane

if (result == JOptionPane.OK_OPTION, 
              JOptionPane.CANCEL_OPTION, 
              JOptionPane.CLOSED_OPTION, etc..

这篇关于Java 对话框 - 确定是否单击了“确定"?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆