1

I am new to creating GUIs, and I am having trouble refreshing the image on a JLabel. I have read other questions from people with the same problems, but none of the answers helped me. I have a program that will roll a die every time the JButton is clicked, and if result is a one, a I want the image of the JLabel to change. Here is the constructor of my GUI class:

private Panel panel;
private Label label;
private TextField text;
private JButton roll;
private ArrayList<ImageIcon> deck;
private ArrayList<ImageIcon> discard;
private JLabel pic;
private JFrame f;
private ImageIcon now;
public Planechase()
{
    f = new JFrame("Planechase");
    deck = new ArrayList<ImageIcon>();
    populate();
    Collections.shuffle(deck);
    discard = new ArrayList<ImageIcon>();
    label = new Label("Planechase");
    text = new TextField(":)",8);
    text.setEditable(false);
    roll = new JButton("Roll");
    roll.addActionListener(
        new ActionListener() {
            public void actionPerformed(ActionEvent e)
            {
                int i = (int)(Math.random()*6)+1;
                System.out.println(i);
                if(i==1)
                {
                    text.setText("Planeswalk");
                    discard.add(now);
                    now = deck.remove(0);
                    pic = new JLabel(now);
                    pic.updateUI();
                }
                else if(i==6)
                {
                    text.setText("Chaos");
                }
                else
                {
                    text.setText("Blank");
                }
            }
        });
    now = deck.remove(0);
    pic = new JLabel(now);
    f.getContentPane().setLayout(new FlowLayout());
    f.getContentPane().add(pic);
    f.getContentPane().add(text);
    f.getContentPane().add(roll);
}

I tried using updateUI() above, as was suggested in similar questions, but the picture doesn't change. What else should I try?

Reimeus
  • 158,255
  • 15
  • 216
  • 276

1 Answers1

2

You're creating a new Jlabel in your ActionListener, but not adding it to the container. You can update the Icon using setIcon

pic.setIcon(now);

Some Side Notes:

  • As you're removing Icons to use in in your JLabel, you will eventually run out of available icons resulting in an IndexOutOfBoundsException if not re-added.
  • Generally mixing AWT & Swing components is not a good idea. The older AWT components typically don't respect the z-order of components and often hide their lightweight neighbors. See here.
Reimeus
  • 158,255
  • 15
  • 216
  • 276
  • +1, Sunday morning nitpick: technically, mixing is just fine nowadays - most of time not really intended, though :-) – kleopatra Mar 24 '13 at 09:09