Reputation: 11
Ive been trying to make adjust my display the way i want it, but it doesnt seem to work. I want to use GridBagLayout to make something like this:
I want to sort panels like this
Ive found a piece of code, and edited it:
public class GBLPanel extends JPanel
{
private static final long serialVersionUID = 1L;
GridBagConstraints gbc = new GridBagConstraints();
public GBLPanel(Dimension appdim)
{
GridBagConstraints c = new GridBagConstraints();
setLayout(new GridBagLayout());
add(gbcComponent(0,0,2,1,0,0), gbc);
add(gbcComponent(0,1,1,1,0,50), gbc);
add(gbcComponent(1,1,1,1,0,50), gbc);
}
private JPanel gbcComponent(int x, int y, int w, int h, int ipadyx, int ipadyy){
gbc.gridx = x;
gbc.gridy = y;
gbc.gridwidth = w;
gbc.gridheight = h;
gbc.weightx = 1.0;
gbc.weighty = 1.0;
gbc.ipadx=ipadyx;
gbc.ipady=ipadyy;
gbc.fill = GridBagConstraints.BOTH;
JPanel panel = new JPanel();
JTextField text = new JTextField("(" + w + ", " + h + ")");
panel.setBorder(new TitledBorder("(" + x + ", " + y + ")"));
panel.add(text);
return panel;
}
}
and i cant figure out how to shape it as i want, anyone can help ? Thanks very much !
Upvotes: -1
Views: 38
Reputation: 10969
A BorderLayout
would probably be easier to do this for you.
But if you want/need to use a GridBagLayout
, the current problem you are having is that you are setting the weight
for both x and y for each panel to 1. Meaning they will all be distributed evenly.
Try changing them to reflect the values you want by doing something like this
public GBLPanel(Dimension appdim)
{
GridBagConstraints c = new GridBagConstraints();
setLayout(new GridBagLayout());
// Pass in weights also
add(gbcComponent(0,0,2,1,0,0, 1, 0.25), gbc); // 100% x and 25% y
add(gbcComponent(0,1,1,1,0,50, 0.25, 0.75), gbc); // 25% x and 75% y
add(gbcComponent(1,1,1,1,0,50, 0.75, 0.75), gbc); // 75% x and 75% y
}
private JPanel gbcComponent(int x, int y, int w, int h, int ipadyx, int ipadyy, double wx, double wy)
{
gbc.gridx = x;
gbc.gridy = y;
gbc.gridwidth = w;
gbc.gridheight = h;
gbc.weightx = wx; // Set to passed in values here
gbc.weighty = wy;
gbc.ipadx=ipadyx;
gbc.ipady=ipadyy;
gbc.fill = GridBagConstraints.BOTH;
JPanel panel = new JPanel();
JTextField text = new JTextField("(" + w + ", " + h + ")");
panel.setBorder(new TitledBorder("(" + x + ", " + y + ")"));
panel.add(text);
return panel;
}
Upvotes: 2