एक GridLayout सभी कंपोनेंट्स को एक आयताकार ग्रिड में रखता है और इसे समान आकार के आयतों में विभाजित करता है और प्रत्येक कंपोनेंट को एक आयत के अंदर रखा जाता है जबकि GridBagLayout एक लचीला लेआउट मैनेजर है जो कंपोनेंट्स को वर्टिकली और हॉरिजॉन्टली संरेखित करता है बिना यह आवश्यकता के कि कंपोनेंट्स समान आकार के हों। प्रत्येक GridBagLayout ऑब्जेक्ट एक डायनामिक, आयताकार सेल्स का ग्रिड बनाए रखता है जिसमें प्रत्येक कंपोनेंट एक या अधिक सेल्स पर कब्जा करता है जिसे कंपोनेंट डिस्प्ले एरिया कहा जाता है।
GridLayout
एक GridLayout कंपोनेंट्स को एक आयताकार ग्रिड में व्यवस्थित करता है। यह कंपोनेंट्स को सेल्स में व्यवस्थित करता है और प्रत्येक सेल का समान आकार होता है। कंपोनेंट्स कॉलम और रो में रखे जाते हैं। GridLayout(int rows, int columns) दो पैरामीटर लेता है जो कॉलम और रो हैं।
उदाहरण
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();
}
}
आउटपुट
2x2 ग्रिड में 4 बटन समान आकार के सेल्स में व्यवस्थित।
GridBagLayout
एक 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);
}
}
आउटपुट
बटन्स विशिष्ट ग्रिड कोऑर्डिनेट्स (gridx, gridy) पर रखे गए हैं, समान आकार के सेल्स की आवश्यकता नहीं। कंपोनेंट्स मल्टीपल सेल्स तक फैल सकते हैं।
मुख्य अंतर: GridLayout सरल, समान ग्रिड के लिए; GridBagLayout जटिल, लचीले लेआउट के लिए जहां कंपोनेंट्स अलग-अलग आकार के हों और मल्टीपल सेल्स तक फैलें।