我一直试图以我想要的方式调整显示器,但它似乎没有用。我想使用GridBagLayout来做这样的事情:
I want to sort panels like this
我找到了一段代码,并对其进行了编辑:
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;
}
}
并且我无法弄清楚如何根据自己的需要塑造它,任何人都可以提供帮助?非常感谢!
答案 0 :(得分:2)
BorderLayout
对您来说可能更容易。
但是如果你想/需要使用GridBagLayout
,你当前遇到的问题是你为每个面板设置x和y的weight
为1.意思是他们都会均匀分配。
尝试通过执行此类操作来更改它们以反映您想要的值
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;
}