Updating a JPanel with an Image

Hi,

Within a gamePanel (set as the content pane) I have player1 (panel), which holds a JLabel containing an ImageIcon. I want to be able to update the player1 JPanel with a different image once the user clicks a button onscreen. My code is as follows:

private JPanel gamePanel, player1;

private ImageIcon fourSpadesL = new ImageIcon("CardsL/FourSpadesL.jpg")

private ImageIcon anotherCard= new ImageIcon("CardsL/anotherCard.jpg")

....

public game()

{

setLayout(null);

setPreferredSize( new Dimension(800,560) );

player1=new JPanel();

player1.setOpaque(false);

player1Text=new JTextField("Player 1");

player1.add(player1Text);

player1.add(new JLabel(fourSpadesL));

player1.setBounds(0,0,80,80);

gamePanel.add(player1)

add(gamePanel);

gamePanel.setBounds(0,0,800,650);

......

}

and the method that the button calls when clicked

public void drawPlayer1Hand()

{

player1.removeAll();

player1.add(new JLabel(anotherCard));

player1.setBounds(0,0,80,80);

gamePanel.add(player1);

setContentPane(gamePanel);

player1Text.setText("new Hand");

}

once this method is invoked, the TextField in the player1 panel is updated as 'new Hand', but the ImageIcons do not change from the original.

Any help would be much appreciated. Thanks, C.

[1434 byte] By [ccbloomersa] at [2007-10-3 11:03:50]
# 1

Don't create a new component simply to change the icon. Just use:

label.setIcon(...)

and it will repaint itself.

If you do remove and add components from a visible GUI to a parent Container, then you need to use:

parent.revalidate();

parent.repaint(); // sometimes required as well.

camickra at 2007-7-15 13:26:14 > top of Java-index,Desktop,Core GUI APIs...
# 2

Hey, thanks for your help. I used label.setIcon(...) to update the card image in the players panel.

I also tried parent.revalidate(); to see if this could work, but I got the error 'parent is not public and cannot be accessed from outside package', as I was calling it from outside of the constructor in another method.

I had to set up a new user account, is there a way I can get you some duke dollars?

Cheers, C

ccbloomera at 2007-7-15 13:26:14 > top of Java-index,Desktop,Core GUI APIs...