java jpanel对齐_java – 如何使用GridBagLayout在JPanel中对齐组件中心?

当我尝试对齐我的组件时,它会左侧或右侧.

所以我只是希望解决方案摆脱这个问题,并告诉我如何将面板的大小设置为400 x 350像素.

这是我的代码…. titleLabel和ResultLabel应该在中心对齐

public TimeGui() {

layout = new GridBagLayout();

setSize(400, 350); //**Its not working**

setBackground(Color.LIGHT_GRAY);

setBorder(BorderFactory.createLineBorder(Color.BLACK));

setBorder(new TitledBorder(new EtchedBorder(), "Time Conversion") );

setLayout(layout);

layoutConstraints = new GridBagConstraints();

textField1 = new JTextField(10);

textField2 = new JTextField(10);

String[] names1 = {"Seconds", "Minutes", "Hours", "Days", "Weeks"};

comboBox1 = new JComboBox<>(names1);

comboBox2 = new JComboBox<>(names1);

titleLabel = new JLabel("Time Conversion Unit", JLabel.CENTER);

resultLabel = new JLabel("Result Label");

equalLabel = new JLabel("=");

convertButton = new JButton("Convert");

layoutConstraints.fill = GridBagConstraints.HORIZONTAL;

Insets inset = new Insets(10, 10, 10, 10);

layoutConstraints.anchor = GridBagConstraints.CENTER;

addComponent(titleLabel, 0, 0, 2, 2, inset ); // I tried (0,1,2,2)

addComponent(comboBox1, 3, 0, 2, 3, inset);

addComponent(comboBox2, 3, 2, 2, 3, inset);

addComponent(textField1, 6, 0, 1, 2, inset);

addComponent(equalLabel, 6, 1, 1, 2, inset);

addComponent(textField2, 6, 2, 1, 2, inset);

addComponent(resultLabel, 8, 1, 2, 1, inset);

addComponent(convertButton, 10, 0, 2, 2, inset);

}

private void addComponent(Component component, int row,

int column, int width, int height, Insets inset1) {

layoutConstraints.gridx = column;

layoutConstraints.gridy = row;

layoutConstraints.gridwidth = width;

layoutConstraints.gridheight = height;

layoutConstraints.insets = inset1;

layout.setConstraints(component, layoutConstraints);

add(component);

}

}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值