添加叠加的 JLabel
Adding Overlayed JLabels
我正在创建一个 swing 应用程序(我知道 rip),并想将 2 个 JLabel 放在彼此之上。这是场景
该游戏是一个岛屿的鸟瞰图,岛屿被分成方格...现在在每个方格上,可以有许多 1 个物品和 1 个动物。我创建了两个 JLabel
JLabel animal = new JLabel();
JLabel item = new JLabel();
然后使用animal.setIcon(...);
设置他们的形象。现在一切正常,但我想在动物标签上放置一个图像,这样我就可以在同一个网格正方形上看到两个。
我正在使用扩展 JPanel 在 class 中编写以下代码,稍后我将其添加到 jframe(这是网格广场 class)
if(inputItem!= null){
try{
imgItem = ImageIO.read(inputItem);
itemLabel.setIcon(new ImageIcon(imgItem.getScaledInstance(this.getWidth(), this.getHeight(), Image.SCALE_SMOOTH)));
this.add(itemLabel);
}catch(Exception e){
//do something
}
}
所以这很好用。我也为 inputAnimal 和 imgAnimal 变量做了一些非常相似的事情。只是想知道如何将它们添加到彼此之上。我试过简单地按顺序添加它们,但这不起作用。
提前致谢
Now on each of these grid squares, there can be many 1 item and 1 animal. Ive created two JLabels
您可以使用 OverlayLayout
。它允许您在同一面板上沿 Z 轴堆叠组件。
或者你可以利用组件之间的 Swing 父/子关系,将一个标签添加到另一个标签,只要父标签使用布局管理器即可:
animal.setLayout(new BorderLayout() );
animal.add( item );
gridSquare.add( animal );
我正在创建一个 swing 应用程序(我知道 rip),并想将 2 个 JLabel 放在彼此之上。这是场景
该游戏是一个岛屿的鸟瞰图,岛屿被分成方格...现在在每个方格上,可以有许多 1 个物品和 1 个动物。我创建了两个 JLabel
JLabel animal = new JLabel();
JLabel item = new JLabel();
然后使用animal.setIcon(...);
设置他们的形象。现在一切正常,但我想在动物标签上放置一个图像,这样我就可以在同一个网格正方形上看到两个。
我正在使用扩展 JPanel 在 class 中编写以下代码,稍后我将其添加到 jframe(这是网格广场 class)
if(inputItem!= null){
try{
imgItem = ImageIO.read(inputItem);
itemLabel.setIcon(new ImageIcon(imgItem.getScaledInstance(this.getWidth(), this.getHeight(), Image.SCALE_SMOOTH)));
this.add(itemLabel);
}catch(Exception e){
//do something
}
}
所以这很好用。我也为 inputAnimal 和 imgAnimal 变量做了一些非常相似的事情。只是想知道如何将它们添加到彼此之上。我试过简单地按顺序添加它们,但这不起作用。
提前致谢
Now on each of these grid squares, there can be many 1 item and 1 animal. Ive created two JLabels
您可以使用 OverlayLayout
。它允许您在同一面板上沿 Z 轴堆叠组件。
或者你可以利用组件之间的 Swing 父/子关系,将一个标签添加到另一个标签,只要父标签使用布局管理器即可:
animal.setLayout(new BorderLayout() );
animal.add( item );
gridSquare.add( animal );