简体   繁体   中英

Can't draw more than one instance

I'm trying to set up a menu system with buttons; however, only one button is displayed right.

Well I found the problem, I can't create multiple instances of the Button class from one class or it's sub-classes. If I do that it doesn't create the second instance right and it will then have a missing background image. Could that have to do with the fact that I made the Button class a standart class?

Here is the main portion of the Button class, all I took out where get methods which return the values of the things in this class.

public class Button {
private int x, y;
private int width, height;
private Image sprite;
private data.ImageControl Image = new data.ImageControl();
private String text = "";

public Button() {
    sprite = Image.getImage("game/menu/btn.png");
}

public void setImage(String file) {
    sprite = Image.getImage(file);
}

public void draw(Graphics2D g) {
    g.drawImage(sprite, x, y, null);
    Font_LARGE font = new Font_LARGE();

    //Find text pos
    int stringX, stringY;
    int textWidth;
    textWidth = text.length() * 14;

    stringX = x + ((width / 2) - (textWidth / 2));
    stringY = y + ((height / 2) - 8);

    font.drawString(g, text, stringX, stringY);
}

And here is the code for where I get the image from:

public Image getImage(String filename) {
    Image img;
    try {
        ImageIcon i = new ImageIcon(getClass().getResource("sprite/" + filename));
        img = i.getImage();
    } catch(Exception e) {
        e.printStackTrace();
        System.err.println("ERROR - Unable to load image at " + filename + " loading empty image.");
        ImageIcon i = new ImageIcon(getClass().getResource("sprite/Physix/noImage.png"));
        img = i.getImage();
    }

    return img;
}

What are the x and y positions?

It looks to me that you draw one button on top of the other one.

I have fixed the problem now by just drawing the button background outside of the button class. I have still no idea why it doesn't work, but this way it works.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM