import java.awt.Color;
import java.awt.Component;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.Toolkit;
import javax.swing.JFrame;
import javax.swing.JLabel;
public class TestGui extends JFrame {
private static final long serialVersionUID = 1L;
private JLabel label1 = new JLabel("O");
private JLabel label2 = new JLabel("O");
private JLabel label3 = new JLabel("O");
private JLabel label4 = new JLabel("O");
final Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
public static void main(String args[]) {
TestGui gui = new TestGui();
gui.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
gui.setVisible(true);
}
private TestGui() {
// Size and Position
int width = screenSize.width;
int height = screenSize.height;
label1.setOpaque(true);
label2.setOpaque(true);
label3.setOpaque(true);
label4.setOpaque(true);
label1.setBackground(Color.RED);
label2.setBackground(Color.GREEN);
label3.setBackground(Color.BLUE);
label4.setBackground(Color.GRAY);
Container contentpane = getContentPane();
GridBagLayout gbl = new GridBagLayout();
this.setSize(80, 180);
this.setLocation(width / 2 - 300, height / 2 - 325);
int[] rowheights = { 20, 20};
int[] colwidths = { 20, 20};
gbl.columnWidths = colwidths;
gbl.rowHeights = rowheights;
contentpane.setLayout(gbl);
// Add components
addComponent(contentpane, gbl, label1, 0, 0, 1, 1, 1.0, 1.0, 1);
addComponent(contentpane, gbl, label2, 0, 1, 1, 1, 1.0, 1.0, 1);
addComponent(contentpane, gbl, label3, 1, 0, 1, 1, 1.0, 1.0, 1);
addComponent(contentpane, gbl, label4, 1, 1, 1, 1, 1.0, 1.0, 1);
}
private void addComponent(Container cont, GridBagLayout gbl, Component c, int x, int y, int width, int height,
double weightx, double weighty, int fill) {
GridBagConstraints gbc = new GridBagConstraints();
gbc.insets = new Insets(0, 0, 0, 0);
gbc.fill = fill;
gbc.gridx = x;
gbc.gridy = y;
gbc.gridwidth = width;
gbc.gridheight = height;
gbc.weightx = weightx;
gbc.weighty = weighty;
gbl.setConstraints(c, gbc);
cont.add(c);
}
}