java - GridBagLayout 无法正确布局

标签 java swing layout-manager gridbaglayout

我是 GridBagLayout 的新手,但我尝试使用我可以使用的标准约定 找到哪个是在一张网格纸上画出我的想法,然后尝试将网格值转换成网格包...

我的目标是使布局如下所示:

Desired layout

目前看起来像这样:

Actual layout

知道为什么吗?

如果您想到左上角为 0,0 的网格,我正在寻找的确切尺寸 对于

  1. 目标图片面板中的红色:从第0列开始,跨越10列,高度为1行
  2. 对于黑色面板:从第 0 列第 1 行开始,跨越 10 列,高度为 20 行
  3. 对于蓝色面板:从第 0 列第 21 行开始,跨越 10 列,高度为 1
  4. 对于绿色列:从第 10 列第 0 行开始,跨越 16 列,高度为 7
  5. 对于紫色列:从第 10 列第 7 行开始,跨越 16 列,高度为 16

这是我的源代码:

GBC是一个扩展GridBagConstraints的辅助类,使用的构造函数是

GBC(int startingX,int startingY,int width,int height)

 /*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

import java.awt.Color;
import java.awt.EventQueue;
import java.awt.GridBagLayout;
import java.awt.Rectangle;
import javax.swing.JApplet;
import javax.swing.JLabel;
import javax.swing.JPanel;

public class Demo extends JApplet
{

    JPanel panel1 = new JPanel();
    JPanel panel2 = new JPanel();
    JPanel panel3 = new JPanel();
    JPanel panel4 = new JPanel();
    JPanel panel5 = new JPanel();

    public void init()
    {
        EventQueue.invokeLater(new Runnable()
        {
            public void run()
            {
                initComponents();
            }
        });
    }

    public void initComponents()
    {
        //set the layout of the content pane to gridbag layout
        GridBagLayout gridBag = new GridBagLayout();
        getContentPane().setLayout(gridBag);

        Rectangle rect = getContentPane().getBounds();

        panel1.setBackground(Color.green);
        panel2.setBackground(Color.black);
        panel3.setBackground(Color.red);
        panel4.setBackground(Color.orange);
        panel5.setBackground(Color.yellow);

        add(panel4, new GBC(10, 0, 16, 7).setFill(GBC.BOTH).setWeight(1.0, 1.0));
        add(panel1, new GBC(0, 0, 10, 1).setFill(GBC.BOTH).setWeight(1.0, 1.0));
        add(panel3, new GBC(0, 21, 10, 1).setFill(GBC.BOTH).setWeight(1.0, 1.0));
        add(panel2, new GBC(0, 1, 10, 20).setFill(GBC.BOTH).setWeight(1.0, 1.0));
        add(panel5, new GBC(10, 7, 16, 16).setFill(GBC.BOTH).setWeight(1.0, 1.0));
    }
}

任何帮助将不胜感激(但请解释你的逻辑)

最佳答案

好吧,您可以使用 GridBagLayout 轻松完成此操作。

考虑到 contentPaneGridBagLayout 作为其布局,您现在可以将 JPanel 分为三个部分。单个左侧 JPanel(带有 GridBagLayout,其中将包含那些 REDBLACKBLUE JPanel),右侧由两个 JPanel 组成,即 GREENMAGENTA

 ------------------------
|  left   | green JPanel |
| JPanel  |______________|
|  with   |magenta Jpanel|
|3 JPanel |              |
|________________________|

现在左边的 JPanel 将放置 REDBLACKBLUE JPanel自身,使用 GridBagLayout 作为其 Layout ManagerRED 和 BLUE 具有 weighty = 0.1,并且 黑色 weighty = 0.8

查看示例代码:

import java.awt.*;
import javax.swing.*;

public class GridBagExample {
    private JPanel leftPanel;
    private JPanel redPanel;
    private JPanel blackPanel;
    private JPanel bluePanel;
    private JPanel greenPanel;
    private JPanel magentaPanel;

    private GridBagConstraints gbc;

    public GridBagExample() {
        gbc = new GridBagConstraints();
        gbc.anchor = GridBagConstraints.FIRST_LINE_START;
    }

    private void displayGUI() {
        JFrame frame = new JFrame("GridBagLayout Example");
        frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);

        JPanel contentPane = new JPanel(new GridBagLayout());

        leftPanel = getPanel(Color.WHITE);
        leftPanel.setLayout(new GridBagLayout());
        redPanel = getPanel(Color.RED.darker());
        blackPanel = getPanel(Color.BLACK);
        bluePanel = getPanel(Color.CYAN.darker().darker());
        greenPanel = getPanel(Color.GREEN.darker().darker());
        magentaPanel = getPanel(Color.MAGENTA);
        /**
          * @param : 
          * leftPanel : JPanel (with GridBagLayout), on which
          *               all other components will be placed.
          * redPanel : JPanel, which will be added to the leftPanel
          * 0 : specifies the grid X, which in this case is 0
          * 0 : specifies the grid Y, which in this case is 0
          * 1 : specifies the width for this grid (cell), we keeping 
          *     this default as 1
          * 1 : specifies the height for this grid (cell), we keeping
          *     this default as 1
          * GridBagConstraints.BOTH : allows JPanel to expand in both
          *     directions as the containing container expands (in 
          *     this case redPanel will expand both HORIZONTALLY and
          *     VERTICALLY, as leftPanel will expand)
          * weightx : This is the actual width the redPanel will occupy
          *           relative to all other components on the leftPanel
          * weighty : This is the actual height the redPanel will occupy
          *           relative to all other components on the leftPanel
          */
        addComp(leftPanel, redPanel, 0, 0, 1, 1,
                        GridBagConstraints.BOTH, 1.0, 0.1);
        addComp(leftPanel, blackPanel, 0, 1, 1, 1,
                        GridBagConstraints.BOTH, 1.0, 0.8);
        addComp(leftPanel, bluePanel, 0, 2, 1, 1,
                        GridBagConstraints.BOTH, 1.0, 0.1);
        addComp(contentPane, leftPanel, 0, 0, 1, 2,
                        GridBagConstraints.BOTH, 0.5, 1.0);
        addComp(contentPane, greenPanel, 1, 0, 1, 1,
                        GridBagConstraints.BOTH, 0.5, 0.3);
        addComp(contentPane, magentaPanel, 1, 1, 1, 1,
                        GridBagConstraints.BOTH, 0.5, 0.7);

        frame.setContentPane(contentPane);
        /*
         * Once you will add components to these
         * JPanels, then use pack(), instead of
         * setSize(). The use of the latter is 
         * just for illustration purpose only
         */
        //frame.pack();
        frame.setSize(300, 300);
        frame.setLocationByPlatform(true);
        frame.setVisible(true);
    }

    private void addComp(JPanel panel, JComponent comp,
                            int x, int y, int width, int height,
                            int fill, double weightx, double weighty) {
        gbc.gridx = x;
        gbc.gridy = y;
        gbc.gridwidth = width;
        gbc.gridheight = height;
        gbc.fill = fill;
        gbc.weightx = weightx;
        gbc.weighty = weighty;

        panel.add(comp, gbc);
    }

    private JPanel getPanel(Color backColor) {
        JPanel panel = new JPanel();
        panel.setOpaque(true);
        panel.setBackground(backColor);

        return panel;
    }

    public static void main(String[] args) {
        Runnable runnable = new Runnable() {
            @Override
            public void run() {
                new GridBagExample().displayGUI();
            }
        };
        EventQueue.invokeLater(runnable);
    }
}

这是相同的输出:

GRIDBAGLAYOUTIMAGE

关于java - GridBagLayout 无法正确布局,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17372068/

相关文章:

java - Java中从多个类绘制到主类

java - 强制更新 JList

java - 如何在两个平台上运行java程序?

java - 如何保持 2 个 JPanel 彼此垂直对齐?

java - 前几个微软翻译器 API 请求成功,然后调用失败并抛出 NoArgument 异常且 appid 无效

java - 信息图标

java - Swing游戏布局问题

java - Android JSON解析parcelable列表

java - 如何从基础应用程序访问方法?

java - 如何获取ContainerRequest中的session Object才能使用注解@RolesAllowed(Role_user)?