Question

Ive trying to build some code and keep running into this error. Ive tried ways around it but it then messes with the execution of methods within Journey.

Ive looked at other threads but cant seem to find an answer.

class Main{
private Journey newJourney;

public static void main(String[] args){
        startStation.addItemListener(
            new ItemListener(){
                public void itemStateChanged(ItemEvent event){
                    if(event.getStateChange()==ItemEvent.SELECTED){

                        String selectedItem = startStation.getSelectedItem().toString();
                        newJourney = new Journey();
                        newJourney.setStart(selectedItem);


                    }
                }
            }
        );

Obviously ommited some code but thats the main just of things.

Any help is appreciated and the error im recieveing is

Main.java:102: non-static variable newJourney cannot be referenced from a static context
                        newJourney.setStart(selectedItem);
                        ^

No correct solution

OTHER TIPS

The error says it all. newJourney is not a static variable where main is a static method. This means main cannot access it. This means the following code will not work

private Journey newJourney;

you would need

private static Journey newJourney;

You should declare your object as a sataic one as following:

private static Journey newJourney;

Because you are using this object in a non-static way, It must be a static one

You may want to adopt the following paradigm, in which you create a new object for the class that your static Main method is in, and then do all your work from that object.

class Main{
private static final Main me;
private Journey newJourney;

public static void main(String[] args){
    me = new Main();
    me.doWork(args);
}
private void doWork(String[] args) {
    startStation.addItemListener(
        new ItemListener(){
            public void itemStateChanged(ItemEvent event){
                if(event.getStateChange()==ItemEvent.SELECTED){
                    String selectedItem = startStation.getSelectedItem().toString();
                    newJourney = new Journey();
                    newJourney.setStart(selectedItem);
                }
            }
        }
    );
}

newJourney is not static, you are trying to access into static methods.

As a Java concept, an object's state can not be changed inside static methods.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top