gpt4 book ai didi

java - 网格包布局未按我想要的方式显示

转载 作者:搜寻专家 更新时间:2023-11-01 04:04:47 24 4
gpt4 key购买 nike

所以我有 6 个面板,它们都使用网格布局。我使用 gridbaglayout 将它们放在一起,这是我想要的设计

layout

结果它变得一团糟“第二个”面板变得更远向右第三个面板向左挤压了很多,这是一场灾难。这是我的 gridbag 布局代码

    c.gridx = 0; c.gridy = 0;
add (first,c);

c.gridx = 2; //so that the second panel starts from the center and is divided evenly with the first panel
add(second,c);

c.gridx = 0; c.gridy = 1;
add(third,c);

c.gridx = 1;
add(fourth,c);

c.gridx = 2;
add(fifth,c);

c.gridx = 3;
add(sixth,c);

感谢任何帮助。

最佳答案

在您编写 c.gridx = 0 和 c.gridy = 0 时,您忘记指定希望此 JPanel 占据多少列。为了指定它,您应该使用 c.gridwidth = 2,它告诉布局此 JPanel 需要两列的空间。

要得到这样的输出:

GRIDBAGLAYOUTEXAMPLE

这是一个小的工作示例:

import java.awt.*;
import javax.swing.*;
// http://stackoverflow.com/questions/10968853/two-jpanels-in-jframe-one-under-other
public class GridBagLayoutExample
{
// http://stackoverflow.com/questions/10977017/grid-bag-layout-not-displaying-the-way-i-want
private void displayGUI()
{
JFrame frame = new JFrame("GridBagLayout Example");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

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

GridBagConstraints gbc = new GridBagConstraints();
gbc.anchor = GridBagConstraints.FIRST_LINE_START;
gbc.fill = GridBagConstraints.BOTH;
gbc.gridx = 0;
gbc.gridy = 0;
gbc.gridwidth = 2;
gbc.weightx = 0.5;
gbc.weighty = 0.2;

JPanel topLeftPanel = new JPanel();
topLeftPanel.setOpaque(true);
topLeftPanel.setBackground(Color.DARK_GRAY);
contentPane.add(topLeftPanel, gbc);

gbc.gridx = 2;

JPanel topRightPanel = new JPanel();
topRightPanel.setOpaque(true);
topRightPanel.setBackground(Color.BLUE);
contentPane.add(topRightPanel, gbc);

gbc.gridwidth = 1;
gbc.gridx = 0;
gbc.gridy = 1;
gbc.weightx = 0.25;
gbc.weighty = 0.8;

JPanel firstPanel = new JPanel();
firstPanel.setOpaque(true);
firstPanel.setBackground(Color.RED);
contentPane.add(firstPanel, gbc);

gbc.gridx = 1;

JPanel secondPanel = new JPanel();
secondPanel.setOpaque(true);
secondPanel.setBackground(Color.GREEN.darker());
contentPane.add(secondPanel, gbc);

gbc.gridx = 2;

JPanel thirdPanel = new JPanel();
thirdPanel.setOpaque(true);
thirdPanel.setBackground(Color.WHITE);
contentPane.add(thirdPanel, gbc);

gbc.gridx = 3;

JPanel fourthPanel = new JPanel();
fourthPanel.setOpaque(true);
fourthPanel.setBackground(Color.MAGENTA);
contentPane.add(fourthPanel, gbc);

frame.setContentPane(contentPane);
frame.setSize(200, 300);
frame.setLocationByPlatform(true);
frame.setVisible(true);
}

public static void main(String... args)
{
SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
new GridBagLayoutExample().displayGUI();
}
});
}
}

关于java - 网格包布局未按我想要的方式显示,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10977017/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com