我尝试使用GridBagLayout创建一个使用Swing的布局。
我想放置一个除了Button之外的ComboBox,其中Button的大小是常量,ComboBox填充该行中的所有可用空间:
但是,如果我放大窗口,ComboBox和Button之间会出现空白区域:
如何布置此表单,以便ComboBox填充所有空间,即使调整窗口大小?
Scala中组件的布局代码:
layout(button) = new Constraints() {
gridx = 1
gridy = 0
anchor = GridBagPanel.Anchor.LineEnd
}
layout(comboBox) = new Constraints() {
gridx = 0
gridy = 0
fill = GridBagPanel.Fill.Horizontal
}
layout(centerPanel) = new Constraints() {
gridx = 0
gridy = 1
weighty = 1
weightx = 1
gridwidth = 2
fill = GridBagPanel.Fill.Both
}
答案 0 :(得分:3)
对GUI的该部分使用BorderLayout
。把组合。在CENTER
和LINE_END
中的按钮。
像这样:
import java.awt.BorderLayout;
import javax.swing.*;
import javax.swing.border.*;
public class StretchComboLayout {
public static void main(String[] args) {
Runnable r = new Runnable() {
@Override
public void run() {
JPanel ui = new JPanel(new BorderLayout(2, 2));
ui.setBorder(new EmptyBorder(4, 4, 4, 4));
JPanel controls = new JPanel(new BorderLayout(2, 2));
ui.add(controls, BorderLayout.PAGE_START);
String s = new String(Character.toChars(8594));
String[] items = {"Choice: right " + s + " arrow"};
JComboBox cb = new JComboBox(items);
controls.add(cb, BorderLayout.CENTER);
controls.add(new JButton("Button"), BorderLayout.LINE_END);
JSplitPane sp = new JSplitPane(
JSplitPane.VERTICAL_SPLIT,
new JTextArea(4,40),
new JTextArea(4,40));
ui.add(sp, BorderLayout.CENTER);
JFrame f = new JFrame("Stretch Combo Layout");
f.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
f.setContentPane(ui);
f.pack();
f.setLocationByPlatform(true);
f.setVisible(true);
}
};
SwingUtilities.invokeLater(r);
}
}