Java JFrame freezing

Viewed 1156

I have this simple java application using swing. However the moment I execute the program the frame will appear but I won't be able to click anywhere and the button only appears after a few seconds. I am very new to javas Swing library so I could be missing something, however from what I've read this code shouldn't be causing any issues.

import java.awt.Graphics;
import java.awt.image.BufferStrategy;
import java.awt.FlowLayout;
import javax.swing.*;

public class Game {

    public static void main(String[] args) {

        JFrame frame = new JFrame("JFrame Example");
        JPanel panel = new JPanel();
        panel.setLayout(new FlowLayout());
        JLabel label = new JLabel("This is a label!");
        JButton button = new JButton();

        button.setText("Press me");

        panel.add(label);
        panel.add(button);

        frame.add(panel);
        frame.setSize(300, 300);
        frame.setLocationRelativeTo(null);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setVisible(true);

    }
}

EDIT So I reinstalled my jdk but discovered this: if my browser is running when I execute the above code it will hang and freeze, however if I close my browser it runs as expected. But I can't start my browser until I kill my application so it seems something is wrong with my install as these shouldn't be using the same resources?

EDIT Solved my problem: had multiple versions of jdk and jre install so unstalled both and then installed latest versions and everything seems to be working!

1 Answers

You need to create UI under UI dispatching thread:

SwingUtilities.invokeLater(new Runnable() {
    public void run() {
        // code to create UI or call to function that creates the UI
    }
});

Java 8 style:

SwingUtilities.invokeLater(()->{
    // Your UI code
});

If you don't use that idiom then the UI can't be partially created in inconsistent state, see Creating UI in swing:

almost all code that creates or interacts with Swing components must run on the event dispatch thread

You can also use invokeAndWait is you need to block until the UI is created.

Related