I am trying to add an image on top of a button using swing. I have looked at other similar questions on stackoverflow, and have tried to do this is a few different ways. Unfortunately none have been successful. To be specific, I have looked at this tutorial, this question and this question.
The relevant code is this:
import java.awt.GridLayout;
import java.awt.Image;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;
import java.io.InputStream;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JPanel;
import javax.swing.Icon;
public class GameBoard extends JPanel implements ActionListener {
private JButton B1, B2, B3, B4, B5, B6, B7, B8, B9;
private GameArray GArray;
private boolean Player = false;
private int PlayerMark = 1;
GameBoard() {
setLayout(new GridLayout(3, 3));
B1 = new JButton();
...
B9 = new JButton();
SetGame();
add(B1);
...
add(B9);
B1.addActionListener(this);
...
B9.addActionListener(this);
}
public void SetGame() {
GArray = new GameArray(this);
DefaultText();
DisableAll(true);
Player = false;
PlayerMark = 1;
}
public void Reset() {
SetGame();
}
public void actionPerformed(ActionEvent E) {
...
}
//Other methods
public void SetText(JButton Btn, boolean Play) {
if (Play == true) {
Btn.setText("O");
} else if (Play == false) {
Btn.setIcon(new ImageIcon(GameBoard.class.getResource("red.png")));
}
}
}
What I was hoping to happen is that after I press one of the nine buttons on the first go, the button will have the image "red.png" on it and will no longer be enabled. However, what actually happens is that is just becomes disabled and turns a dark grey.
What I'm guessing is happening is that the image is underneath the button - is this correct? If so, how would I change it so that the image can be seen on the button?