如何使用GridLayout和多个面板?

时间:2018-09-23 00:57:20

标签: java swing layout-manager grid-layout

如何使用多个 list.addListener((ListChangeListener<String>) c -> { // If the size of the list is less than 1, disable the button; otherwise enable it button.setDisable(c.getList().size() < 1); }); 容器使此代码看起来像这样?

这是我的代码应该是什么样的图像,但我无法弄清楚。 我只能使用JPanelGridLayoutBorderLayout。作为初学者,我们仅涉及基本概念,但我需要更多帮助。

我也不允许使用FlowLayout。我感谢所有的帮助。

1 个答案:

答案 0 :(得分:3)

解决复杂计算任务的一种常见策略是将它们分解为细小,定义明确的可管理任务。分而治之。
这也适用于gui:将设计分为较小的,易于布局的容器。
在这种情况下,请考虑将设计分为嵌套在主JPanel中的3个区域(JPanel):

enter image description here

如果您不能使用GridBagLayout,则可以使用BoxLayout来实现底部面板。
BoxLayout对于主面板也是有效的选项,以允许不同的子面板(顶部,中间,底部)高度。

演示:

import java.awt.Color;
import java.awt.Dimension;
import java.awt.GridLayout;
import javax.swing.BoxLayout;
import javax.swing.JFrame;
import javax.swing.JPanel;

public class Lab1 extends JFrame
{
    public Lab1() {

        setDefaultCloseOperation(EXIT_ON_CLOSE);
        JPanel main = new JPanel(new GridLayout(3,1));
        //to allow different child-panels height use BoxLayout
        //BoxLayout boxLayout = new BoxLayout(main, BoxLayout.Y_AXIS);

        add(main);
        JPanel top = new JPanel(new GridLayout(1,3));
        main.add(top);
        top.add(getPanel(Color.RED));
        top.add(getPanel(Color.GREEN));
        top.add(getPanel(Color.BLUE));

        JPanel center = new JPanel(new GridLayout(1,4));
        main.add(center);
        center.add(getPanel(Color.YELLOW));
        center.add(getPanel(Color.CYAN));
        center.add(getPanel(Color.BLACK));
        center.add(getPanel(Color.LIGHT_GRAY));

        JPanel bottom = new JPanel();
        bottom.setLayout(new BoxLayout(bottom, BoxLayout.LINE_AXIS));
        main.add(bottom);

        bottom.add(getPanel(Color.PINK));
        JPanel rightPane =  getPanel(Color.MAGENTA);
        rightPane.setPreferredSize(new Dimension(900, 200));
        bottom.add(rightPane);

        pack();
        setVisible(true);
    }

    private JPanel getPanel(Color color) {
        JPanel panel = new JPanel();
        panel.setBackground(color);
        panel.setPreferredSize(new Dimension(300, 200));
        return panel;
    }

    public static void main(String args[])
    {
        new Lab1();
    }
}
相关问题