Swing的BorderLayout範例

2019-10-16 22:03:59

BorderLayout類排列元件為五個區域:東,西,北,南和中心。

範例

import java.awt.BorderLayout;

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 BorderLayout範例");
      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();
      BorderLayout layout = new BorderLayout();
      layout.setHgap(10);
      layout.setVgap(10);

      panel.setLayout(layout);        
      panel.add(new JButton("中心"),BorderLayout.CENTER);
      panel.add(new JButton("行開始"),BorderLayout.LINE_START); 
      panel.add(new JButton("行結束"),BorderLayout.LINE_END);
      panel.add(new JButton("東"),BorderLayout.EAST);   
      panel.add(new JButton("西"),BorderLayout.WEST); 
      panel.add(new JButton("北"),BorderLayout.NORTH); 
      panel.add(new JButton("南"),BorderLayout.SOUTH); 
      frame.getContentPane().add(panel, BorderLayout.CENTER); 
   }
}

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