I am relatively new to Java Swing and I am having a little trouble understanding how Grid layouts can do certain things and if they can't, then how the gridbag layout, which is supposedly more powerful can do that.
Here is a program i tried with Grid layout
import javax.swing.*;
import java.awt.*;
//import java.awt.event.*;
public class Swing24
{
public static void main(String[] args)
{
JFrame f1= new JFrame("Grid Layout Test");
f1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f1.setResizable(true);
f1.setLocation(500,200);
f1.setSize(600,600);
JPanel p1 = new JPanel();
p1.setBackground(Color.black);
f1.add(p1);
JButton b1= new JButton("Button 1");
b1.setBackground(Color.white);
JButton b2= new JButton("Button 2");
b2.setBackground(Color.white);
JButton b3= new JButton("Button 3");
b3.setBackground(Color.white);
JLabel lb1=new JLabel(" Label 1");
lb1.setForeground(Color.orange);
//lb1.setOpaque(true);
lb1.setBackground(Color.yellow);
JLabel lb2=new JLabel(" Label 2");
lb2.setBackground(Color.orange);
lb2.setOpaque(true);
GridLayout glm1=new GridLayout(2,3,0,0);
p1.setLayout(glm1);
p1.add(b1);
p1.add(b2);
p1.add(b3);
p1.add(lb1);
p1.add(lb2);
f1.setVisible(true);
}
}
The above program allows me divide the container into 2 rows and 3 columns. Basically I can divide a container into m rows and n columns with a grid layout. But it adds the components(the butons and labels) serially.
Question 1: How can I directly add a button to the cell(4,3) in a grid of size(10,10)? Question 2: Can a button occupy multiple cells in a grid layout?
If the answer to any of the above is not possible, then how can gridbag layout help solve the problem. I tried using gridbag layout with a button. But it gets placed in the center! How can I, say, place it to the cell(4,3) in a container which can be divided into size(10,10)<10 rows and 10 columns>