我想知道是否有办法将 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);
}
}
...结果
如果这对您来说不够灵活,我建议您使用 GridBagLayout
。
关于java - 如何将 Java ComboBox 的宽度设置为与其所在的 JPanel 一样宽?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5866814/