Gridlayout超出其大小

问题描述 投票:0回答:1

我创建了JPanel并将布局设置为Gridlayout,将其设置为具有3行和5列。我添加到此JPanel 11对象,它显示3行,每行显示4列。我希望对象以5列的3行显示。

softwarePanel = new JPanel();
softwarePanel.setLayout(new GridLayout(3, 5, 15, 15));
softwarePanel.add(new object());
... //Add here 10 times
java swing layout-manager grid-layout
1个回答
0
投票

解决方案是为网格布局的其余插槽添加某种填充物。 3行5列的网格布局可以包含3x5 = 15个组件。由于您添加了11个组件,因此有4个插槽/位置为空。在这些位置上使用填充物将为您提供所需的结果。

请参见我的示例:

public static void main(String[] args) {
    SwingUtilities.invokeLater(() -> {
        JFrame frame = new JFrame();
        JPanel panel = new JPanel(new GridLayout(3, 5));
        for (int i = 0; i < 11; i++) {
            JLabel label = new JLabel("something");
            label.setBorder(BorderFactory.createLineBorder(Color.green));
            panel.add(label);
        }

        for (int i = 0; i < 3 * 5 - panel.getComponentCount(); i++) {
            panel.add(Box.createRigidArea(new Dimension()));
        }
        frame.add(panel);

        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setLocationByPlatform(true);
        frame.pack();
        frame.setVisible(true);
    });
}

结果:

enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.