GridBagLayout
您可以使用(并使用GridBagConstraint
with a )实现垂直布局(垂直居中gridwidth=REMAINDER
):
import java.awt.FlowLayout;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
public class TestGridBagLayout {
protected void initUI() {
JFrame frame = new JFrame();
JPanel controlPanel = (JPanel) frame.getContentPane();
controlPanel.setLayout(new GridBagLayout());
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridwidth = GridBagConstraints.REMAINDER;
JPanel fromDatePanel = new JPanel(new FlowLayout());
JPanel untilDatePanel = new JPanel(new FlowLayout());
fromDatePanel.add(new JLabel("From - "));
fromDatePanel.add(new JButton("..."));
untilDatePanel.add(new JLabel("Until - "));
untilDatePanel.add(new JButton("..."));
controlPanel.add(fromDatePanel, gbc);
controlPanel.add(untilDatePanel, gbc);
frame.setSize(600, 600);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
TestGridBagLayout testMultiplePanels = new TestGridBagLayout();
testMultiplePanels.initUI();
}
});
}
}
关于添加到 a之间的差异JButton
,这是由于. 返回首选大小,而将返回由无限维度解释的首选大小。JPanel
BoxLayout
getMaximumSize()
BoxLayout
JButton
JPanel
null
BoxLayout
如果你想保留你的BoxLayout
,你可以覆盖JPanel.getMaximumSize()
并返回getPreferredSize()
:
import java.awt.Dimension;
import java.awt.FlowLayout;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
public class TestGridBagLayout {
protected void initUI() {
JFrame frame = new JFrame();
JPanel controlPanel = (JPanel) frame.getContentPane();
controlPanel.setLayout(new BoxLayout(controlPanel, BoxLayout.Y_AXIS));
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel fromDatePanel = new JPanel(new FlowLayout()) {
@Override
public Dimension getMaximumSize() {
return getPreferredSize();
}
};
JPanel untilDatePanel = new JPanel(new FlowLayout()) {
@Override
public Dimension getMaximumSize() {
return super.getMaximumSize();
}
};
fromDatePanel.add(new JLabel("From - "));
fromDatePanel.add(new JButton("..."));
untilDatePanel.add(new JLabel("Until - "));
untilDatePanel.add(new JButton("..."));
controlPanel.add(fromDatePanel);
controlPanel.add(untilDatePanel);
frame.setSize(600, 600);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
TestGridBagLayout testMultiplePanels = new TestGridBagLayout();
testMultiplePanels.initUI();
}
});
}
}