dimanche 7 février 2016

The if, else statment does not really work out

I've got a new problem with this code. I know what's wrong but I can't really figure out how to fix it. The code should make the button change color and text on click. Everything works good on the first click but not on the second. What I think is that I've from the start set MyButtons string to "Yellow". Even if the "if statment" changes it, the else statment won't work because of the static string "yellow". Eventhough it looks like it have been changed. But I could be wrong. Other explanation could be that when it's clicked, it just start over and won't get longer than "if". This is a homework so i need to use swing.*; and not javaFX.

import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.event.*;
import javax.swing.*;

public class Sparkling extends JFrame 
{
    public static void main(String[] args)
        {
            JFrame frame = new JFrame ("So Many Colors");
            frame.setVisible(true);
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.setSize(300, 300);
            frame.setLayout(new FlowLayout());

            JButton MyButton = new JButton("");
            MyButton.setText("Yellow");
            MyButton.setText("Blue");
            MyButton.setBackground(Color.YELLOW);
            frame.add(MyButton);

                MyButton.addActionListener(new ActionListener()
                {

                    public void actionPerformed(ActionEvent e) 
                    {

                        if ( e.getSource().equals(MyButton) )
                        {
                            if(MyButton.getText().equals("Yellow"))
                            {
                                MyButton.setText("Blue");
                                MyButton.setBackground(Color.BLUE);
                            }

                            else (MyButton.getText().equals("Blue"))
                            {
                                MyButton.setText("Yellow");
                                MyButton.setBackground(Color.YELLOW);
                            }
                    }

                }



                });

        }
}

Aucun commentaire:

Enregistrer un commentaire