建立你的第一個 JFrame

import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.SwingUtilities;

public class FrameCreator {
    
    public static void main(String args[]) {
        //All Swing actions should be run on the Event Dispatch Thread (EDT)
        //Calling SwingUtilities.invokeLater makes sure that happens.
        SwingUtilities.invokeLater(() -> {
            JFrame frame = new JFrame();
            //JFrames will not display without size being set
            frame.setSize(500, 500);
            
            JLabel label = new JLabel("Hello World");
            frame.add(label);
            
            frame.setVisible(true);
        });
    }
        
}

你可能會注意到,如果你執行此程式碼,標籤位於非常糟糕的位置。使用 add 方法很難以良好的方式改變。為了實現更加動態和靈活的放置,請檢視 Swing Layout Manager