简体   繁体   English

Java Swing-从外部线程关闭JDialog

[英]Java Swing - Close JDialog from external Thread

I am working with Swing right now and I do not get this to work properly. 我正在与Swing合作,但无法正常工作。

What I need is the following: 我需要的是以下内容:

I've got a class "Client" that is able to connect to a TCP server. 我有一个可以连接到TCP服务器的“客户端”类。 If the connection fails (wrong IP for example), then it will show an error dialog that can be closed by clicking on the "OK" Button. 如果连接失败(例如,错误的IP),则会显示一个错误对话框,可通过单击“确定”按钮关闭该对话框。

However if the client connected successfully, a window should popup that runs until my client receives a specific message from the server. 但是,如果客户端成功连接,则应弹出一个窗口,直到我的客户端从服务器接收到特定的消息为止。

My code looks like this: 我的代码如下所示:

if(ip != null) {
    Client c = new Client();
    try{

        c.connect(ip, 56556);

        JOptionPane msg = new JOptionPane("Connecting...", JOptionPane.INFORMATION_MESSAGE);
        JDialog dlg = msg.createDialog("Connecting...");
        dlg.setDefaultCloseOperation(JDialog.DO_NOTHING_ON_CLOSE);
        dlg.setVisible(true);

        c.addIncomingMessageHandler(new IncomingMessageHandler(){
           @Override
           public void incomingMessage(Connection<?> cnctn, Object o) {
               dlg.setVisible(false);
               dlg.dispose();
           }
       });

   }catch(Exception e) {
       int n = JOptionPane.showOptionDialog(this, "Oops! Something went wrong!",
            "Title", JOptionPane.OK_CANCEL_OPTION, JOptionPane.WARNING_MESSAGE,
            null, new Object[] {"OK"}, JOptionPane.OK_OPTION);
        }
}

So the exception is throws if c.connect() fails. 因此,如果c.connect()失败,则会引发异常。 c.addIncomingMessageHandler() is a listener that listens to any incoming messages to the client. c.addIncomingMessageHandler()是一个侦听器,它侦听到客户端的所有传入消息。 If the server sends something, this method will be called. 如果服务器发送了一些内容,则将调用此方法。 If that's the case, the JDialog will be closed. 如果是这种情况,JDialog将关闭。 But this window can be closed right now by clicking on the OK-Button. 但是可以通过单击“确定”按钮立即关闭此窗口。

在此处输入图片说明

I'd like to rename that button and add a function. 我想重命名该按钮并添加一个功能。 The new text should be "Cancel" and if the button is pressed, the client should be closed (c.disconnect) and the window itself should be closed as well. 新文本应为“取消”,如果按下该按钮,则应关闭客户端(c.disconnect),同时也应关闭窗口本身。

How could I do that? 我该怎么办?

From the Documentation: 从文档中:

Stopping Automatic Dialog Closing 停止自动关闭对话框

By default, when the user clicks a JOptionPane-created button, the dialog closes. 默认情况下,当用户单击JOptionPane创建的按钮时,对话框关闭。 But what if you want to check the user's answer before closing the dialog? 但是,如果要在关闭对话框之前检查用户的答案怎么办? In this case, you must implement your own property change listener so that when the user clicks a button, the dialog does not automatically close. 在这种情况下,您必须实现自己的属性更改侦听器,以便在用户单击按钮时,对话框不会自动关闭。

DialogDemo contains two dialogs that implement a property change listener. DialogDemo包含两个实现属性更改侦听器的对话框。 One of these dialogs is a custom modal dialog, implemented in CustomDialog , that uses JOptionPane both to get the standard icon and to get layout assistance. 这些对话框之一是在CustomDialog实现的自定义模式对话框,该对话框使用JOptionPane来获取标准图标并获得布局帮助。 The other dialog, whose code is below, uses a standard Yes/No JOptionPane . 另一个对话框(其代码如下)使用标准的Yes/No JOptionPane Though this dialog is rather useless as written, its code is simple enough that you can use it as a template for more complex dialogs. 尽管此对话框在编写时没有多大用处,但其代码非常简单,您可以将其用作更复杂对话框的模板。

Besides setting the property change listener, the following code also calls the JDialog's setDefaultCloseOperation method and implements a window listener that handles the window close attempt properly. 除了设置属性更改侦听器之外,以下代码还调用JDialog的setDefaultCloseOperation方法并实现一个窗口侦听器,该侦听器可以正确处理窗口关闭尝试。 If you do not care to be notified when the user closes the window explicitly, then ignore the bold code. 如果您不希望在用户显式关闭窗口时收到通知,请忽略粗体代码。

final JOptionPane optionPane = new JOptionPane(
                "The only way to close this dialog is by\n"
                + "pressing one of the following buttons.\n"
                + "Do you understand?",
                JOptionPane.QUESTION_MESSAGE,
                JOptionPane.YES_NO_OPTION);

final JDialog dialog = new JDialog(frame, 
                             "Click a button",
                             true);
dialog.setContentPane(optionPane);
dialog.setDefaultCloseOperation(
    JDialog.DO_NOTHING_ON_CLOSE);
dialog.addWindowListener(new WindowAdapter() {
    public void windowClosing(WindowEvent we) {
        setLabel("Thwarted user attempt to close window.");
    }
});
optionPane.addPropertyChangeListener(
    new PropertyChangeListener() {
        public void propertyChange(PropertyChangeEvent e) {
            String prop = e.getPropertyName();

            if (dialog.isVisible() 
             && (e.getSource() == optionPane)
             && (prop.equals(JOptionPane.VALUE_PROPERTY))) {
                //If you were going to check something
                //before closing the window, you'd do
                //it here.
                dialog.setVisible(false);
            }
        }
    });
dialog.pack();
dialog.setVisible(true);

int value = ((Integer)optionPane.getValue()).intValue();
if (value == JOptionPane.YES_OPTION) {
    setLabel("Good.");
} else if (value == JOptionPane.NO_OPTION) {
    setLabel("Try using the window decorations "
             + "to close the non-auto-closing dialog. "
             + "You can't!");
}

Click here ! 点击这里

Related question . 相关问题

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM