我想为坦克游戏编写代码,但在现有 ImageIcon 上设置 Tank.jpg 时遇到问题,因为我希望这两个图像都可见并向用户显示,就像:
JButton block = new JButton () ;
block.setIcon(new ImageIcon("ground.png")) ;// sets the first image
block.setIcon(new ImageIcon("tank.png")) ;// sets the second image
但是如果我这样写代码,第二个 setIcon 将取代第一个,这是我不想要的,有什么想法如何在 JButton 上同时有 2 个图标吗?谢谢
最佳答案
最简单的方法是将两个图标合并为一个。您可以手动执行此操作(如果您只有很少的组合)或自行编写 Icon
实现。
您可以例如使用以下实现并排对齐两个图标:
import java.awt.Component;
import java.awt.Graphics;
import javax.swing.Icon;
public class DoubleIcon implements Icon {
private static final int ICONSPACING = 4;
private final Icon i1;
private final Icon i2;
public DoubleIcon(Icon i1, Icon i2) {
this.i1 = i1;
this.i2 = i2;
}
@Override
public void paintIcon(Component c, Graphics g, int x, int y) {
i1.paintIcon(c, g, x, y + (getIconHeight() - i1.getIconHeight()) / 2);
i2.paintIcon(c, g, x + ICONSPACING + i1.getIconWidth(), y + (getIconHeight() - i2.getIconHeight()) / 2);
}
@Override
public int getIconWidth() {
return i1.getIconWidth() + ICONSPACING + i2.getIconWidth();
}
@Override
public int getIconHeight() {
return Math.max(i1.getIconHeight(), i2.getIconHeight());
}
}
关于java - 如何在 JButton 上的较大 imageIcon 上设置较小的 ImageIcon ?虽然我希望两个图像都可见,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6178406/