我需要创建一个 JFrame,其中包含三个 JPanel,如下所示:
有人可以告诉我如何实现这个布局吗?我已经尝试过使用 BorderLayout
,但是在 BorderLayout
,如果我将最上面的 Pane 添加到 BorderLayout.NORTH
,位于中心的 BorderLayout.CENTER
,以及底部的 BorderLayout.SOUTH
,最上面的 Pane 变得太小(高度),而中间的 Pane 变得太大(高度)。
附注我已经制作了 3 个 Pane 并正确设置了它们的首选尺寸。
最佳答案
您可以使用各种东西、复合布局(例如使用两个 BorderLayout
)或其他布局,这取决于您最终想要实现的目标。
为了简单起见,我将使用 GridBagLayout
,例如...
import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class TestLayout {
public static void main(String[] args) {
new TestLayout();
}
public TestLayout() {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
}
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class TestPane extends JPanel {
public TestPane() {
setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridwidth = GridBagConstraints.REMAINDER;
gbc.weightx = 1;
gbc.weighty = 1;
gbc.fill = GridBagConstraints.BOTH;
add(new ABigPanel(), gbc);
gbc.weighty = 0;
gbc.fill = GridBagConstraints.HORIZONTAL;
add(new ASmallPanel(), gbc);
add(new ASmallerPanel(), gbc);
}
}
public class ABigPanel extends JPanel {
public ABigPanel() {
setBackground(Color.RED);
}
@Override
public Dimension getPreferredSize() {
return new Dimension(400, 200);
}
}
public class ASmallPanel extends JPanel {
public ASmallPanel() {
setBackground(Color.GREEN);
}
@Override
public Dimension getPreferredSize() {
return new Dimension(200, 180);
}
}
public class ASmallerPanel extends JPanel {
public ASmallerPanel() {
setBackground(Color.CYAN);
}
@Override
public Dimension getPreferredSize() {
return new Dimension(200, 40);
}
}
}
参见How to Use GridBagLayout了解更多详情
关于Java集布局,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33166142/