1

I want to write program in which you can chance scene (JPanel) thanks to JComboBox. I used ActionListener, but it doesn't work.

At the beginning of constructor I defined panel as final, but it didn't help.

scene.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent e) {
        String choice = String.valueOf(scene.getSelectedItem());
        if(choice=="Sceneria"||choice=="Scene"){
            slider.setEnabled(false);
            panel = new JPanel();// problem here
        }
    }
});

Error

The final local variable panel cannot be assigned, since it is defined in an enclosing type
Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
Xalion
  • 623
  • 9
  • 27
  • 1
    Change `==` to `equals(String)` – Murat Karagöz May 30 '15 at 10:44
  • my if is ok. I made similarly in other class, and it works. problem is here: panel = new JPanel(); – Xalion May 30 '15 at 10:48
  • 1
    1) For better help sooner, post an [MCVE](http://stackoverflow.com/help/mcve) (Minimal Complete Verifiable Example) or [SSCCE](http://www.sscce.org/) (Short, Self Contained, Correct Example). 2) But use a [`CardLayout`](http://download.oracle.com/javase/8/docs/api/java/awt/CardLayout.html) instead, as shown in [this answer](http://stackoverflow.com/a/5786005/418556). – Andrew Thompson May 30 '15 at 10:50

1 Answers1

0

I suggest you to make panel an attribute of your class. Then call panel such as YourClass.this.panel.

public class YourClass {

    private JPanel panel;

    public YourClass() {

        // ...

        scene.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                String choice = String.valueOf(scene.getSelectedItem());
                if(choice.equals("Sceneria") || choice.equals("Scene")) {
                    slider.setEnabled(false);
                    YourClass.this.panel = new JPanel();
                    YourClass.this.panel.revalidate();
                    YourClass.this.panel.repaint();
                }
            }
        });
    }
}
Stéphane Bruckert
  • 21,706
  • 14
  • 92
  • 130
  • now, there is no error, but JPanel doesnt work. ActionListener works coz i can see changes in slider. – Xalion May 30 '15 at 11:30
  • What do you mean it doesn't work? What did you expect and what is the actual result? Did you add new components to your new JPanel? **If you need more help, please read [Andrew Thompson's comment](http://stackoverflow.com/questions/30545118/actionlistener-of-jcombobox-and-initialize-jpanel/30545216?noredirect=1#comment49163079_30545118).** – Stéphane Bruckert May 30 '15 at 11:36
  • https://www.youtube.com/watch?v=zHl-VNwNwMU look at this. DrawScene1 is class which is exntended by JPanel – Xalion May 30 '15 at 12:03
  • Try to call `YourClass.this.panel.revalidate();` and/or `YourClass.this.panel.repaint();`. Also try this on `getContentPane()`. – Stéphane Bruckert May 30 '15 at 12:28