0

I have an assignment where I have to create a button, click it, then display a random picture based on a random result. However, when I try to create an if statement to display the random result I can't get the button to match to a string. For instance

if (button1 == "results"){
// display image
}

Here is my code for the panel so far. import java.awt.; import javax.swing.; import java.awt.event.*;

public class myJPanel6 extends JPanel implements ActionListener
{
myJButton b1,b2;
    JLabel b3;

public myJPanel6()
{
       // setSize(260,260);
            ImageIcon imageFred = new ImageIcon("images/fred.gif");
        ImageIcon imageCar = new ImageIcon("images/Magnum.JPG");
            ImageIcon imageMaldives = new ImageIcon("image/maldives.jpg");
    setLayout(new GridLayout(1,1));  
//=====================================
    student st1 = new student("Michael", "Robinson", 20);
//=====================================
    b1 = new myJButton(st1.getName());
            b1.addActionListener(this); 
    add(b1);
//=====================================
    b2 = new myJButton(st1.WhatIsUp());
             b2.addActionListener(this); 
    add(b2);

            if (st1.WhatIsUp() == "reading"){
                b2.setIcon(imageFred);
            } else if (st1.WhatIsUp() == "talking") {
                b2.setIcon(imageCar);
            } else if (st1.WhatIsUp() == "interacting") {
                   b2.setIcon(imageMaldives);
            }



            //b3 = new JLabel(".....");
          //  add(b3);

    }
public void actionPerformed(ActionEvent event) 
    {
         Object obj = event.getSource();
//=====================================
     if (obj == b1){{b2.setText(b2.getText());}
    } else {
    b2.setText(b2.getText());
        }
}
}

The main problem that I am having is that the code only displays an image sometimes. Also I think a new result should be outputted every time the user clicks, but the code I have displays the same random result each time.

Thanks for any help.

user1566796
  • 35
  • 2
  • 9

2 Answers2

0

Strings must be compared using equals as opposed to ==

if (string1.equals(string2))

William Falcon
  • 9,813
  • 14
  • 67
  • 110
0

Try String.equals.

Also if it's a Button view you'll need to call getText(), so:

if (button1.getText().toString().equals("results")) { }
Ricky
  • 7,785
  • 2
  • 34
  • 46