Java GridBagLayout components won't go to the designated position - java

For a school project I want to create a GUI which displays a few statistics of a server. I want to use a GridBagLayout to designate boxes to different statistics. The following picture is what I want the GUI layout to be
But when I run my code it looks like this:
The text should fill their area with the background colour and be in their designated area depicted in the first picture.
This is the code I am using:
package Monitoring;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class MonitoringGui extends JFrame implements ActionListener {
private Configuratie config;
private MonitoringPanel mp;
public MonitoringGui(Configuratie config) {
this.config = config;
setTitle("MonitoringGui");
setSize(850, 600);
setLayout(new GridBagLayout());
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
// onderdelen toevoegen en verwijderen
JPanel selectorPanel = new JPanel();
selectorPanel.setLayout(new GridBagLayout());
selectorPanel.setBorder(BorderFactory.createLineBorder(Color.black));
addElement(selectorPanel, 0, 0, 4, 2, 0.2, 1, new int[]{20, 20, 20, 20});
// output en input area
JPanel drawArea = new JPanel();
selectorPanel.setLayout(new GridBagLayout());
drawArea.setBackground(Color.lightGray);
addElement(drawArea, 5, 0, 10, 1, 1, 1, new int[]{20, 0, 0, 20});
// buttons, etc
JPanel buttonPanel = new JPanel();
buttonPanel.setLayout(new GridBagLayout());
addElement(buttonPanel, 5, 1, 10, 1, 1, 0.2, new int[]{0, 0, 20, 20});
//grafiek area
JPanel grafiekArea = new JPanel();
grafiekArea.setLayout(new GridBagLayout());
grafiekArea.setBackground(Color.CYAN);
grafiekArea.add(new JLabel("GrafiekArea"));
addElement(grafiekArea, 0, 0, 3, 1, 1, 0, new int[]{20, 20, 20, 20}, drawArea);
//beschikbaar area
JPanel beschArea = new JPanel();
beschArea.setLayout(new GridBagLayout());
beschArea.setBackground(Color.ORANGE);
beschArea.add(new JLabel("BeschArea"));
addElement(beschArea, 0, 1, 1, 1, 0, 0, new int[]{20, 20, 20, 20}, drawArea);
//uptime area
JPanel uptimeArea = new JPanel();
uptimeArea.setLayout(new GridBagLayout());
uptimeArea.setBackground(Color.RED);
uptimeArea.add(new JLabel("UptimeArea"));
addElement(uptimeArea, 2, 1, 1, 1, 0, 0, new int[]{20, 20, 20, 20}, drawArea);
//schijfruimte area
JPanel schijfruimteArea = new JPanel();
schijfruimteArea.setLayout(new GridBagLayout());
schijfruimteArea.setBackground(Color.GREEN);
schijfruimteArea.add(new JLabel("Schijfruimte"));
addElement(schijfruimteArea, 3, 1, 1, 1, 0.2, 0.2, new int[]{20, 20, 20, 20}, drawArea);
setVisible(true);
}
public void addElement(Component comp, int x, int y, int width, int height, double weightx, double weighty, int[] insets) {
GridBagConstraints c = new GridBagConstraints();
c.fill = GridBagConstraints.BOTH;
c.gridx = x;
c.gridy = y;
c.gridheight = height;
c.gridwidth = width;
c.weightx = weightx;
c.weighty = weighty;
c.insets = new Insets(insets[0], insets[1], insets[2], insets[3]);
add(comp, c);
}
public void addElement(Component comp, int x, int y, int width, int height, double weightx, double weighty, int[] insets, JPanel panel) {
GridBagConstraints c = new GridBagConstraints();
c.fill = GridBagConstraints.BOTH;
c.gridx = x;
c.gridy = y;
c.gridheight = height;
c.gridwidth = width;
c.weightx = weightx;
c.weighty = weighty;
c.insets = new Insets(insets[0], insets[1], insets[2], insets[3]);
panel.add(comp, c);
}
}

I figured out the answer. To make this layout work for my application I have to specify the size of the different panels inside each panel. These are the lines of code I had to add:
selectorPanel.setPreferredSize(new Dimension(120,600));
drawArea.setPreferredSize(new Dimension(660, 600));
grafiekArea.setPreferredSize(new Dimension(670,400));
beschArea.setPreferredSize(new Dimension(220,200));
uptimeArea.setPreferredSize(new Dimension(220,200));
schijfruimteArea.setPreferredSize(new Dimension(220,200));

Related

putting a JPanel in a JFrame: setContentPane() and add() both work?

putting a JPanel in a JFrame: setContentPane() and add() both seem to work. Is there any technical difference?
One example from web has the following. Changing frame.setContentPane(panel) to frame.add(panel) seems to produce the same behavior.
//file: Calculator.java
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Calculator extends JPanel implements ActionListener {
GridBagConstraints gbc = new GridBagConstraints();
JTextField theDisplay = new JTextField();
public Calculator() {
gbc.weightx = 1.0; gbc.weighty = 1.0;
gbc.fill = GridBagConstraints.BOTH;
ContainerListener listener = new ContainerAdapter() {
public void componentAdded(ContainerEvent e) {
Component comp = e.getChild();
if (comp instanceof JButton)
((JButton)comp).addActionListener(Calculator.this);
}
};
addContainerListener(listener);
gbc.gridwidth = 4;
addGB(this, theDisplay, 0, 0);
// make the top row
JPanel topRow = new JPanel();
topRow.addContainerListener(listener);
gbc.gridwidth = 1;
gbc.weightx = 1.0;
addGB(topRow, new JButton("C"), 0, 0);
gbc.weightx = 0.33;
addGB(topRow, new JButton("%"), 1, 0);
gbc.weightx = 1.0;
addGB(topRow, new JButton("+"), 2, 0 );
gbc.gridwidth = 4;
addGB(this, topRow, 0, 1);
gbc.weightx = 1.0; gbc.gridwidth = 1;
// make the digits
for(int j=0; j<3; j++)
for(int i=0; i<3; i++)
addGB(this, new JButton("" + ((2-j)*3+i+1) ), i, j+2);
// -, x, and divide
addGB(this, new JButton("-"), 3, 2);
addGB(this, new JButton("x"), 3, 3);
addGB(this, new JButton("\u00F7"), 3, 4);
// make the bottom row
JPanel bottomRow = new JPanel();
bottomRow.addContainerListener(listener);
gbc.weightx = 1.0;
addGB(bottomRow, new JButton("0"), 0, 0);
gbc.weightx = 0.33;
addGB(bottomRow, new JButton("."), 1, 0);
gbc.weightx = 1.0;
addGB(bottomRow, new JButton("="), 2, 0);
gbc.gridwidth = 4;
addGB(this, bottomRow, 0, 5);
}
void addGB(Container cont, Component comp, int x, int y) {
if ((cont.getLayout() instanceof GridBagLayout) == false)
cont.setLayout(new GridBagLayout());
gbc.gridx = x; gbc.gridy = y;
cont.add(comp, gbc);
}
public void actionPerformed(ActionEvent e) {
if (e.getActionCommand().equals("C"))
theDisplay.setText("");
else
theDisplay.setText(theDisplay.getText()
+ e.getActionCommand());
}
public static void main(String[] args) {
JFrame frame = new JFrame("Calculator");
frame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
frame.setSize(200, 250);
frame.setLocation(200, 200);
frame.setContentPane(new Calculator());
frame.setVisible(true);
}
}
Another has the following. Changing frame.add(panel) to frame.setContentPane(panel) seems to produce the same behavior.
import javax.swing.*;
import java.awt.*;
import java.util.HashMap;
import java.util.Map;
public class recMod {
public enum RecFieldNames {
FIRST_NAME("First Name:"),
LAST_NAME("Last Name:"),
VENDOR("Vendor:"),
VENDOR_LOC_CODE("Vendor Location Code:"),
USER_EMAIL("User Email Address:"),
USER_NAME("Username:"),
PASSWORD("Password:"),
USER_CODE("User Code:");
private String name;
private RecFieldNames(String name) {
this.name = name;
}
public String getName() {
return name;
}
}
private static final int FIELD_COLS = 7;
private Map<RecFieldNames, JTextField> recFieldMap =
new HashMap<RecFieldNames, JTextField>();
//JButton[] recButtons = new JButton[3];
public recMod() {
JFrame frame = new JFrame("Record Modify");
JPanel panel = new JPanel();
panel.setLayout(new GridBagLayout());
addLabelField(panel, RecFieldNames.FIRST_NAME, 0, 0, 1, 1,
GridBagConstraints.WEST, GridBagConstraints.CENTER);
addLabelField(panel, RecFieldNames.LAST_NAME, 2, 0, 1, 1,
GridBagConstraints.CENTER, GridBagConstraints.EAST);
addLabelField(panel, RecFieldNames.VENDOR, 0, 1, 1, 1,
GridBagConstraints.WEST, GridBagConstraints.CENTER);
addLabelField(panel, RecFieldNames.VENDOR_LOC_CODE, 2, 1, 1, 1,
GridBagConstraints.CENTER, GridBagConstraints.WEST);
addLabelField(panel, RecFieldNames.USER_EMAIL, 0, 2, 1, 1,
GridBagConstraints.WEST, GridBagConstraints.WEST);
addLabelField(panel, RecFieldNames.USER_NAME, 0, 3, 1, 1,
GridBagConstraints.WEST, GridBagConstraints.CENTER);
addLabelField(panel, RecFieldNames.PASSWORD, 2, 3, 1, 1,
GridBagConstraints.CENTER, GridBagConstraints.WEST);
addLabelField(panel, RecFieldNames.USER_CODE, 0, 4, 1, 1,
GridBagConstraints.WEST, GridBagConstraints.WEST);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(panel);
//frame.getContentPane().setPreferredSize(new Dimension(500, 400));
((JComponent) frame.getContentPane()).
setBorder(BorderFactory.createEmptyBorder(30, 30, 30, 30));
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public String getFieldText(RecFieldNames rfn) {
return recFieldMap.get(rfn).getText();
}
private void addLabelField(JPanel p, RecFieldNames recFieldNames, int x,
int y, int width, int height, int labelAlign, int fieldAlign) {
GridBagConstraints gbc = new GridBagConstraints();
JLabel label = new JLabel(recFieldNames.getName());
JTextField textField = new JTextField(FIELD_COLS);
recFieldMap.put(recFieldNames, textField);
gbc.gridx = x;
gbc.gridy = y;
gbc.gridwidth = width;
gbc.gridheight = height;
gbc.weightx = 1.0;
gbc.weighty = 0.0;
int midInset = (x == 2) ? 40 : 5;
gbc.insets = new Insets(5, midInset, 5, 5);
gbc.anchor = labelAlign;
gbc.fill = GridBagConstraints.HORIZONTAL;
p.add(label, gbc);
gbc.gridx = x + 1;
gbc.anchor = fieldAlign;
gbc.insets = new Insets(5, 5, 5, 5);
p.add(textField, gbc);
}
public static void main(String args[]) {
new recMod();
}
}
The content pane of the frame is a JPanel.
So if you use frame.add( another panel ), then you have a structure like:
- JFrame
- content pane
- another panel
If you use frame setContentPane( another panel ) you have:
- JFrame
- another panel
See the section from the Swing tutorial on Adding Components to the Content Pane.

I want to add separate panels (using JPanel) in my code using gridbag layout .Can anyone one suggest me with the right code.Thanks in advance

Hi I am unable to add panels separately to the components.Can you help me with the right code please.
import javax.swing.*;
import javax.swing.border.EtchedBorder;
import java.awt.*;
import java.awt.event.*;
public class Example3 extends JPanel
{
GridBagConstraints constraints = new GridBagConstraints();
public Example3()
{
setLayout(new GridBagLayout());
constraints.weightx = 1.0;
constraints.weighty = 1.0;
constraints.fill = GridBagConstraints.HORIZONTAL;
constraints.insets=new Insets(5,5,5,5);
int x, y;
// Iwant to add panel to this section to the left side//
constraints.gridheight = 1;
addGB(new JLabel("label1"), x = 0, y = 0);
addGB(new JLabel("label2"), x = 0, y = 1);
addGB(new JLabel("label3"), x = 0, y = 2);
addGB(new JLabel("label4"), x = 0, y = 3);
addGB(new JLabel("label5"), x = 0, y = 4);
//i want another panel to add to this section to the bottom//
constraints.gridwidth=2;
addGB(new JTextField("txt1"), x=1, y=0);
addGB(new JButton("btn1"), x=1, y=1);
addGB(new JRadioButton("no"), x=1, y=2);
addGB(new JRadioButton("no"), x=1, y=2);
addGB(new JComboBox(), x=1, y=3);
addGB(new JTextField("txt3"), x=1, y=4);
addGB(new JButton("OK"), x=1, y=5);
//I want to add panels to this section in the center//
addGB(new JCheckBox("chk1"), x=3, y=0);
addGB(new JCheckBox("chk2"), x=3, y=1);
addGB(new JTextArea("txtar1"), x=3, y=2);
addGB(new JRadioButton("rbtn2"), x=3, y=3);
addGB(new JComboBox(), x=3, y=4);
addGB(new JButton("CANCEL"), x=3, y=5);
//I want to add panel to this section to right side//
addGB(new JCheckBox("chk3"), x=5, y=0);
addGB(new JCheckBox("chk4"), x=7, y=0);
}
void addGB(Component component, int x, int y)
{
constraints.gridx = x;
constraints.gridy = y;
add(component, constraints);
}
public static void main(String[] args)
{
JFrame frame = new JFrame("Welcome to Example3");
frame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
frame.setSize(200, 200);
frame.setLocation(200, 200);
frame.setContentPane(new Example3());
frame.setVisible(true);
}
}
I want to add panels to labels separately and checkboxes separately using gridbag layout,JPanel.Can anyone suggest me with the right code please.
If you wont just to add JPanel you can add this code in your main
JFrame frame = new JFrame("Welcome to Example3");
frame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
.....
//you miss those line
JPanel p = new JPanel();
frame.getContentPane().add(p);
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import javax.swing.BorderFactory;
import javax.swing.Box;
import javax.swing.ButtonGroup;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JComboBox;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.JTextField;
public class PizzaGridBagLayout extends JFrame {
public static void main(String[] args) {
new PizzaGridBagLayout();
}
JTextField name = new JTextField(10), phone = new JTextField(10);JComboBox address = new JComboBox(new String[]{"ComboBox 1","hi","hello"});
JComboBox address1 = new JComboBox(new String[]{"ComboBox 2","hi","hello"});
JButton labels=new JButton("labels");
JLabel label1 = new JLabel("label1");
JLabel label2 = new JLabel("label2");
JLabel label3 = new JLabel("Label3");
JLabel label4 = new JLabel("Label4");
JLabel label5 = new JLabel("Label5");
JRadioButton yes = new JRadioButton("yes"),
no = new JRadioButton("no");
JCheckBox box1 = new JCheckBox("box1"), box2 = new JCheckBox("box2"),
box3 = new JCheckBox("box3");
JButton okButton = new JButton("OK"), closeButton = new JButton("Close");
public PizzaGridBagLayout() {
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel1 = new JPanel();
panel1.setLayout(new GridBagLayout());
//addItem(panel1, new JLabel(""), 0, 0, 1, 1, GridBagConstraints.CENTER);
// addItem(panel1, new JLabel(""), 1, 1, 1, 1, GridBagConstraints.CENTER);
// addItem(panel1, new JLabel(""), 1, 2, 1, 1, GridBagConstraints.CENTER);
addItem(panel1, name, 1, 2, 1, 0, GridBagConstraints.CENTER);
addItem(panel1, phone, 1, 2, 1, 1, GridBagConstraints.CENTER);
addItem(panel1, address, 1, 4, 1, 0, GridBagConstraints.CENTER);
addItem(panel1, address1, 1, 6, 1, 0, GridBagConstraints.CENTER);
Box sizeBox = Box.createVerticalBox();
//ButtonGroup sizeGroup = new ButtonGroup();
//sizeGroup.add(label1);
//sizeGroup.add(label2);
//sizeGroup.add(label3);
//sizeGroup.add(label4);
//sizeGroup.add(label5);
sizeBox.add(label1);
sizeBox.add(label2);
sizeBox.add(label3);
sizeBox.add(label4);
sizeBox.add(label5);
sizeBox.setBorder(BorderFactory.createTitledBorder(""));
addItem(panel1, sizeBox, 0, 3, 1, 1, GridBagConstraints.NORTH);
addItem(panel1, label1, 0, 3, 1, 1,GridBagConstraints.NORTH);
addItem(panel1, label2, 0, 4, 1, 1,GridBagConstraints.NORTH);
addItem(panel1, label3, 0, 5, 1, 1,GridBagConstraints.NORTH);
addItem(panel1, label4, 0, 6, 1, 1,GridBagConstraints.NORTH);
addItem(panel1, label5, 0, 7, 1, 1,GridBagConstraints.NORTH);
/*Box sizeBox1 = Box.createVerticalBox();
ButtonGroup sizeGroup1 = new ButtonGroup();
sizeBox1.add(labels);
addItem(panel1, sizeBox1, 0, 1, 1, 0, GridBagConstraints.NORTH);*/
Box styleBox = Box.createVerticalBox();
// ButtonGroup styleGroup = new ButtonGroup();
// styleGroup.add(yes);
// styleGroup.add(no);
styleBox.add(yes);
styleBox.add(no);
styleBox.setBorder(BorderFactory.createTitledBorder(""));
addItem(panel1, styleBox, 1, 3, 1, 1, GridBagConstraints.NORTH);
Box topBox = Box.createVerticalBox();
ButtonGroup topGroup = new ButtonGroup();
//topGroup.add(box1);
//topGroup.add(box2);
//topGroup.add(box3);
topBox.add(box1);
topBox.add(box2);
//topBox.add(box3);
topBox.setBorder(BorderFactory.createTitledBorder(""));
addItem(panel1, topBox, 2, 3, 1, 1, GridBagConstraints.NORTH);
Box buttonBox = Box.createHorizontalBox();
buttonBox.add(okButton);
addItem(panel1, buttonBox, 1, 6, 1, 1, GridBagConstraints.NORTH);
buttonBox.add(Box.createHorizontalStrut(20));
buttonBox.add(closeButton);
addItem(panel1, buttonBox, 2, 7, 1, 1, GridBagConstraints.NORTH);
this.add(panel1);
this.pack();
this.setVisible(true);
}
private void addItem(JPanel p, JComponent c, int x, int y, int width, int height, int align) {
GridBagConstraints gc = new GridBagConstraints();
gc.gridx = x;
gc.gridy = y;
gc.gridwidth = width;
gc.gridheight = height;
gc.weightx = 100.0;
gc.weighty = 100.0;
gc.insets = new Insets(2, 2, 2, 2);
gc.anchor = align;
gc.fill = GridBagConstraints.NONE;
p.add(c, gc);
}
}

Java : divide the screen

I try to do a simple swing window, but with the layout it's not easy...
I mean I just want a window with 3 panels :
header with 20% of window in height
content with 60% of window in height
footer with 20% of window in height
But I can't succeed to have what I want. I used a gridLayout(3,1) but I can't specify the height.
public class Window extends JFrame implements Serializable {
private JPanel _header;
private JPanel _content;
private JPanel _footer;
public Window() {
GridLayout grid = new GridLayout(3,1);
setLayout(grid);
_header = new JPanel();
_header.setBackground(Color.GRAY);
getContentPane().add(_header);
_content = new JPanel();
JScrollPane jsp = new JScrollPane(_content, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
jsp.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED);
getContentPane().add(jsp);
_footer = new JPanel();
_footer.setBackground(Color.GRAY);
getContentPane().add(_footer);
pack();
validate();
setTitle("Chat client");
setVisible(true);
setSize(500, 500);
setLocationRelativeTo(null);
}
Can you help me ?
Best regards
GridBagLayout is capable of dividing vertical or horizontal space proportionally.
Here's an example that displays a red JPanel in the top 20% of a window, a green JPanel in the middle 60%, and a blue JPanel in the bottom 20%:
JFrame window = new JFrame();
window.setLayout(new GridBagLayout());
JPanel top = new JPanel(), middle = new JPanel(), bottom = new JPanel();
top.setBackground(Color.red);
middle.setBackground(Color.green);
bottom.setBackground(Color.blue);
GridBagConstraints c = new GridBagConstraints();
// we want the layout to stretch the components in both directions
c.fill = GridBagConstraints.BOTH;
// if the total X weight is 0, then it won't stretch horizontally.
// It doesn't matter what the weight actually is, as long as it's not 0,
// because the grid is only one component wide
c.weightx = 1;
// Vertical space is divided in proportion to the Y weights of the components
c.weighty = 0.2;
c.gridy = 0;
window.add(top, c);
// It's fine to reuse the constraints object; add makes a copy.
c.weighty = 0.6;
c.gridy = 1;
window.add(middle, c);
c.weighty = 0.2;
c.gridy = 2;
window.add(bottom, c);
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
window.setVisible(true);
Result:
GridLayout always spaces evenly. You could instead use GridBagLayout, the most evil of all the Java layout managers. I've given them "weights" of 20, 60, 20 so you can see which values are which. You can just as easily use 2, 6, 2, it doesn't matter it's just a ratio. Look at the GridBagLayout tutorial for more info.
Example
public class Window extends JFrame implements Serializable {
private JPanel _header;
private JPanel _content;
private JPanel _footer;
public Window() {
GridBagLayout grid = new GridBagLayout();
setLayout(grid);
_header = new JPanel();
_header.setBackground(Color.GRAY);
// <=== add with constraints here
getContentPane().add(_header, new GridBagConstraints(0, 0, 1, 1, 1, 20, GridBagConstraints.BASELINE, GridBagConstraints.BOTH, new Insets(0, 0, 0, 0), 0, 0));
_content = new JPanel();
JScrollPane jsp = new JScrollPane(_content, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
jsp.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED);
// <=== add with constraints here
getContentPane().add(jsp, new GridBagConstraints(0, 1, 1, 1, 1, 60, GridBagConstraints.BASELINE, GridBagConstraints.BOTH, new Insets(0, 0, 0, 0), 0, 0));
_footer = new JPanel();
_footer.setBackground(Color.GRAY);
// <=== add with constraints here
getContentPane().add(_footer, new GridBagConstraints(0, 2, 1, 1, 1, 20, GridBagConstraints.BASELINE, GridBagConstraints.BOTH, new Insets(0, 0, 0, 0), 0, 0));
pack();
validate();
setTitle("Chat client");
setVisible(true);
setSize(500, 500);
setLocationRelativeTo(null);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
new Window();
}
});
}
}
Screenshot

GridBagLayout - different row size

normally, i'm not that bad with Swing and the different Layouts, but this one is really bugging me out.
What's wrong on the following chart using GridBagLayout? Every thick rectange is an JPanel.
The thin lines are just helper for the right y values.
Thanks in advance!
package at;
import java.awt.Color;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import javax.swing.BorderFactory;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class GridMask extends JFrame {
JPanel jPanel1, jPanel2, jPanel3, jPanel4, jPanel5, jPanel6;
public GridMask() {
unimportantStuff();
GridBagLayout gbl = new GridBagLayout();
setLayout(gbl);
GridBagConstraints gbc;
gbc = getGbc(0, 0, 3, 1, 0.5);
gbl.setConstraints(jPanel1, gbc);
gbc = getGbc(1, 0, 4, 1, 0.75);
gbl.setConstraints(jPanel2, gbc);
gbc = getGbc(2, 0, 3, 1, 0.5);
gbl.setConstraints(jPanel3, gbc);
gbc = getGbc(0, 3, 3, 1, 0.5);
gbl.setConstraints(jPanel4, gbc);
gbc = getGbc(1, 4, 2, 1, 0.25);
gbl.setConstraints(jPanel5, gbc);
gbc = getGbc(2, 3, 3, 1, 0.5);
gbl.setConstraints(jPanel6, gbc);
add(jPanel1);
add(jPanel2);
add(jPanel3);
add(jPanel4);
add(jPanel5);
add(jPanel6);
setVisible(true);
}
private GridBagConstraints getGbc(int x, int y, int height, int width, double weightY) {
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridx = x;
gbc.gridy = y;
gbc.gridheight = height;
gbc.gridwidth = width;
gbc.fill = GridBagConstraints.BOTH;
gbc.weightx = 1.0;
gbc.weighty = weightY;
return gbc;
}
private void unimportantStuff() {
jPanel1 = new javax.swing.JPanel();
jPanel2 = new javax.swing.JPanel();
jPanel3 = new javax.swing.JPanel();
jPanel4 = new javax.swing.JPanel();
jPanel5 = new javax.swing.JPanel();
jPanel6 = new javax.swing.JPanel();
jPanel1.setBorder(BorderFactory.createLineBorder(Color.BLACK));
jPanel2.setBorder(BorderFactory.createLineBorder(Color.BLACK));
jPanel3.setBorder(BorderFactory.createLineBorder(Color.BLACK));
jPanel4.setBorder(BorderFactory.createLineBorder(Color.BLACK));
jPanel5.setBorder(BorderFactory.createLineBorder(Color.BLACK));
jPanel6.setBorder(BorderFactory.createLineBorder(Color.BLACK));
}
public static void main(String[] args) {
new GridMask();
}
}
The result is a JFrame where the two rows have different heights, but the cells in a row have all the same height.
but the cells in a row have all the same height.
gbc.fill = GridBagConstraints.BOTH;
You are telling the layout to size all the components to fill the space available in each cell.

GridBagLayout is not working

this.rootComponent.setLayout(new GridBagLayout());
GridBagConstraints gbc=new GridBagConstraints();
//gbc.gridwidth=2;
gbc.gridx=0;
gbc.gridy=0;
gbc.gridwidth=8;
gbc.anchor=GridBagConstraints.FIRST_LINE_START;
this.rootComponent.add(new JLabel("Test label 1"),gbc);
gbc.gridx=8;
gbc.gridy=12;
gbc.gridwidth=GridBagConstraints.REMAINDER;
gbc.anchor=GridBagConstraints.FIRST_LINE_START;
this.rootComponent.add(new JLabel("Test label"),gbc);
Want to format it like this. grey part shows the jpanel part. Initially i want to layout the first 2 jpanel correctly . which is not working. how to fix it?
You are failing to specify any weightx and weighty values to the GridBagConstraints. Moreover your gridwidth values are wrong, since it only needs to be 2 for the bottom most JPanel, for the rest it needs to be 1.
Explanation of what I am doing :
Consider JPanels BLUE and RED, they are to be placed along the X-AXIS, in the ratio
70:30, with respect to each other (therefore their weightx will be 0.7 and 0.3 respectively. Since the total area along the X-AXIS is 1.0).
Now both of these BLUE and RED JPanels are to be placed along the Y-AXIS, with respect to the third GREEN JPanel in the ratio 90:10, therefore, both of these BLUE and RED will have weighty = 0.9, and the GREEN JPanel will have weighty = 0.1, but since GREEN JPanel is suppose to occupy the whole area (with respect to X-AXIS), as occupied by BLUE and RED JPanels, for that matter, its gridwidth = 2 and weightx = 1.0.
Try this code example :
import java.awt.*;
import javax.swing.*;
public class GridBagLayoutExample
{
private GridBagConstraints gbc;
public GridBagLayoutExample()
{
gbc = new GridBagConstraints();
gbc.anchor = GridBagConstraints.FIRST_LINE_START;
}
private void displayGUI()
{
JFrame frame = new JFrame("GridBagLayout Example");
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
JPanel contentPane = getPanel(Color.WHITE);
contentPane.setLayout(new GridBagLayout());
JPanel leftPanel = getPanel(Color.BLUE);
JPanel rightPanel = getPanel(Color.RED);
JPanel bottomPanel = getPanel(Color.GREEN.darker());
addComp(contentPane, leftPanel
, 0, 0, 0.7, 0.9, 1, 1, GridBagConstraints.BOTH);
addComp(contentPane, rightPanel
, 1, 0, 0.3, 0.9, 1, 1, GridBagConstraints.BOTH);
addComp(contentPane, bottomPanel
, 0, 1, 1.0, 0.1, 2, 1, GridBagConstraints.BOTH);
frame.setContentPane(contentPane);
//frame.pack();
frame.setSize(300, 300);
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
private void addComp(JPanel panel, JComponent comp
, int gridX, int gridY
, double weightX, double weightY
, int gridWidth, int gridHeight, int fill)
{
gbc.gridx = gridX;
gbc.gridy = gridY;
gbc.weightx = weightX;
gbc.weighty = weightY;
gbc.gridwidth = gridWidth;
gbc.gridheight = gridHeight;
gbc.fill = fill;
panel.add(comp, gbc);
}
private JPanel getPanel(Color backColour)
{
JPanel panel = new JPanel();
panel.setOpaque(true);
panel.setBackground(backColour);
panel.setBorder(
BorderFactory.createEmptyBorder(5, 5, 5, 5));
return panel;
}
public static void main(String[] args)
{
Runnable runnable = new Runnable()
{
#Override
public void run()
{
new GridBagLayoutExample().displayGUI();
}
};
EventQueue.invokeLater(runnable);
}
}
Here is the OUTPUT of the same :

Categories