Swing的GridLayout範例

2019-10-16 22:03:56

GridLayout類將元件排列在矩形網格中。

範例

import java.awt.BorderLayout;
import java.awt.GridLayout;

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的GridLayout範例");
      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();
      GridLayout layout = new GridLayout(0,3);
      layout.setHgap(10);
      layout.setVgap(10);

      panel.setLayout(layout);        
      panel.add(new JButton("按鈕 1"));
      panel.add(new JButton("按鈕 2")); 
      panel.add(new JButton("按鈕 3")); 
      panel.add(new JButton("按鈕 4")); 
      panel.add(new JButton("按鈕 5"));    
      frame.getContentPane().add(panel, BorderLayout.CENTER);    
   }
}

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