首页javalayoutJava Swing - 如何垂直布局与BoxLayout

Java Swing - 如何垂直布局与BoxLayout

我们想知道如何垂直布局与BoxLayout。
import javax.swing.BoxLayout;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;

public class Main extends JFrame {

  private JLabel jLabelOne = new JLabel();
  private JLabel jLabelTwo = new JLabel();
  private JPanel panel = new JPanel();
  private BoxLayout boxLayout = new BoxLayout(panel, BoxLayout.Y_AXIS);

  public Main() {

    panel.setLayout(boxLayout);

    jLabelOne.setAlignmentX(CENTER_ALIGNMENT);
    jLabelTwo.setAlignmentX(CENTER_ALIGNMENT);

    jLabelOne.setText("This is text one");
    jLabelTwo.setText("This is text two");

    panel.add(jLabelOne);
    panel.add(jLabelTwo);

    panel.setAlignmentX(CENTER_ALIGNMENT);
    add(panel);
    setSize(300, 300);
    setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
    setLocationRelativeTo(null);
    setVisible(true);
  }

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