Java 对话框 - 查看是否单击了“确定”?

标签 java swing user-interface jdialog joptionpane

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

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, "\nPort: ", 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

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

最佳答案

我建议改用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 对话框 - 查看是否单击了“确定”?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8582743/

相关文章:

java - Swing JTree 节点可以是哪些类型的对象?

html - 如果客户端不支持 html 时事通讯中的符号,是否有办法显示 alt 符号

java - 在 JFrame 中向下移动一个矩形

Java等待 future 结果而不阻塞

Java GUI 线程 - SwingWorker

java - 将 getText() 与 double 一起使用

Java 弹出按钮

java - 使用区域设置设置自定义货币符号

java - 在 JSP 中调用 doPost 方法以及页面的 url

python - 参数 'event' 值未使用