简体   繁体   中英

Why does my GUI fail to appear on the page?

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

public class Grid extends JFrame{
    public Grid(){
        super("Pathfinding Algorithms");
        setContentPane(new drawGrid());
        setSize(1920,1080);
        setExtendedState(JFrame.MAXIMIZED_BOTH);
        setUndecorated(true);
        setVisible(true);
    }
    class drawGrid extends JPanel { 
        public void paintComponent(Graphics g){
            g.setColor(Color.BLACK);
            g.drawLine(0,50,1920,50);
        }
    }
    public static void main(String[] args){
        new Grid();
    }
}

For some reason, nothing is being displayed whenever I run this code. I receive no errors and I get no output messages. How can I fix this?

Follow a tutorial to learn the basics of Swing. Oracle provides one free-of-cost.

There you will find this example code to compare to your code.

In that example code you'll find the main method makes this call:

javax.swing.SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                createAndShowGUI();
            }
});

Swing thread

Every Swing app has a thread dedicated to the GUI, the event dispatching thread (EDT) thread mentioned here in the Comments. Drawing, tracking the user's inputs with mouse and keyboard, responding to window dragging/resizing, and all other on-screen work must be performed on that thread dedicated to Swing.

In contrast, you code is running on the main thread.

That invokeLater call seen above is a way to get your GUI creation code to run on the Swing thread. So you could modify your code like this:

javax.swing.SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                new Grid() ;
            }
});

However, I suggest you study that tutorial and other examples for better ways of how to work with Swing. For example, it is generally best to avoid doing work unnecessarily in constructors as seen in your code snippet. And pay attention to issues listed in Comment by Andrew Thompson .


By the way, Swing is fully supported but is in maintenance-mode .

You may want to consider the alternative, JavaFX ( OpenJFX ). JavaFX is being actively developed, with a release every six months synchronized to Java releases. Development is led by the Gluon company in cooperation with Oracle Corp. as a sub-project on the OpenJDK project .

Same threading rules apply to JavaFX, where a thread is dedicated to the GUI. Never access or manipulate a GUI widget in either Swing or JavaFX/OpenJFX from another thread.

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