gpt4 book ai didi

java - 如何构建 2 个相同宽度的 JButton 实例

转载 作者:行者123 更新时间:2023-12-01 18:46:44 26 4
gpt4 key购买 nike

我有 2 个按钮,一个名为 btnShort,一个名为 btnLong。我希望它们具有相同的宽度,那么最好的选择是什么?

enter image description here

import java.awt.Dimension;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;


public class TestCode2 {

public static void main(String[] args) {

JFrame window = new JFrame("Test2");
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
window.setSize(400, 200);

// ---------------------------------------------------------------------

GridBagLayout layout = new GridBagLayout();
GridBagConstraints constraints = new GridBagConstraints();

JPanel container = new JPanel(layout);
window.add(container);

constraints.gridy = 0;

JButton btnShort = new JButton("Short");
layout.setConstraints(btnShort, constraints);
container.add(btnShort);

constraints.gridy = 1;

JButton btnLong = new JButton("That's a long button");
layout.setConstraints(btnLong, constraints);
container.add(btnLong);

//This one won't work because button dimension is not known yet...
//btnShort.setPreferredSize(new Dimension(btnLong.getWidth(), btnLong.getHeight()));

// ---------------------------------------------------------------------

window.setVisible(true);
}

}

最佳答案

GridBagConstraints 填充属性设置为 GridBagConstraints.HORIZONTAL,以便两个 JButton 组件在容器中占据相同的宽度

constraints.fill = GridBagConstraints.HORIZONTAL;

关于java - 如何构建 2 个相同宽度的 JButton 实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17485533/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com