GridBagLayout
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class LayoutGridBag extends JApplet implements ActionListener
{
JButton buttonOne = new JButton("Button 1");
JButton buttonTwo = new JButton("Button 2");
JButton buttonThree = new JButton("Button 3");
JButton buttonFour = new JButton("Button 4");
JButton buttonFive = new JButton("Button 5");
JLabel iSawThat = new JLabel("Press a Button");
GridBagConstraints gbc;
Insets i = new Insets(0,0,0,0);
public void init()
{
GridBagLayout gbl = new GridBagLayout();
// GridBagConstraints(int gridx, int gridy, int gridwidth, int gridheight,
// double weightx, double weighty, int anchor, int fill, Insets insets,
// int ipadx, int ipady);
gbc = new GridBagConstraints(0,0,1,1,0.0,0.0,gbc.WEST,gbc.NONE,i,0,0);
gbl.setConstraints(buttonOne, gbc);
gbc = new GridBagConstraints(1,0,1,1,0.0,0.0,gbc.WEST,gbc.NONE,i,0,0);
gbl.setConstraints(buttonTwo, gbc);
gbc = new GridBagConstraints(0,1,1,1,0.0,0.0,gbc.WEST,gbc.NONE,i,0,0);
gbl.setConstraints(buttonThree, gbc);
gbc = new GridBagConstraints(1,1,1,1,0.0,0.0,gbc.WEST,gbc.NONE,i,0,0);
gbl.setConstraints(buttonFour, gbc);
gbc = new GridBagConstraints(0,2,1,1,0.0,0.0,gbc.WEST,gbc.NONE,i,0,0);
gbl.setConstraints(buttonFive, gbc);
gbc = new GridBagConstraints(0,3,2,1,0.0,0.0,gbc.WEST,gbc.NONE,i,0,0);
gbl.setConstraints(iSawThat, gbc);
Container con = getContentPane();
con.setLayout(gbl);
con.add(buttonOne);
con.add(buttonTwo);
con.add(buttonThree);
con.add(buttonFour);
con.add(buttonFive);
con.add(iSawThat);
buttonOne.addActionListener(this);
buttonTwo.addActionListener(this);
buttonThree.addActionListener(this);
buttonFour.addActionListener(this);
buttonFive.addActionListener(this);
}
public void actionPerformed(ActionEvent thisEvent)
{
Object source = thisEvent.getSource();
if(source == buttonOne)
{
iSawThat.setText("Button 1 was pressed.");
}
else if(source == buttonTwo)
{
iSawThat.setText("Button 2 was pressed.");
}
else if(source == buttonThree)
{
iSawThat.setText("Button 3 was pressed.");
}
else if(source == buttonFour)
{
iSawThat.setText("Button 4 was pressed.");
}
else if(source == buttonFive)
{
iSawThat.setText("Button 5 was pressed.");
}
repaint();
}
}