也许有不同的方法可以实现同样的目标,但对我来说,使用
GridBagLayout
看见
How to Use GridBagLayout
更多细节
import java.awt.Color;
import java.awt.Component;
import static java.awt.Component.TOP_ALIGNMENT;
import java.awt.Dimension;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import javax.swing.BorderFactory;
import javax.swing.BoxLayout;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class Main extends JFrame {
private static final long serialVersionUID = 1L;
public Main() {
setTitle("Paddle Events");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(400, 200);
setLocation(100, 100);
// nesting enables me to see the border of the panel
getContentPane().add(getMainPanel());
setVisible(true);
}
private Component getMainPanel() {
JPanel panel = new JPanel();
panel.add(getGreenPanel());
panel.add(getDarkGrayPanel());
return panel;
}
private JPanel getGreenPanel() {
JPanel panel = new JPanel(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.weighty = 1;
gbc.anchor = gbc.PAGE_START;
gbc.insets = new Insets(4, 2, 4, 2);
panel.setBorder(BorderFactory.createLineBorder(Color.green));
panel.setPreferredSize(new Dimension(175, 100));
panel.add(getWrapperA(), gbc);
panel.add(getWrapperB(), gbc);
panel.add(getWrapperC(), gbc);
return panel;
}
private JPanel getDarkGrayPanel() {
JPanel panel = new JPanel(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.weighty = 1;
gbc.anchor = gbc.PAGE_START;
gbc.insets = new Insets(4, 2, 4, 2);
panel.setBorder(BorderFactory.createLineBorder(Color.darkGray));
panel.setPreferredSize(new Dimension(150, 70));
panel.add(getWrapperA(), gbc);
panel.add(getWrapperB(), gbc);
panel.add(getWrapperC(), gbc);
return panel;
}
private Component getWrapperA() {
JPanel panel = new JPanel();
panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));
panel.setBorder(BorderFactory.createLineBorder(Color.black));
panel.add(new JLabel("label 1"));
panel.add(new JLabel("label 2"));
panel.add(new JLabel("label 3"));
return panel;
}
private Component getWrapperB() {
JPanel panel = new JPanel();
panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));
panel.setBorder(BorderFactory.createLineBorder(Color.blue));
panel.setAlignmentY(TOP_ALIGNMENT); // pointless
panel.add(new JLabel("label 4"));
panel.add(new JLabel("label 5"));
return panel;
}
private Component getWrapperC() {
JPanel panel = new JPanel();
panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));
panel.setBorder(BorderFactory.createLineBorder(Color.red));
panel.add(new JLabel("label 6"));
return panel;
}
public static void main(String[] args) {
new Main();
}
}