本文的目的是弄清楚为什么两个按钮都会复制两张图片,这非常奇怪,不应该发生这种情况。那就是主要目标。然后就是找到一个解决方案。谢谢!
这是它的外观图像
我已经制作出最小可复现示例(MRE)。
它在两个按钮上都输出了相同的两张图片,我不知道为什么。
import java.awt.Color;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class GameManager extends JFrame{
private final Map <String, String> images = new HashMap<>(2);
GameManager()
{
images.put("Articuno", "https://i.ya-webdesign.com/images/articuno-transparent-pokemon-xy-17.gif");
images.put("Rayquaza", "https://play.pokemonshowdown.com/sprites/ani-back-shiny/rayquaza.gif");
JPanel pnlPokemonInParty = new JPanel(new GridBagLayout());
GridBagConstraints c = new GridBagConstraints();
//Why does it put both images on both buttons? It actually sets the images on top of one another.
//You can tell which image is in the front and which is behind the other.
//I'm setting the buttons to be transparent. Setting the buttons to not be transparent will cover the the image below it,
//that's how I know they're being stacked on top of one another.
JButton btn1 = gifBtn("Articuno");
JButton btn2 = gifBtn("Rayquaza");
c.gridx = 0;
pnlPokemonInParty.add(btn1, c);
c.gridx = 1;
pnlPokemonInParty.add(btn2, c);
this.add(pnlPokemonInParty);
this.pack();
this.setVisible(true);
}
public JButton gifBtn(String name)
{
final JButton btn = new JButton();
URL url = null;
try {
url = new URL(images.get(name));
} catch (MalformedURLException ex) {
ex.printStackTrace();
}
Icon icon = new ImageIcon(url);
btn.setIcon(icon);
btn.setBackground(new Color(50,50,50,0));
return btn;
}
public static void main(String[] args)
{
GameManager gameManager = new GameManager();
}
}
我可以通过不将JButton的背景色设置为透明来隐藏问题,但这并不能解决问题。
为什么会发生这种情况呢? 我更担心的是两个图像出现在同一个JButton上,但还有另一个问题,当观察图像时,我不知道该如何解释。