-
adding Image to JButton
I am looking to add an Image to a JButton after it has been pressed. Im not sure of how to do this and I cant find much about it online, I found setPressedIcon(); but i've tried and got nothing. Any help would be great. this is a little of what i have so far. Thanks
Container c = getContentPane();
ImageIcon knight = new ImageIcon("knight.jpg");
private JButton[][] buttons = new JButton[length][height];
public Knight(){
setTitle("Knight's Tour");
setSize(1000, 1000);
setDefaultCloseOperation(EXIT_ON_CLOSE);
c.setLayout(null);
//Initialize and add the buttons
for (int i = 0; i < buttons.length; i++)
{
for (int j = 0; j < buttons[i].length; j++)
{
buttons[i][j] = new JButton();
buttons[i][j].setPressedIcon(new ImageIcon("knight.jpg"));
buttons[i][j].setSize(100, 100);
buttons[i][j].setLocation(10 + (i * 100), 10 + (j * 100));
//buttons[i][j].addActionListener(buttons);
c.add(buttons[i][j]);
}
}
setVisible(true);
}
private class buttonHandler implements ActionListener
{
public void actionPerformed(ActionEvent a)
{
-
Changing a button's image is sometimes as easy as just setting it's image icon via setIcon(Icon icon).
Please describe in greater detail what you want to have happen on button press. Do you want to change the image on the button and for this to remain after the press has occurred? Perhaps you want to look at a JToggleButton instead (hard to say given the info at hand)?
-
I have 64 buttons (8x8) board. I want all the buttons to be empty at first and after I click each button I want to add a image to it.
-
Then the simplest is probably to set the icon as I described above.