Search code examples
javaswingconcurrencyserversocketevent-dispatch-thread

Content in JFrame doesn't show when called from a specific method


The content in the JFrame WaitingFrame doesn't show up as expected. This is in essence what I am trying to do:

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

When setup() is called the WaitingFrame does indeed show up, but the contents are missing. I've tried different image formats, but it does work from other methods and classes, so that shouldn't matter. Does anyone know what's going on here?


Solution

  • Use SwingUtilities.invokeLater()/invokeAndWait() to show your frame because all the GUI should be updated from EDT.