[英]Java/Swing layer labels on top if each other
I know this has been asked several times, but none of the solutions have worked for us. 我知道这个问题已经被问过几次了,但是没有一个解决方案对我们有用。 We are recreating a game which has a world map, and is supposed to show flags on every country.
我们正在重新创建一个具有世界地图的游戏,并且该游戏应该在每个国家/地区显示国旗。 We got it working(sort of) by using a graphics method, but this was not persistent, also we couldnt adress a flag by a var name.
我们通过使用图形方法使它正常工作,但这不是持久性的,我们也不能通过变量名来获取标志。
Thats why we want to have every flag in a JLabel
, and draw them inside the gamePane
, but on their specifiy coordinates. 这就是为什么我们要在
JLabel
包含每个标志,并将它们绘制在gamePane
,但要在它们的指定坐标上绘制。 So we need to be able to position with a z-axis. 因此,我们需要能够使用z轴定位。
The GamePane has a JLabel
with an ImageIcon
inside, that should form the background. GamePane有一个内部带有
ImageIcon
的JLabel
,该JLabel
应该构成背景。 On top of that we want to create the flags 最重要的是,我们要创建标志
some code(might not be helpful):- 一些代码(可能没有帮助):
gamePane = new JPanel();
[...]
public void paintFlagLabel() {
for (Country currentCountry : risiko.getCountryList()) {
JLabel flag = new JLabel();
int x = currentCountry.getX();
int y = currentCountry.getY();
if (currentCountry.getOwningPlayer().equals(this.player)) {
flag.setIcon(new ImageIcon(greenFlag));
} else {
flag.setIcon(new ImageIcon(redFlag));
}
String coordinates = "pos " + x + " " + y;
gamePane.add(flag, coordinates);
gamePane.revalidate();
gamePane.repaint();
}
}
We are recreating a game which has a world map, and is supposed to show flags on every country.
我们正在重新创建一个具有世界地图的游戏,并且该游戏应该在每个国家/地区显示国旗。
You can easily add a JLabel to any other component, including a Jlabel. 您可以轻松地将JLabel添加到任何其他组件,包括Jlabel。
The basic code is: 基本代码是:
JLabel background = new JLabel( new ImageIcon(...) );
background.setLayout( null );
JLabel flag = new JLabel( new ImageIcon(...) );
flag.setSize( flag.getPrefferedSize() );
flag.setLocation(....);
background.add( flag );
we couldnt adress a flag by a var name.
我们无法通过var名称获得标志。
You could keep a Hashmap of all the flags: 您可以保留所有标志的哈希表:
Hashmap<String, JLabel> flags = new Hashmap<String, JLabel>()
flags.add("theCountryName", theFlag);
Then when you want to access the flag you simply use the get(...)
method of the Hashmap
. 然后,当您要访问标志时,只需使用
Hashmap
的get(...)
方法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.