JOptionPane.showMessageDialog没有显示文本

1 java swing dialog jpanel

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

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

 JOptionPane.showMessageDialog(null, "alert", "alert", JOptionPane.ERROR_MESSAGE);
Run Code Online (Sandbox Code Playgroud)

上面的代码提供了以下图片:

输出我得到

如果有人能告诉我我做错了什么,或者我应该使用不同的方法,我会非常感激.

编辑:

我的主要类:这创建了一个GUI,用户输入信息"Host"和"DisplayName".当他们单击"连接"时,会创建一个新线程(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);
}   
Run Code Online (Sandbox Code Playgroud)

ClientConnectSocket类:

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();
    }
}
Run Code Online (Sandbox Code Playgroud)

Hov*_*els 5

您发布的代码段表明您遇到了Swing线程问题.如果你的程序是一个Swing GUI,则需要最上面的代码中被取消了摇摆EDT或é通风口d ispatch 牛逼 hread,而任何摇摆电话,包括显示的JOptionPane应该叫了EDT.有关更具体的帮助,请考虑说明并显示有关代码和背景线程使用的更多信息.


编辑
确定,以便代码在后台线程中.所以现在你必须注意在EDT上显示你的JOptionPane.考虑进行这些更改:

} 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);          
        }
    });
}
Run Code Online (Sandbox Code Playgroud)

注意:代码未通过编译或运行进行测试.请注意拼写错误.


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

 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) {
              // ........
           }

           // ...............
        }
     }
   });
Run Code Online (Sandbox Code Playgroud)

  • +1 [例如(但仅对Java6有效,在Java7中不再是线程安全方法)](http://stackoverflow.com/a/12643642/714968) (2认同)