JOptionPane.showMessageDialog没有显示文本

时间:2014-09-01 20:04:05

标签: java swing dialog jpanel

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

这是我用来尝试创建提醒的代码:

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

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

Output I get

如果有人能告诉我我做错了什么,或者我应该使用哪种方法,我会非常感激。

编辑:

我的主要课程: 这将创建一个GUI,用户可以在其中输入信息" Host"和" DisplayName"。当他们点击" Connect"创建一个新线程(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类:

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();
    }
}

1 个答案:

答案 0 :(得分:5)

您发布的代码段表明您遇到了Swing线程问题。如果您的程序是Swing GUI,那么上述大部分代码都需要从Swing EDT或 E vent D ispatch T 中调用hread,而任何Swing调用,包括显示JOptionPane都应该在EDT上被称为 on 。有关更具体的帮助,请考虑说明并显示有关代码和背景线程使用的更多信息。


修改
好的,这样代码就在后台线程中。所以现在你必须注意在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);          
        }
    });
}

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


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

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