开发者

How to Set a smaller ImageIcon on a larger imageIcon on a JButton ? while i want the both images to be visible

i want to write a code for the Tanks Game and I have a problem setting a tank.jpg on an existing ImageIcon , casue i want the both images to be visible and showed to the user , it's like :

JButton block = new JButton () ;
blo开发者_运维问答ck.setIcon(new ImageIcon("ground.png")) ;// sets the first image 
block.setIcon(new ImageIcon("tank.png")) ;// sets the second image

but if i write the code like this , the second setIcon will replace the first one , which is what i dont want , any Ideas how to have 2 icons on a JButton at once ? thanks


The easiest way is to combine the two icons into one. You can do this either manually (if you have only few combinations) or write an Icon implementation on your own.

You can e.g. align the two icons side-by-side with the following implementation:

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());
    }
}


Compound Icon gives you more flexibility on how the Icons are painted.


You'll need to combine the images before you set the button icon. How you do that depends upon how you want to composite them. Do you want one on top of the other, or do you want them side by side? Either way, you'll need to do something like this:

BufferedImage groundImage = ImageIO.read(new File("ground.png");
BufferedImage tankImage = ImageIO.read(new File("tank.png"));
Graphics2 g2 = groundImage.createGraphics();
g2.drawImage(x, y, tankImage);

Then groundImage will have tankImage drawn on top of it starting at coordinate (x, y). At that point you can set the button icon to groundImage. (caveat: I just answered this on my iPad, so the code might nit be completely correct)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜