Blin420
Blin420

Reputation: 29

Java Swing GUI closing randomly

My problem is quite weird: even if I create a JFrame with literally nothing in it, so it should just display a white window, but it crashes after doing anything with it. For example, when I resize the window, the new, resized area will be black in most cases (or sometimes be the right color I really don't know why) and it will either just close or display "Not responding" and then close after a few seconds.

GUI class:

public class GUI extends JFrame {

    private static JFrame frame;

    public GUI() {
        frame = new JFrame();
        frame.setTitle("test");
        frame.getContentPane().setLayout(new FlowLayout());
        frame.pack();
        frame.setVisible(true);
    }
}

Main class:

public class Main {

    public static void main(String[] args) {
        GUI gui = new GUI();
    }
}

And here's an image exactly showing the behavior: Why does it behave like this? It's most definitely not because of the code, I think. It must be something else. I tried reinstalling Java, didn't help out. Switched from SDK 13 to 1.8.0_171, nothing. Older programs using Swing also suddenly don't work anymore and behave the same. Any ideas?

Upvotes: 0

Views: 323

Answers (2)

Ronny V
Ronny V

Reputation: 13

Try this (width 400, height 300):

public class GUI extends JFrame {

    private static JFrame frame;

    public GUI() {
        frame = new JFrame();
        frame.setTitle("test");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 400, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 300, Short.MAX_VALUE)
        );

        frame.pack();
        frame.setVisible(true);
    }
}

Upvotes: 0

sleepToken
sleepToken

Reputation: 1847

Always start your GUI from the event dispatching thread to avoid unwanted behavior.

public static void main(String[] args) {
  javax.swing.SwingUtilities.invokeLater(new Runnable() {
    public void run() {
      GUI gui = new GUI();
    }
  });
}

See the javadoc: invokeLater

Upvotes: 1

Related Questions