How do I use GridLayout and multiple Panels?

為{幸葍}努か 提交于 2021-01-27 21:06:20

问题


How do I use multiple JPanel containers to make this code look like this?

This is the image of what my code is supposed to be like but I cant figure it out. I can only use GridLayout, BorderLayout and FlowLayout. As a beginner, We've only been over basic concepts but I need more help.

I am also not permitted to use GridBagLayout. I appreciate all the help.


回答1:


A common strategy to solve complex computing tasks, is to break them into small, well defined manageable tasks. Divide and conquer.
This also applies to gui: break the design into small, easy to layout containers.
In this case, consider dividing the design into 3 areas (JPanels) nested in a main JPanel:

If you can't use GridBagLayout you can implement bottom panel using BoxLayout.
BoxLayout is a valid option also for main panel, to allow for different child panels (top, center, bottom) height.

Demo:

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();
    }
}


来源:https://stackoverflow.com/questions/52462093/how-do-i-use-gridlayout-and-multiple-panels

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!