使用GridBagLayout
,我正在尝试安排我的组件:
但是这些组件就像这样,所有组合在一起的东西:
我以前从未使用GridBagConstraints
字段gridwidth
和gridheight
。我做错了什么?这是一个SSCCE:
import java.awt.Dimension;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import javax.swing.*;
public class GUI extends JFrame {
private GridBagLayout gridBag = new GridBagLayout();
GridBagConstraints constraints = new GridBagConstraints();
private static final String[] ALL_STRINGS = { "B", "A", "C" };
private JButton leftButton = new JButton("<");
private JButton rightButton = new JButton(">");
private JList<String> list = new JList<String>(ALL_STRINGS);
private JList<String> queue = new JList<String>();
private JPanel selectionPanel = new JPanel(gridBag);
private JCheckBox filterBox = new JCheckBox("filterBox");
private JButton clear = new JButton("Clear");
public GUI() {
setWindowProperties();
addComponents();
}
private void setWindowProperties() {
setLayout(gridBag);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(new Dimension(400, 400));
setTitle("GridBagLayout issues");
setResizable(false);
setLocationRelativeTo(null);
}
private void setUpSelectionPanel() {
JLabel listLabel = new JLabel("Quest List");
JLabel queueLabel = new JLabel("Queue");
JScrollPane listScroll = new JScrollPane(list);
JScrollPane queueScroll = new JScrollPane(queue);
Dimension scrollSize = new Dimension(150, 300);
listScroll.setPreferredSize(scrollSize);
queueScroll.setPreferredSize(scrollSize);
constraints.gridx = 0;
constraints.gridy = 0;
gridBag.setConstraints(listLabel, constraints);
constraints.gridx = 0;
constraints.gridy = 1;
constraints.gridwidth = 2;
constraints.gridheight = 3;
gridBag.setConstraints(listScroll, constraints);
constraints.gridx = 2;
constraints.gridy = 1;
gridBag.setConstraints(filterBox, constraints);
constraints.gridx = 2;
constraints.gridy = 2;
gridBag.setConstraints(leftButton, constraints);
constraints.gridx = 2;
constraints.gridy = 3;
gridBag.setConstraints(rightButton, constraints);
constraints.gridx = 2;
constraints.gridy = 4;
gridBag.setConstraints(clear, constraints);
constraints.gridx = 3;
constraints.gridy = 0;
gridBag.setConstraints(queueLabel, constraints);
constraints.gridx = 3;
constraints.gridy = 1;
constraints.gridwidth = 2;
constraints.gridheight = 3;
gridBag.setConstraints(queueScroll, constraints);
selectionPanel.add(listLabel);
selectionPanel.add(listScroll);
selectionPanel.add(filterBox);
selectionPanel.add(leftButton);
selectionPanel.add(rightButton);
selectionPanel.add(clear);
selectionPanel.add(queueLabel);
selectionPanel.add(queueScroll);
}
private void addComponents() {
setUpSelectionPanel();
add(selectionPanel);
}
public static void main(String[] args) {
new GUI().setVisible(true);
}
}
答案 0 :(得分:4)
在添加listScroll后的这些行之后:
constraints.gridwidth = 2;
constraints.gridheight = 3;
您永远不会将它们重置为1,因此所有后续组件都将具有这些约束。只需添加:
constraints.gridwidth = 1;
constraints.gridheight = 1;
到你的filterBox约束中,它们将保留其余组件的方式,直到你需要时更改它们。