1

JFrame WaitingFrame 中的内容未按预期显示。这本质上是我想要做的:

package org.brbcoffee.missinggui;

import java.net.*;
import java.io.*;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

public class Main {
    public static KeynoteServer server;
    public static void main(String[] args){
        JFrame frame = new JFrame("SSCCE");
        JButton btn = new JButton("Test");
        btn.addActionListener(new ActionListener(){
            @Override
            public void actionPerformed(ActionEvent arg0) {
                connectToPhone();
            }
        });
        frame.add(btn);
        frame.pack();
        frame.setVisible(true);
    }
    public static void connectToPhone(){
        WaitingFrame wf = new WaitingFrame();
        wf.setVisible(true);
        server = new KeynoteServer();
        if (server.setup()){
            System.out.println("Server set up and connected");
        } else {
            System.out.println("Couldn't connect");
        }
        wf.dispose();
    }
}   

@SuppressWarnings("serial")
class WaitingFrame extends JFrame {
    public WaitingFrame(){
        setTitle("Waiting");
        this.setLocationByPlatform(true);

        JLabel label = new JLabel("Waiting for client..."); // This will never show
        JPanel content = new JPanel();          
        content.add(label);

        this.add(content);
        pack();
    }
}
class KeynoteServer{
    private int port = 55555;
    private ServerSocket server;
    private Socket clientSocket;

    public boolean setup() {
        try {
            server = new ServerSocket(55555);
            server.setSoTimeout(10000);
            clientSocket = server.accept();
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }
}

当 setup() 被调用时,WaitingFrame 确实出现了,但是内容丢失了。我尝试了不同的图像格式,但它确实适用于其他方法和类,所以这无关紧要。有谁知道这里发生了什么?

4

1 回答 1

2

用于SwingUtilities.invokeLater()/invokeAndWait()显示您的框架,因为所有 GUI 都应从 EDT 更新。

于 2012-12-14T07:55:28.030 回答