swing在调整Java GUI的大小时防止垂直间距
我有一个简单的GUI,我正在尝试为窗口的左侧创建按钮和控件。右侧有一个文本区域,最终将显示内容。左侧包含供用户操作的按钮和控件。我使用了一组布局管理器(他们似乎相当挑剔)来制作我现在拥有的东西
我已经查阅了Oracle关于BoxLayout的文档,这是左侧控件的容器所使用的,我看不到在调整窗口大小时防止按钮间隔的方法。我希望它们在顶部被砸碎,并保持在那里,不留空隙。BoxLayout的“胶水”功能并不像你想象的那样,它应该被称为橡皮筋
我的问题是,当屏幕变大时,如何保持左边的内容不被越来越宽的分隔
我的GUI:
public class TestCode extends JFrame{
JTextArea textArea = new JTextArea ();
JComboBox <String> typeComboBox;
JTextField searchField;
JTextField fileField;
public TestCode() {
System.out.println ("In constructor");
setTitle ("GUI Test");
setSize (600, 300);
setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
setVisible (true);
JScrollPane scrollPane = new JScrollPane(textArea);
add(scrollPane, BorderLayout.CENTER);
JButton readButton = new JButton("Read File");
JButton displayButton = new JButton("Display");
JButton searchButton = new JButton("Search");
searchField = new JTextField(10);
fileField = new JTextField(15);
typeComboBox = new JComboBox <String> ();
typeComboBox.addItem("Index");
typeComboBox.addItem("Type");
typeComboBox.addItem("Name");
JPanel container = new JPanel();
container.setLayout(new BoxLayout(container, BoxLayout.Y_AXIS));
JPanel filePanel = new JPanel();
filePanel.setLayout(new FlowLayout(FlowLayout.LEFT));
filePanel.add(new JLabel("Source file:", SwingConstants.RIGHT));
filePanel.add(fileField);
filePanel.add(readButton);
JPanel displayPanel = new JPanel();
displayPanel.setLayout(new FlowLayout(FlowLayout.LEFT));
displayPanel.add(new JLabel("Display data:", SwingConstants.RIGHT));
displayPanel.add(displayButton);
JPanel searchPanel = new JPanel();
searchPanel.setLayout(new FlowLayout(FlowLayout.LEFT));
searchPanel.add(new JLabel ("Search target"));
searchPanel.add(Box.createHorizontalBox());
searchPanel.add(searchField);
searchPanel.add(typeComboBox);
searchPanel.add(Box.createHorizontalBox());
searchPanel.add(searchButton);
container.add(filePanel);
container.add(displayPanel);
container.add(searchPanel);
add(container, BorderLayout.WEST);
validate();
}
# 1 楼答案
如果固定使用方框布局,则可以使用方框。Filler创建一个空白区域并将其添加到左侧容器中。检查标题自定义框下的oracle文档here。填充物。在代码中,添加filePanel、displayPanel、searchPanel后,请添加一个首选大小大于支持的分辨率的填充符。下面是添加了填充符的代码,以便在调整大小时内容间距保持不变
另一方面,您可以使用Mig布局并使用“包裹”来实现相同的行为,无需特殊填充物或胶水
# 2 楼答案
BoxLayout使用preferredSize以及最小和最大尺寸来显示布局。在您的情况下,随着可用空间的增加,面板将从首选尺寸增加到最大尺寸。要防止这种情况发生,您可以执行以下操作:
尽管更好的解决方案是覆盖每个面板的
getMaximumSize()
以返回getPreferredSize()
。现在,当您可能在不同的LAF中使用您的应用程序时,您永远不会看到每个面板的首选大小可能会发生变化# 3 楼答案
Camickrs的解决方案才是出路。要减少空间,可以对其进行增强,并在将所有组件添加到面板后使用面板/长方体的组件流: