Cactus
Cactus

Reputation: 11

How to put an image onto a Jbutton

I'm having a lot of trouble figuring out how to code this simple slot machine on java, the first problem which should be the easiest to resolve is putting 3 .png images onto JButton's when i run the program on eclipse. all the files are in the source folder as well.

Here's what my code looks like now:

JButton b = new JButton("Green.png");

window.getContentPane().add(b);
JButton c = new JButton("Red.png");
window.getContentPane().add(c);
JButton d = new JButton("Purple.png");
window.getContentPane().add(d);
JButton z = new JButton();
window.getContentPane().add(z);
JButton a = new JButton("Spin");
window.getContentPane().add(a);
JButton y = new JButton();
window.getContentPane().add(y);

Random random = new Random();


ActionListener x = new EventHandler();
a.addActionListener(x);

Upvotes: 0

Views: 101

Answers (1)

David Siro
David Siro

Reputation: 1906

You' re using wrong constructor for JButton. That one sets just the caption.

Use the constructor that allows you to set text and the icon.

ImageIcon icon = createImageIcon("images/middle.gif",
                                 "a pretty but meaningless splat");
label1 = new JButton("Image and Text", icon);

/** Returns an ImageIcon, or null if the path was invalid. */
protected ImageIcon createImageIcon(String path,
                                           String description) {
    java.net.URL imgURL = getClass().getResource(path);
    if (imgURL != null) {
        return new ImageIcon(imgURL, description);
    } else {
        System.err.println("Couldn't find file: " + path);
        return null;
    }
}

Upvotes: 2

Related Questions