简体   繁体   中英

why won't my jframe appear?

I am trying to display a simple jframe that I will eventually put a canvas in to render 3d objects. Last year I built two GUI programs that used jframe's and I've looked at those and they work fine, but I can't figure out why nothing happens when I run the program. This is my code:

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

public class Hello3d extends JFrame
{
    JFrame frame;
    JLabel label;

    public Hello3d()
    {
        frame = new JFrame("This is a jframe, YAAAYYYY!!!!");
        frame.setSize( 600, 400 );
        frame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );

        frame.setLayout( new BorderLayout() );
        label = new JLabel("This is where i put somthing 3d");
        frame.add( label );
        frame.setVisible(true);
    }

    public static void main(String[] args)
    {
        new Hello3d();
    }
}

Here, see if this is working. Please, do watch the main method, since, Swing GUI or any GUI for that matter, must run in it's own thread, but not main . Moreover, instead of setting sizes manually, consider calling frame.pack() , this will create a JFrame after calculating sizes of the components, contained with this container, in a good sense.

Try to use JFrame.DISPOSE_ON_CLOSE over, JFrame.EXIT_ON_CLOSE , since, the latter is very much similar to using System.exit(0) , which simply kills the application, though the former, will graciously wait for all daemon threads to stop, before actually JVM shuts down.

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

public class HelloFrame {
    private void displayGUI() {
        JFrame frame = new JFrame("Hello Frame Example");
        frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);

        JPanel contentPane = new JPanel();
        JLabel label = new JLabel(
            "This is where I put something 3D", JLabel.CENTER);
        contentPane.add(label);

        frame.setContentPane(contentPane);
        frame.pack();
        frame.setLocationByPlatform(true);
        frame.setVisible(true);
    }

    public static void main(String[] args) {
        Runnable runnable = new Runnable() {
            @Override
            public void run() {
                new HelloFrame().displayGUI();
            }
        };
        EventQueue.invokeLater(runnable);
    }
}

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