java gridbag,Java中的Gridbag布局

I have to edit a gridbag layout problematically and i am having weird results.

expected:

| A | | B |

| -- | | C |

| D | | -- |

Results:

| A | | B |

| D | | C |

A and C have a height of 2

Is this just how gridbag works? is there anyway to force it?

My program has two columns and n number of rows. It supports a width of 2 but it only comes into effect when it is in the first col. If in the 2nd row it acts as though the width is 1.

gbc.gridx = 0;

gbc.gridy = 0;

gbc.gridheight = 1;

gbc.gridwidth = 1;

gbc.weighty = 1;

gbc.fill = GridBagConstraints.BOTH;

gbc.insets = new Insets(7, 7, 7, 7);

gbc.weightx = 0.5;

gbc.anchor = GridBagConstraints.NORTH;

the components are added by the user and the user determines the width and height. the gridxand gridy values are determined by what other components are added and placed.

The gridbag layout works fine for say

*_ _

|A|B|

|_|C|

it just doesn't seem to like it when C has a height of 2

解决方案

Now that the question has been clarified:

protected static final Insets entryInsets = new Insets(0, 10, 4, 10);

protected static final Insets spaceInsets = new Insets(10, 10, 4, 10);

protected void createPartControl() {

panel = new JPanel();

panel.setLayout(new GridBagLayout());

int gridy = 0;

gridy = createTextFields(gridy);

}

protected int createTextFields(int gridy) {

JLabel a = new JLabel("A");

a.setHorizontalAlignment(SwingConstants.LEFT);

addComponent(panel, a, 0, gridy, 1, 2, spaceInsets,

GridBagConstraints.LINE_START, GridBagConstraints.HORIZONTAL);

JLabel b = new JLabel("B");

b.setHorizontalAlignment(SwingConstants.LEFT);

addComponent(panel, b, 1, gridy++, 1, 1, spaceInsets,

GridBagConstraints.LINE_START, GridBagConstraints.HORIZONTAL);

JLabel c = new JLabel("C");

c.setHorizontalAlignment(SwingConstants.LEFT);

addComponent(panel, c, 1, gridy++, 1, 1, entryInsets,

GridBagConstraints.LINE_START, GridBagConstraints.HORIZONTAL);

JLabel d = new JLabel("D");

d.setHorizontalAlignment(SwingConstants.LEFT);

addComponent(panel, d, 0, gridy++, 2, 1, entryInsets,

GridBagConstraints.LINE_START, GridBagConstraints.HORIZONTAL);

return gridy;

}

protected void addComponent(Container container, Component component,

int gridx, int gridy, int gridwidth, int gridheight,

Insets insets, int anchor, int fill) {

GridBagConstraints gbc = new GridBagConstraints(gridx, gridy,

gridwidth, gridheight, 1.0D, 1.0D, anchor, fill, insets, 0, 0);

container.add(component, gbc);

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值