我正试图让垂直,顶部对齐的布局工作。这就是我所拥有的:
JPanel pane = new JPanel();
pane.setLayout(new BoxLayout(pane, BoxLayout.Y_AXIS));
MyImagePanel panelImage = new MyImagePanel();
panelImage.setSize(400, 400);
pane.add(new JComboBox());
pane.add(panelImage);
pane.add(new JButton("1"));
pane.add(new JButton("2"));
pane.add(new JButton("3"));
JFrame frame = new JFrame("Title");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(800, 600);
frame.add(pane);
frame.pack();
frame.setVisible(true);
显示所有控件,但看起来在顶部和底部之间的运行时应用了填充,因此它们在某种程度上垂直居中。这就是我想要的:
-----------------------------------------------------
| ComboBox | |
------------ |
| | |
| Image | |
| | |
------------ |
| Button 1 | Any additional space fills the right |
------------ |
| Button 2 | |
------------ |
| Button 3 | |
------------ |
| |
| Any additional space fills the bottom |
| |
-----------------------------------------------------
如何让BoxLayout这样做?
由于
-------------------------更新--------------------- ----
能够使用这个:
Box vertical = Box.createVerticalBox();
frame.add(vertical, BorderLayout.NORTH);
vertical.add(new JComboBox());
vertical.add(new JButton("1"));
...
得到我想要的东西。
答案 0 :(得分:1)
更合适的LayoutManager是GridBagLayout,但还有其他选项:
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
public class Test3 {
protected static void initUI() {
JPanel pane = new JPanel(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.anchor = GridBagConstraints.NORTHWEST;
gbc.fill = GridBagConstraints.NONE;
gbc.weightx = 0.0;
gbc.weighty = 0.0;
gbc.gridwidth = GridBagConstraints.REMAINDER;
JPanel panelImage = new JPanel() {
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(Color.RED);
g.fillRect(0, 0, 400, 400);
}
};
panelImage.setPreferredSize(new Dimension(400, 400));
pane.add(new JComboBox(), gbc);
pane.add(panelImage, gbc);
pane.add(new JButton("1"), gbc);
pane.add(new JButton("2"), gbc);
// We give all the extra horizontal and vertical space to the last component
gbc.weightx = 1.0;
gbc.weighty = 1.0;
pane.add(new JButton("3"), gbc);
JFrame frame = new JFrame("Title");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(pane);
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
initUI();
}
});
}
}