gpt4 book ai didi

java - 如何将 Java ComboBox 的宽度设置为与其所在的 JPanel 一样宽?

转载 作者:行者123 更新时间:2023-11-29 07:19:57 25 4
gpt4 key购买 nike

我想知道是否有办法将 ComboBox 的宽度设置为与其所在的 JPanel 一样宽。我有以下代码片段:

    public newPanel() {
setLayout(new GridLayout(2,0));

String[] example = new String[] {"one, "two", "three", "four"};

JComboBox cBox = new JComboBox(levels);
cBox.setPreferredSize(new Dimension(300, 20));

this.add(new JLabel("This is text that goes above the ComboBox:"));
this.add(cBox);
}

您可以看到我说过我希望 ComboBox 的宽度为 300px,但是有没有办法自动将其设置为与其所在的 Panel 一样宽?像cBox.setPreferredWidth(max);(我知道那不存在,只是为了展示我的思维方式)。

最佳答案

is there a way to automatically set it as wide as the Panel it's in?

你可能想让布局管理器来处理这个。

如果您设置首选宽度,GridLayout 将确保组合框水平填充整个面板。

这个片段...

import java.awt.GridLayout;
import javax.swing.*;

class Test {
public static void main(String[] args) {

JFrame frame = new JFrame();
JPanel panel = new JPanel();
panel.setLayout(new GridLayout(2,0));

String[] example = new String[] {"one", "two", "three", "four"};

JComboBox cBox = new JComboBox(example);
//cBox.setPreferredSize(new Dimension(300, 20));

panel.add(new JLabel("This is text that goes above the ComboBox:"));
panel.add(cBox);
panel.setBorder(BorderFactory.createTitledBorder("Panel border"));

frame.setContentPane(panel);

frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setVisible(true);
}
}

...结果

enter image description here

如果这对您来说不够灵活,我建议您使用 GridBagLayout

关于java - 如何将 Java ComboBox 的宽度设置为与其所在的 JPanel 一样宽?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5866814/

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