3

I am a student of very basic Java. We did an assignment to make the background color change according to the radio button selected using several if statements. That worked fine. I decided to change the selection process to a combobox and use a switch case. It seems to me the process is failing the if statement in the switch case method. I'm trying to get a better understanding of how things work. The code:

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.*;

class Lab17_4combo extends JFrame implements ActionListener
{
    Container container;
    JComboBox colors;

    public Lab17_4combo()
    {
        super("ComboBox ");
        container = this.getContentPane();
        container.setLayout(new FlowLayout());
        setSize(300,200);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        String[] selectColor = {"Red", "Yellow", "Blue", "Green", "Magenta"};
        JComboBox colors = new JComboBox(selectColor);
        colors.setSelectedIndex(-1);
        colors.addActionListener(this);

        container.add(colors);
        setVisible(true);
    }
    public void actionPerformed(ActionEvent e)
    {
        int chgColor;

        if(e.getSource() == colors)
        {
            chgColor = colors.getSelectedIndex();

            switch(chgColor)
            {
                case 0:
                    container.setBackground(Color.red);
                case 1:
                    container.setBackground(Color.yellow);
                case 2:
                    container.setBackground(Color.blue);
                case 3:
                    container.setBackground(Color.green);
                case 4:
                    container.setBackground(Color.magenta);
            }
        }else
            {
                container.setBackground(Color.magenta);
            }

    }
    public static void main(String[] args)
    {
        Lab17_4combo s = new Lab17_4combo();
    }
}

I put in the else to check if it was failing the if. I'm assuming that is where the problem is, but I don't know how to fix it. Any help would be greatly appreciated. The original assignment has been completed, this is my own experimentation. I'm not asking for anyone to do my homework for me. Cheers

EDIT-- I have made the suggested changes to the code (Thanks to all for the suggestions). The background color of the container still does not change regardless of the selection I make from the combobox. I'm assuming there are mistakes elsewhere in the code, but I'm at a loss to find them. My expectation is that the background color of the container will change according to the selection I make from the combobox. This is not happening.

The revised code:

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.*;

class Lab17_4combo extends JFrame implements ActionListener
{
    Container container;
    JComboBox colors;

    public Lab17_4combo()
    {
        super("ComboBox ");
        container = this.getContentPane();
        container.setLayout(new FlowLayout());
        setSize(300,200);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        String[] selectColor = {"Red", "Yellow", "Blue", "Green", "Magenta"};
        JComboBox colors = new JComboBox(selectColor);
        colors.setSelectedIndex(-1);
        colors.addActionListener(this);

        container.add(colors);
        setVisible(true);
    }
    public void actionPerformed(ActionEvent e)
    {
        int chgColor;

        if(e.getSource() == colors)
        {
            chgColor = colors.getSelectedIndex();

            switch(chgColor)
            {
                case 0:
                    container.setBackground(Color.red);
                    break;
                case 1:
                    container.setBackground(Color.yellow);
                    break;
                case 2:
                    container.setBackground(Color.blue);
                    break;
                case 3:
                    container.setBackground(Color.green);
                    break;
                case 4:
                    container.setBackground(Color.magenta);
                    break;
            }
        }
    }
    public static void main(String[] args)
    {
        Lab17_4combo s = new Lab17_4combo();
    }
}

With my limited knowledge of Java I'm not able to see where the mistake(s) may be. Any help would be appreciated.Cheers

7
  • 1
    You forgot to add break after each case in switch statement. Commented Nov 27, 2013 at 19:55
  • @Spud: Check out docs.oracle.com/javase/tutorial/java/nutsandbolts/switch.html Commented Nov 27, 2013 at 19:56
  • Thank you all. I have added the break after each case statement, but still the background color is not changing. Do I have mistakes somewhere else in the code? Commented Nov 27, 2013 at 20:07
  • @Spud Can you provide a sample input and output you are getting and what you are expecting. That would help us to pinpoint the source of the error. Commented Nov 27, 2013 at 20:15
  • @Prateek - My expectation is that the background color of the container will change according to the selection I make from the combobox. I have added the breaks to each case and I have removed the else statement. Regardless of the selection I make, the background color never changes. Thank you for your help Commented Nov 27, 2013 at 20:20

6 Answers 6

3

You forgot the break statement after each case

Try this:

switch(chgColor)
            {
                case 0:
                    container.setBackground(Color.red);
                     break;
                case 1:
                    container.setBackground(Color.yellow);
                    break;
                case 2:
                    container.setBackground(Color.blue);
                     break;
                case 3:
                    container.setBackground(Color.green);
                    break;
                case 4:
                    container.setBackground(Color.magenta);
                    break;
                default:
                //You may add a default case here.
            }

EDIT:-

I think your condition

if(e.getSource() == colors)

is never true thats why you are getting this problem. You may try to compare like this:

if(e.getSource().equals(colors))

Always use .equals method when you are comparing objects.

Sign up to request clarification or add additional context in comments.

3 Comments

Thank you for your response. I have taken your suggestion but still it is not changing the background color. I removed the else statement, but for each selection in the combobox, the color remains unchanged. Have I made a mistake somewhere else in the code?
It won't work either @Rahul. For some reason his colors is null
@RahulTripathi & Prateek - Thank you both for looking into this. I still don't know why colors would be null. I would really like to understand what is going on in the code, that is why I did the experiment in the first place. Would appreciate any help.
1

As mentioned in my comment you forgot to add break in each of your case.

           switch(chgColor)
            {
                case 0:
                    container.setBackground(Color.red);
                    break;
                case 1:
                    container.setBackground(Color.yellow);
                     break;
                case 2:
                    container.setBackground(Color.blue);
                    break;
                case 3:
                    container.setBackground(Color.green);
                    break;
                case 4:
                    container.setBackground(Color.magenta);
                    break;
                default:
                //What if none of above condition is satisfied.
             }

Edit: - Check the comments in the code

    class Lab17_4combo extends JFrame implements ActionListener
    {
        Container container;
        JComboBox colors;// you declared colors. 

        public Lab17_4combo()
        {
            super("ComboBox ");
            container = this.getContentPane();
            container.setLayout(new FlowLayout());
            setSize(300,200);
            setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

            String[] selectColor = {"Red", "Yellow", "Blue", "Green", "Magenta"};

            //JComboBox colors = new JComboBox(selectColor);// You declared colors again. Change     this line to 

            colors = new JComboBox(selectColor);
            colors.setSelectedIndex(-1);
            colors.addActionListener(this);

            container.add(colors);
            setVisible(true);
        }

1 Comment

Good on ya, mate!! So often I fail to see the forest through all the trees. As soon as you pointed it out, it made perfect sense. Thanks for sticking with it. It is a lesson I will remember.Cheers
1

You should use break after each case.

       case 0:
          container.setBackground(Color.red);
          break;
        case 1:
          container.setBackground(Color.yellow);
          break;
          ....

Comments

0

You need to make sure and add a break; after every line in the case, like this:

        switch(chgColor)
        {
            case 0:
                container.setBackground(Color.red);
                break;
            case 1:
                container.setBackground(Color.yellow);
                break;
            case 2:
                container.setBackground(Color.blue);
                break;
            case 3:
                container.setBackground(Color.green);
                break;
            case 4:
                container.setBackground(Color.magenta);
                break;
        }
    }else
        {
            container.setBackground(Color.magenta);
        }

Comments

0

Looks like you always end up with magenta color given the if condition and the switch statement.

Use break for each case statement.

In the switch statement, for each case, you do not have a break;. So even if switch finds a valid matching case, it executes that case and, in your code (since you do not break the control to come out of that case), it eventually passes the control to the cases following the matching case and always ending up in the last case.

Comments

0

I think you are using the wrong colors object inside the constructor, instead of

JComboBox colors = new JComboBox(selectColor);

you have to use the colors attribute

colors = new JComboBox(selectColor);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.