小编典典

BorderLayout无法正确显示

java

我想要一个JFrame,在左右两侧有一个边框,边框为黑色,宽度为withfOfJFrame / 10。

现在,我的尝试如下所示:

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(JFrame的开始宽度)的1/10。

我究竟做错了什么?还是有更好的方法来做到这一点?


阅读 546

收藏
2020-11-30

共1个答案

小编典典

您可以使用GridBagLayout和适当的权重来获得所需的结果:

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);
            }
        });
    }
}
2020-11-30