Swing的GroupLayout範例

2019-10-16 22:04:04

GroupLayout類對元件進行分層分組,以便將它們放置在容器中。

範例

import java.awt.BorderLayout;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;

import javax.swing.GroupLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;

public class SwingTester {
   public static void main(String[] args) {
      createWindow();
   }

   private static void createWindow() {    
      JFrame frame = new JFrame("Swing的GroupLayout範例");
      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      createUI(frame);
      frame.setSize(560, 200);      
      frame.setLocationRelativeTo(null);  
      frame.setVisible(true);
   }

   private static void createUI(final JFrame frame){  
      JPanel panel = new JPanel();
      GroupLayout layout = new GroupLayout(panel);
      layout.setAutoCreateGaps(true);
      layout.setAutoCreateContainerGaps(true);

      JButton btn1 = new JButton("按鈕 1");
      JButton btn2 = new JButton("按鈕 2");
      JButton btn3 = new JButton("按鈕 3");

      layout.setHorizontalGroup(layout.createSequentialGroup()
         .addComponent(btn1)
         .addGroup(layout.createSequentialGroup()
         .addGroup(layout.createParallelGroup(
         GroupLayout.Alignment.LEADING)
         .addComponent(btn2)
         .addComponent(btn3))));

      layout.setVerticalGroup(layout.createSequentialGroup()
         .addComponent(btn1)
         .addComponent(btn2)
         .addComponent(btn3));

      panel.setLayout(layout);       
      frame.getContentPane().add(panel, BorderLayout.CENTER);    
   }
}

執行上面範例程式碼,得到以下結果: