使用GridBagLayout
,我正在尝试像这样安排我的组件:
但是组件变成了这样,所有的东西都混在一起了:
我以前从未使用过这些GridBagConstraints
字段。我做错了什么?这是一个SSCCE:gridwidth
gridheight
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);
}
}