JOptionPane.showMessageDialog不显示文本 [英] JOptionPane.showMessageDialog not showing text

查看:119
本文介绍了JOptionPane.showMessageDialog不显示文本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用JOptionPane.showMessageDialog()方法时,似乎出现了一些问题.当我使用该方法时,唯一正确设置的是对话框标题.它不想显示我提供的文本.

I seem to be having some issues when using the JOptionPane.showMessageDialog() method. When I use the method the only thing that is set up correctly is the dialogs title. It doesn't want to display the text that I provide.

这是我用来尝试创建警报的代码:

Here's the code that I'm using to try and create an alert:

 JOptionPane.showMessageDialog(null, "alert", "alert", JOptionPane.ERROR_MESSAGE);

上面的代码提供了下图:

The code above provides the image below:

如果有人可以告诉我我做错了什么,或者如果我应该使用其他方法,我将不胜感激.

If someone could tell me what I'm doing wrong or if there is a different method that I'm supposed to be using, I would much appreciate it.

我的主班:这将创建一个GUI,用户可以在其中输入信息主机"和"DisplayName".当他们单击连接"时,将创建一个新线程(ClientConnectSocket).

My main class: This creates a GUI where the user enters information "Host" and "DisplayName". When they click "Connect" a new thread is created (the ClientConnectSocket).

public class Main extends JFrame {

public static JPanel contentPane;
private JTextField hostTxt;
public static JTextField displayNameTxt;

JLabel lblDisplayName = new JLabel("Display Name:");
JButton btnConnect = new JButton("Connect");
JLabel lblHost = new JLabel("Host:");


public static String username = "None :(";
public static String host = "localhost";

public static boolean connected = false;

/**
 * Launch the application.
 */
public static void main(String[] args) {
    EventQueue.invokeLater(new Runnable() {
        public void run() {
            try {
                Main frame = new Main();
                frame.setVisible(true);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    });
}

/**
 * Create the frame.
 */
public Main() {
    setType(Type.UTILITY);
    setTitle("Java Chat Client - v0.1");
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    setBounds(100, 100, 390, 200);
    contentPane = new JPanel();
    this.setResizable(false);
    contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
    setContentPane(contentPane);
    contentPane.setLayout(null);


    lblHost.setBounds(60, 11, 56, 19);
    contentPane.add(lblHost);

    hostTxt = new JTextField();
    hostTxt.setBounds(165, 10, 103, 20);
    contentPane.add(hostTxt);
    hostTxt.setColumns(10);


    btnConnect.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent arg0) {
            if (hostTxt.getText() == null || displayNameTxt.getText() == null){

            }else{
                Thread ccs = new ClientConnectSocket(hostTxt.getText(), displayNameTxt.getText());
                ccs.start();
                while (!connected){
                    //System.out.println("Not connected yet..");
                    try {
                        Thread.sleep(500);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                System.out.println("Yey, connected");
                username = displayNameTxt.getText();
                host = hostTxt.getText();

                EventQueue.invokeLater(new Runnable() {
                    public void run() {
                        try {
                            Chat frame = new Chat();
                            frame.setVisible(true);

                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                });
                dispose();

            }
        }
    });
    btnConnect.setBounds((this.getWidth()/2)- 70, 76, 89, 23);

    contentPane.add(btnConnect);

    displayNameTxt = new JTextField();
    displayNameTxt.setColumns(10);
    displayNameTxt.setBounds(165, 45, 103, 20);
    contentPane.add(displayNameTxt);


    lblDisplayName.setBounds(60, 41, 95, 29);
    contentPane.add(lblDisplayName);

    this.getRootPane().setDefaultButton(btnConnect);
}   

ClientConnectSocket类:

ClientConnectSocket class:

public class ClientConnectSocket extends Thread{

String host;
String name;

public ClientConnectSocket(String host, String displayName){
    this.host = host;
    this.name = displayName;
}

boolean b = true;

public void run(){
    try{
        while (b){
            Socket server = new Socket(host, 6969);
            System.out.println("Sending info to try and connect.");

            BufferedWriter out = new BufferedWriter(new OutputStreamWriter(server.getOutputStream()));
            out.write("method=connect:displayName="+ name);
            out.flush();

            Thread.sleep(500);

            InputStream in = server.getInputStream();

            StringBuffer sb = new StringBuffer();
            byte[] buffer = new byte[1024];
            int buf;
            while ((buf = in.read(buffer)) != -1){
                String line = new String(buffer, 0, buf);

                sb.append(line);
            }
            in.close();
            System.out.println(sb.toString() + " || " + sb.toString().equalsIgnoreCase("connect"));

            if (sb.toString().equalsIgnoreCase("connect")){
                //Allow them to connect
                Main.connected = true;
            }else if(sb.toString().equalsIgnoreCase("invalid:Username")){
                //Tell them they have username already taken;
                 JOptionPane.showMessageDialog(null, "alert", "alert", JOptionPane.ERROR_MESSAGE);
                b = false;
            }

            server.close();
            out.close();
            in.close();

            b = false;
        }
    }catch (Exception e){
        System.exit(2);
        e.printStackTrace();
    }
}

推荐答案

您发布的代码段表明您遇到了Swing线程问题.如果您的程序是Swing GUI,则需要从Swing EDT或 E vent D ispatch T 调用上面的大多数代码hread,而任何Swing调用(包括显示JOptionPane)都应在EDT上要获得更具体的帮助,请考虑告诉并显示更多有关您的代码以及您对后台线程的使用的信息.

Your posted code snippet suggests that you're running into a Swing threading issue. If your program is a Swing GUI, then most of the above code needs to be called off of the Swing EDT or Event Dispatch Thread, while any Swing calls, including displaying the JOptionPane should be called on the EDT. For more specific help, consider telling and showing more about your code and your use of background threading.

修改
好的,这样代码就在后台线程中了.因此,现在您必须注意在EDT上显示JOptionPane.考虑进行以下更改:

Edit
OK, so that code is in a background thread. So now you must take care to show your JOptionPane on the EDT. Consider making these changes:

} else if(sb.toString().equalsIgnoreCase("invalid:Username")) {

    b = false;

    SwingUtilities.invokeLater(new Runnable() {
        @Override
        public void run() {
            JOptionPane.showMessageDialog(null, "alert", "alert", 
               JOptionPane.ERROR_MESSAGE);          
        }
    });
}

注意:代码未经编译或运行测试.请注意错别字.

Note: code not tested by compiling or by running. Please be wary of typos.

编辑2
顺便说一句,您还有其他问题,包括连接的变量不应该是静态的.您还存在线程问题:

Edit 2
As an aside, you've got other issues including that the connected variable should not be static. You also have threading issues:

 btnConnect.addActionListener(new ActionListener() {
     public void actionPerformed(ActionEvent arg0) {
        if (hostTxt.getText() == null || displayNameTxt.getText() == null) {

        } else {

           // .........

           // ********** you should not have this type of code on the EDT
           while (!connected) {
              // ........
           }

           // ...............
        }
     }
   });

这篇关于JOptionPane.showMessageDialog不显示文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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