首页javalayoutJava Swing - 如何使用GridBagLayout将JLabel放在JPanel中

Java Swing - 如何使用GridBagLayout将JLabel放在JPanel中

我们想知道如何使用GridBagLayout将JLabel放在JPanel中。
import java.awt.GridBagLayout;

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

public class Main {

  public static void main(String[] args) {

    JFrame frame = new JFrame("Test");
    JPanel panel = new JPanel();
    JLabel label = new JLabel("CenteredJLabel");

    panel.setLayout(new GridBagLayout());
    panel.add(label);
    panel.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
    frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
    frame.add(panel);
    frame.setSize(400, 300);
    frame.setVisible(true);

  }
}