Xantrax
Xantrax

Reputation: 219

Unsure about adding icons to JButton in JAVA

I'm trying to make a chessboard, but I can't seem to figure out where to put my code to add a pawn icon to the buttons. In fact, im not really sure wether it's the right use of code or if it's in the wrong place.

My code looks like this so far:

package gui;

import java.awt.Color;

import javax.swing.ImageIcon;
import javax.swing.JButton;

public class Square extends JButton implements Config {

    public Square(int n) {
        new ImageIcon("pawn.png");
        setBackground(calcColor(n));
     }

    Color calcColor(int n) {
        boolean everysecondSquare = (n % 2==0);
        boolean everysecondRow = ((n / ROWS) % 2 == 0);
        return (everysecondSquare != everysecondRow?P1Color:P2Color);
    }

    public ChessBoard ChessBoard;
}

I was pretty sure it would work adding the icon the same place as where you define the background-color of the squares, but appearently it didn't work. Obviously I am very new to java-coding.

Did I really mess this up? All feedback is deeply appreciated. If more information about the code is needed, please tell me and I will add it as fast as I can.

Upvotes: 2

Views: 577

Answers (2)

mahju
mahju

Reputation: 1156

You can pass an Icon object with the constructor to the Button or use the setIcon method of the button.

JButton b = new Button(myIconObject)

myButtonObject.setIcon(myIconObject)

Take a look here for the documentation: http://docs.oracle.com/javase/7/docs/api/javax/swing/JButton.html

Edit:

In your case you could edit the first line of the constructor to

public Square(int n) {
    setIcon(new ImageIcon("pawn.png"));
    setBackground(calcColor(n));
}

But this means every square created will have a pawn icon. You would be better off moving that out of the constructor and doing something like

Square s = new Square(n);
/* And then somewhere more appropriate ...*/
s.setIcon(new ImageIcon("pawn"));

Upvotes: 2

GavinCattell
GavinCattell

Reputation: 3963

Try this instead. You need to actually set the Icon of the button.

public Square(int n) {
setIcon(new ImageIcon("pawn.png"));
setBackground(calcColor(n));
}

Upvotes: 1

Related Questions