简体   繁体   中英

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?

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM