0

I'm making a game and I want to change an image already being shown. I think the problem is the wording in the actionPerformed class.

Here's my code:

TwoButtons()
{

    setLayout (new FlowLayout());

    image = new ImageIcon ("as.jpg");
    b = new JButton (image);
    b.setActionCommand("a");
    b.addActionListener(this);
    add(b);
}

public void actionPerformed (ActionEvent evt)
{
    if (evt.getActionCommand().equals("a"))
    {
        image = (new ImageIcon("qd.jpg"));
    }
    repaint();
}
Frakcool
  • 10,915
  • 9
  • 50
  • 89
may255
  • 1
  • 2
    Pick a [duplicate](http://stackoverflow.com/search?tab=votes&q=%5bswing%5d%20%22How%20to%20Use%20Buttons%22%20icon); most cite the same [tutorial](https://docs.oracle.com/javase/tutorial/uiswing/components/button.html). – trashgod Jan 03 '17 at 22:30
  • 2
    `actionPerformed` isn't a class, it's a method. For better help sooner please post a valid [mcve] with hotlinks to [these images](http://stackoverflow.com/questions/19209650/example-images-for-code-and-mark-up-qas) so we can copy-paste and see the same output – Frakcool Jan 03 '17 at 22:30
  • 2
    `" I think the problem is..."` -- **what** problem? If you're having a problem with your code and need help, it makes sense to explain the details of the problem in your question, right? Otherwise, yes, check out the [previous similar questions](https://www.google.com/webhp?sourceid=chrome-instant&ion=1&espv=2&ie=UTF-8#q=site:stackoverflow.com+java+swing+change+image+in+ActionListener) and post your valid [mcve]. – Hovercraft Full Of Eels Jan 03 '17 at 22:33
  • Note that your code shows some "magical thinking". You're changing the ImageIcon that the image variable is referring to, but this will not magically change the ImageIcon that is displayed by the JButton, since changing the variable has no effect on the original object -- a key distinction that is often difficult for newbies to grok initially. For you're code to work, you're going to have to call `setIcon(...)` on the JButton (or JLabel as need be) and pass the new ImageIcon into the method. – Hovercraft Full Of Eels Jan 03 '17 at 22:44
  • Read some of the duplicate questions found in the link as it's all pretty well explained there since this sort of question gets asked a lot. – Hovercraft Full Of Eels Jan 03 '17 at 22:44
  • thanks! this solved it. – may255 Jan 04 '17 at 02:57

0 Answers0