BorderLayout无法正确显示 [英] BorderLayout doesn't show correctly
问题描述
我想要一个JFrame,左边和右边有一个边框,颜色为黑色,宽度为withfOfJFrame / 10。
I want to have a JFrame, where on the left and the right there is a border that has the color black and a width of withfOfJFrame/10.
现在,我的尝试看起来像这样:
Now, my try at it looks like this:
JFrame f = new JFrame();
f.setSize(800, 600);
f.setLayout(new BorderLayout());
JPanel leftBorder = new JPanel();
JPanel rightBorder = new JPanel();
leftBorder.setBackground(Color.black);
rightBorder.setBackground(Color.black);
leftBorder.setSize(f.getWidth()/10, f.getHeight());
rightBorder.setSize(f.getWidth()/10, f.getHeight());
JPanel center = new JPanel();
center.setBackground(Color.red);
f.add(leftBorder, BorderLayout.WEST);
f.add(center, BorderLayout.CENTER);
f.add(rightBorder, BorderLayout.EAST);
f.setVisible(true);
这会在左侧和右侧添加黑色边框,但该边框具有固定大小并且不会调整窗口大小时重新计算。大小甚至不是800的1/10(JFrame的起始宽度)。
This adds a black border on the left and the right, but that border has a fixed size and doesn't recalculate when resizing the window. The size isn't even 1/10 of 800 (the beginning width of the JFrame).
我做错了什么?或者还有更好的方法吗?
What am I doing wrong? Or is there even a better way to do this?
推荐答案
您可以使用 GridBagLayout
和适当的权重:
You may achieve the desired result with a GridBagLayout
and appropriate weights:
public class Snippet {
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
JFrame f = new JFrame();
f.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
JPanel leftBorder = new JPanel();
JPanel rightBorder = new JPanel();
leftBorder.setBackground(Color.black);
rightBorder.setBackground(Color.black);
JPanel center = new JPanel();
center.setBackground(Color.red);
f.setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.fill = GridBagConstraints.BOTH;
gbc.weighty = 1.0;
gbc.gridy = 0;
gbc.gridwidth = 1;
gbc.gridheight = 1;
gbc.gridx = 0;
gbc.weightx = 0.1;
f.add(leftBorder, gbc);
gbc.gridx = 1;
gbc.weightx = 0.8;
f.add(center, gbc);
gbc.gridx = 2;
gbc.weightx = 0.1;
f.add(rightBorder, gbc);
f.pack();
f.setVisible(true);
}
});
}
}
这篇关于BorderLayout无法正确显示的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!