简体   繁体   中英

Program terminates immediately when GUI's are involved

When trying to run the following code in Eclipse, it terminates almost immediately with no message (only that the exit value is -1073740940), yet any java code that doesn't contain GUI elements runs fine. When run with the debugger it reaches the 'new Runnable' line and then terminates, but the GUI window never shows up. GUIs were working fine a while ago but they stopped working at some point and I have no idea why.

import java.awt.*;
import javax.swing.*;

public class Test {
    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                Wat wat = new Wat("Test");
                wat.init();
                System.out.println("wat");
            }
        });
    }
}

@SuppressWarnings("serial")
class Wat extends JFrame {
    public Wat(String title) {
        super(title);
    }

    public void init() {
        JPanel p = new JPanel();
        this.setContentPane(p);

        p.add(new JLabel("Why?"));

        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        this.setSize(600, 500);
        this.setVisible(true);
    }
}

The code for main method should look like this

public class Test {
    public static void main(String[] args) {
        Wat wat = new Wat("Test");
        wat.init();
        System.out.println("wat");
    }
}

Simply, run the UI code on the main thread. Use separate threads for long running operations started from UI. See tutorial for SwingWorker .

I switched a couple of lines around in the Wat class init method and added a serialVersionUID to the Wat class.

This code brings up a GUI every time I run it.

import java.awt.EventQueue;

import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;

public class Test {
    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                Wat wat = new Wat("Test");
                wat.init();
                System.out.println("wat");
            }
        });
    }
}

class Wat extends JFrame {

    private static final long   serialVersionUID    = 
            8993350484858673399L;

    public Wat(String title) {
        super(title);
    }

    public void init() {
        JPanel p = new JPanel();
        p.add(new JLabel("Why?"));

        this.setContentPane(p);
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        this.setSize(600, 500);
        this.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