Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Java

ความแตกต่างระหว่าง GridLayout และ GridBagLayout ใน Java

GridLayout วางคอมโพเนนต์ในกริดสี่เหลี่ยม แบ่งเท่าๆ กัน (equal-sized rectangles) แต่ละคอมโพเนนต์อยู่ในช่องเดียว ส่วน GridBagLayout เป็น Layout Manager ยืดหยุ่น จัดเรียงแนวตั้ง/แนวนอน ไม่บังคับขนาดเท่ากัน แต่ละคอมโพเนนต์ครอบครองช่อง (cell) ได้ 1 หรือหลายช่อง เรียกว่า Component Display Area

GridLayout

  • จัดเรียงในกริดสี่เหลี่ยม ช่องทุกช่อง ขนาดเท่ากัน
  • วางตาม คอลัมน์และแถว
  • Constructor: GridLayout(int rows, int cols)

ตัวอย่าง GridLayout


import java.awt.*;
import javax.swing.*;

public class GridLayoutTest {
    GridLayoutTest() {
        JFrame frame = new JFrame("GridLayout Test");
        JButton b1 = new JButton("Button 1");
        JButton b2 = new JButton("Button 2");
        JButton b3 = new JButton("Button 3");
        JButton b4 = new JButton("Button 4");
        frame.add(b1); frame.add(b2); frame.add(b3); frame.add(b4);
        frame.setLayout(new GridLayout(2, 2)); // 2 แถว 2 คอลัมน์
        frame.setSize(300, 300);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setVisible(true);
    }
    public static void main(String[] args) { new GridLayoutTest(); }
}

GridBagLayout

  • ขยายความสามารถของ GridLayout
  • วางในช่องเดี่ยวได้ และ ขยายครอบหลายคอลัมน์/แถว
  • ต้องสร้าง GridBagConstraints ตั้งค่าต่างๆ (gridx, gridy, gridwidth, gridheight, fill, anchor, weightx, weighty, insets)

ตัวอย่าง GridBagLayout


import javax.swing.*;
import java.awt.*;

public class GridBagLayoutTest extends JFrame {
    public GridBagLayoutTest() {
        setTitle("GridBagLayout Test");
        setLayout(new GridBagLayout());
        GridBagConstraints gbc = new GridBagConstraints();
        
        gbc.gridx = 5; gbc.gridy = 0;
        add(new JButton("Button1"), gbc);
        
        gbc.gridx = 0; gbc.gridy = 5;
        add(new JButton("Button2"), gbc);
        
        gbc.gridx = 2; gbc.gridy = 4;
        add(new JButton("Button3"), gbc);
    }
    public static void main(String[] args) {
        GridBagLayoutTest gbcTest = new GridBagLayoutTest();
        gbcTest.setSize(300, 300);
        gbcTest.setVisible(true);
        gbcTest.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }
}

ตารางเปรียบเทียบ

คุณสมบัติGridLayoutGridBagLayout
ขนาดช่องเท่ากันทุกช่องแตกต่างกันได้
ครอบหลายช่องไม่ได้ได้ (gridwidth/gridheight)
ความซับซ้อนง่ายซับซ้อน (ต้อง config Constraints)
ความยืดหยุ่นต่ำสูงมาก
เหมาะสำหรับForm เรียบง่าย, CalculatorForm ซับซ้อน, Dashboard