gpt4 book ai didi

Java:如何在 GridLayout 中嵌套 JPanel?

转载 作者:搜寻专家 更新时间:2023-11-01 03:06:28 25 4
gpt4 key购买 nike

我想知道如何使用 GridLayout 嵌套 JPanel。它应该是这样的。

enter image description here

到目前为止,我通过两种方式解决了这个问题,

  • 使用 JPanel
  • 使用 JLabel

并且它们都不起作用(仅显示创建的第一个面板)。

这是 JPanel 方法的代码:

    int x=20, y=20;
JPanel [] panels = new JPanel[3];
JLabel animal = new JLabel(new ImageIcon(getClass().getResource("Pictures/animal.gif")));
JLabel map = new JLabel(new ImageIcon(getClass().getResource("Pictures/map.gif")));
JLabel mountain = new JLabel(new ImageIcon(getClass().getResource("Pictures/mountain.gif")));

for(int i=0;i<panels.length;i++)
{
if(i>0)
{
x+=x;
y+=y;
}
panels[i] = new JPanel(new GridLayout(2,2));
panels[i].setPreferredSize(new Dimension(x,y));

if(i==0)
panels[i].add(new JPanel());

else
panels[i].add(panels[i-1]);

panels[i].add(mountain);
panels[i].add(map);
panels[i].add(animal);
}
add(panels[2]);

最佳答案

一个选项是创建一个类,该类将代表一个面板,该面板被划分为带有图像的网格。唯一的问题是左上象限通常包含嵌套面板,在某些时候您希望它只包含一个空白面板。所以也许是这样的(除非进行各种优化):

 class GridPanel extends JPanel{

JLabel mountain, map, animal;

public GridPanel(JPanel panel){
super();
setLayout(new GridLayout(2, 2));
animal = new JLabel(new ImageIcon(getClass().getResource("pictures/animal.gif")));
map = new JLabel(new ImageIcon(getClass().getResource("pictures/map.gif")));
mountain = new JLabel(new ImageIcon(getClass().getResource("pictures/mountain.gif")));
add(panel);
add(mountain);
add(map);
add(animal);
}

}

请注意,它接受要显示在网格左上角的面板。然后可以使用指定的面板调用它。因此,在您要创建主面板的位置:

   JPanel grid = new GridPanel(new JPanel()); //initial
for(int i = 1; i <= 5; i++){
grid = new GridPanel(grid);
}
add(grid);

初始网格是使用空白 JPanel 创建的。并且每个后续网格都将包含前一个作为左上面板。您必须调整图像大小等,甚至可能避免多次加载图像等。但这是另一个问题。此示例显示 5 个嵌套面板。

为了清楚起见,您应该使用 ImageIO 加载一次图像并重复使用这些图像。例如,您可以在主类中创建这样的 BufferedImage:

  BufferedImage mointainImg = ImageIO.read(new File("pictures/mountain.gif"));

当你想创建 JLabel 时,你可以这样做:

  mountain = new JLabel(new ImageIcon(mountainImg));

优点是您可以根据需要对图像进行一些操作。

关于Java:如何在 GridLayout 中嵌套 JPanel?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20662881/

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