我有这个布局使用GridBagLayout
:
public class Example extends JFrame {
public Example() {
Border outline = BorderFactory.createLineBorder(Color.black);
GridBagLayout gbl = new GridBagLayout();
GridBagConstraints gbc = new GridBagConstraints();
JPanel pane = new JPanel(gbl);
gbc.weighty = 1.0;
gbc.weightx = 1.0;
JLabel unitLbl = new JLabel("Unit");
unitLbl.setBorder(outline);
gbc.gridx = 0;
gbc.gridy = 0;
gbc.ipadx = 30;
gbc.ipady = 10;
gbl.setConstraints(unitLbl, gbc);
pane.add(unitLbl);
JLabel typeLbl = new JLabel("Type");
typeLbl.setBorder(outline);
gbc.gridx = 0;
gbc.gridy = 1;
gbc.ipadx = 30;
gbc.ipady = 10;
gbl.setConstraints(typeLbl, gbc);
pane.add(typeLbl);
JTextField unitField = new JTextField();
typeLbl.setBorder(outline);
gbc.gridx = 1;
gbc.gridy = 0;
gbc.ipadx = 30;
gbc.ipady = 10;
gbl.setConstraints(unitField, gbc);
pane.add(unitField);
String[] type = {"All", "Verb", "Noun", "Adjective"};
JComboBox<String> comboBox = new JComboBox<String>(type);
gbc.gridx = 1;
gbc.gridy = 1;
gbc.ipadx = 30;
gbc.ipady = 10;
gbl.setConstraints(comboBox, gbc);
pane.add(comboBox);
add(pane, BorderLayout.CENTER);
setSize(new Dimension(400, 300));
getContentPane().setBackground(Color.WHITE);
setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
new Example();
}
});
}
}
在这个例子中,当运行时,似乎每个组件都在框架的中心。但我想要的是:
- 两个
JLabel
(unitLbl
和typelbl
) 将在框架的左侧 JTextField
和JComboBox
将在两个 的右侧JLabel
,分别相距很小的距离。- 此外,我想
JButton
在网格的位置(3,0)处添加一个新的,但这个位置的高度是两个JLabel
高度之和。这意味着,此按钮高度在“两行”上。
如何修复此代码以实现此目标?请帮我。
谢谢 :)