创建 JFrame 子类

import java.awt.FlowLayout;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.SwingUtilities;

public class CustomFrame extends JFrame {
    
    private static CustomFrame statFrame;
    
    public CustomFrame(String labelText) {
        setSize(500, 500);
        
        //See link below for more info on FlowLayout
        this.setLayout(new FlowLayout());
        
        JLabel label = new JLabel(labelText);
        add(label);
        
        //Tells the JFrame what to do when it's closed
        //In this case, we're saying to "Dispose" on remove all resources
        //associated with the frame on close
        this.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
    }
    
    public void addLabel(String labelText) {
        JLabel label = new JLabel(labelText);
        add(label);
        this.validate();
    }
    
    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(() -> {
            CustomFrame frame = new CustomFrame("Hello Jungle");
            //This is simply being done so it can be accessed later
            statFrame = frame;
            frame.setVisible(true);
        });
        
        try {
            Thread.sleep(5000);
        } catch (InterruptedException ex) {
            //Handle error
        }
        
        SwingUtilities.invokeLater(() -> statFrame.addLabel("Oh, hello world too."));
    }
        
}

有关 FlowLayout 的更多信息,请访问此处