GridLayout ใส่ส่วนประกอบทั้งหมดลงในตารางสี่เหลี่ยมและแบ่งออกเป็น สี่เหลี่ยมขนาดเท่ากัน และแต่ละองค์ประกอบจะถูกวางไว้ภายในสี่เหลี่ยมผืนผ้าในขณะที่ GridBagLayout เป็น ยืดหยุ่น เค้าโครง ผู้จัดการ ที่จัดองค์ประกอบ แนวตั้งและแนวนอน โดยไม่ต้องให้ส่วนประกอบมีขนาดเท่ากัน แต่ละ GridBagLayout ออบเจ็กต์รักษา ตารางเซลล์สี่เหลี่ยมแบบไดนามิก โดยแต่ละองค์ประกอบจะครอบครองเซลล์อย่างน้อยหนึ่งเซลล์ที่เรียกว่า ส่วนประกอบ แสดงผล พื้นที่ .
GridLayout
A GridLayout จัดเรียงส่วนประกอบในตารางสี่เหลี่ยม จัดองค์ประกอบในเซลล์และแต่ละเซลล์มี ขนาดเท่ากัน . ส่วนประกอบจะอยู่ใน คอลัมน์และแถว . GridLayout(แถว int คอลัมน์ int) รับพารามิเตอร์สองตัวคือคอลัมน์และแถว
ตัวอย่าง
import java.awt.*;
import javax.swing.*;
public class GridLayoutTest{
GridLayoutTest() {
JFrame frame = new JFrame("GridLayout Test");
JButton button1, button2, button3, button4;
button1 = new JButton("Button 1");
button2 = new JButton("Button 2");
button3 = new JButton("Button 3");
button4 = new JButton("Button 4");
frame.add(button1);
frame.add(button2);
frame.add(button3);
frame.add(button4);
frame.setLayout(new GridLayout(2,2));
frame.setSize(300,300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
public static void main(String[] args) {
new GridLayoutTest();
}
} ผลลัพธ์

GridBagLayout
A GridBagLayout ขยายขีดความสามารถของ GridLayout GridBagLayout วางองค์ประกอบในแต่ละเซลล์ในตาราง และยังช่วยให้องค์ประกอบขยายไปถึงหลายคอลัมน์หรือหลายแถว เพื่อที่จะใช้ GridBagLayout เราต้องสร้าง GridBagConstraints วัตถุ และกรอกคุณสมบัติที่เหมาะสม
ตัวอย่าง
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);
}
} ผลลัพธ์
