对于第一种情况,您可以在 上使用简单GridLayout
的JPanel
,3 Rows
每个都有单独JPanel
的带有FlowLayout
约束的FLowLayout.LEFT
. 看看这个代码示例:
import java.awt.*;
import javax.swing.*;
public class ExampleLayout
{
private void displayGUI()
{
JFrame frame = new JFrame("Example Layout");
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
JPanel contentPane = new JPanel();
contentPane.setLayout(new GridLayout(0, 1, 5, 5));
JPanel topPanel = new JPanel();
topPanel.setLayout(new FlowLayout(FlowLayout.LEFT, 5, 5));
JRadioButton rbut1 = new JRadioButton("RadioButton 1", false);
JTextField tfield1 = new JTextField(10);
JButton button1 = new JButton("Button 1");
topPanel.add(rbut1);
topPanel.add(tfield1);
topPanel.add(button1);
JPanel middlePanel = new JPanel();
middlePanel.setLayout(new FlowLayout(FlowLayout.LEFT, 5, 5));
JRadioButton rbut2 = new JRadioButton("RadioButton 2", false);
JTextField tfield2 = new JTextField(10);
JButton button2 = new JButton("Button 2");
middlePanel.add(rbut2);
middlePanel.add(tfield2);
middlePanel.add(button2);
JPanel bottomPanel = new JPanel();
bottomPanel.setLayout(new FlowLayout(FlowLayout.LEFT, 5, 5));
JCheckBox cbox = new JCheckBox("CheckBox 1", false);
bottomPanel.add(cbox);
contentPane.add(topPanel);
contentPane.add(middlePanel);
contentPane.add(bottomPanel);
frame.setContentPane(contentPane);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String... args)
{
EventQueue.invokeLater(new Runnable()
{
@Override
public void run()
{
new ExampleLayout().displayGUI();
}
});
}
}
输出 :
对于第二种情况,只需将前两个组件添加到JPanel
具有默认布局。对于第三个组件,只需将组件添加到 have 上JPanel
,GridBagLayout
没有任何限制。
编辑#1:
或者,您可以将这种方法用于您的第二个 block。
import java.awt.*;
import javax.swing.*;
public class ExampleLayout
{
private void displayGUI()
{
JFrame frame = new JFrame("Example Layout");
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
JPanel contentPane = new JPanel();
contentPane.setLayout(new BorderLayout(5, 5));
JPanel basePanel = new JPanel();
basePanel.setLayout(new GridLayout(0, 1, 5, 5));
JPanel topPanel = new JPanel();
//topPanel.setLayout(new FlowLayout(FlowLayout.LEFT, 5, 5));
JLabel label1 = new JLabel("Label 1", JLabel.CENTER);
JRadioButton rbut1 = new JRadioButton("RadioButton 1", false);
topPanel.add(label1);
topPanel.add(rbut1);
JPanel middlePanel = new JPanel();
middlePanel.setLayout(new GridBagLayout());
JButton button1 = new JButton("Button 1");
middlePanel.add(button1);
basePanel.add(topPanel);
basePanel.add(middlePanel);
contentPane.add(basePanel, BorderLayout.PAGE_START);
frame.setContentPane(contentPane);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String... args)
{
EventQueue.invokeLater(new Runnable()
{
@Override
public void run()
{
new ExampleLayout().displayGUI();
}
});
}
}