Java 无法从静态上下文引用非静态变量NewTourney

Java 无法从静态上下文引用非静态变量NewTourney,java,object,methods,static,Java,Object,Methods,Static,我正试图编写一些代码,却一直遇到这个错误。我尝试了一些方法来解决这个问题,但它会在旅程中扰乱方法的执行 我看了其他的线索,但似乎找不到答案 class Main{ private Journey newJourney; public static void main(String[] args){ startStation.addItemListener( new ItemListener(){ public void i

我正试图编写一些代码,却一直遇到这个错误。我尝试了一些方法来解决这个问题,但它会在旅程中扰乱方法的执行

我看了其他的线索,但似乎找不到答案

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);


                    }
                }
            }
        );
很明显,我写了一些代码,但这是最主要的

感谢您的帮助,我收到的错误是

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

错误说明了一切。在main是静态方法的情况下,NewTraveley不是静态变量。这意味着main无法访问它。这意味着以下代码将不起作用

private Journey newJourney;
你需要

private static Journey newJourney;

您应该将对象声明为
sataic
对象,如下所示:

private static Journey newJourney;

由于您以非静态的方式使用此对象,因此它必须是静态的,因此您正在尝试访问静态方法


作为Java概念,对象的状态不能在静态方法中更改。

您可能希望采用以下范例,在该范例中,您为静态主方法所在的类创建一个新对象,然后从该对象执行所有工作

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);
                }
            }
        }
    );
}

查看右侧的
相关部分。如果这些还不够,这里的任何人都帮不了你。