Oliver Muchai
Oliver Muchai

Reputation: 279

The switch statent and return values - How to use a switch to determin JPanel drawn

I have a program which has different JPanels written in different classes. I would like to print a particular JPanel depending on the button clicked by a user.

When the program is launched, it only has three buttons: "Animals JButton", "Plants JButton" and a "Refresh JButton" in a JFrame "frame"; no JPanel.

If, for example, a user clicks on the "Animals JButton", the JPanel with Animals gets printed on the JFrame.

The "AnimalsJPanel" and "PlantsJPanel" are written in different classes. Another class, "PageReturner", has a method that determines what gets printed via a switch.

public class Redirect {

    String pageAnimals = "pageAnimals";
    String pagePlants = "pagePlants";

    String value;

    public String pageRedirect (String pageID) {
        switch (pageID) {
            case pageAnimals:
                value = (AnimalsJPanel animalsJPanel = new AnimalsJPanel());
            break;
            case pagePlants:
                value = (PlantsJPanel plantsJPanel = new PlantsJPanel());
                break;
            case 2:
                value = null;
                break;
        }
        return null;

    }

}

I get "constant string expression required" and "incopatible types" errors in netbeans. What might be the problem with my switch statement, and is there a better way to go about this, i.e, determining a page to print. I'd like to code this and not use cardlayout. I'm new to JAVA and trying to learn how to get objects from classes.

Is my switch statement even well done. I'm teaching myself programming, and have no one to consult. Much appreaciation in advance for any advice

Upvotes: 1

Views: 192

Answers (3)

Luca Basso Ricci
Luca Basso Ricci

Reputation: 18413

You are assign a JPanel object to a String and you can't do that!
Define value as JPanel value; or do write value = (AnimalsJPanel animalsJPanel = new AnimalsJPanel()).toString();

Upvotes: 1

tibtof
tibtof

Reputation: 7967

Declare pageAnimals and pagePlants as static final (note the variable name change to match java conventions for constants):

static final String PAGE_ANIMALS = "pageAnimals";
static final String PAGE_PANTS = "pagePlants";

Also, you have to explicitly case the panels to String:

case PAGE_ANIMALS :
     value = (AnimalsJPanel animalsJPanel = new AnimalsJPanel()).toString();
     break;
case PAGE_PANTS :
     value = (PlantsJPanel plantsJPanel = new PlantsJPanel()).toString();
     break;

Upvotes: 2

Prabhaker A
Prabhaker A

Reputation: 8483

Declare variable as final those are used in switch case.

   final String pageAnimals = "pageAnimals";
   final String pagePlants = "pagePlants";

Since all case labels should be compile time constants in Switch.

Upvotes: 3

Related Questions