开发者

How do I replace "this" in Java with something that works

I'm looking to get the showGUI() method work, the compiler says "this" is not a static variable and cannot be referenced from a static context, what would I use to replace "this"? I've tried test.main (test being the package it's in). The reason I'm using the static method showGUI() is because I need the method to be called from another static method, as well as the startup() 开发者_运维问答method. Below are my two main classes.

public class Main extends SingleFrameApplication {

    @Override protected void startup() {
        showGUI();
    }

    @Override protected void configureWindow(java.awt.Window root) {
    }

    public static Main getApplication() {
        return Application.getInstance(Main.class);
    }

    public static void main(String[] args) {
       launch(Main.class, args);

    }

    public static void showGUI() {
        show(new GUI(this));
    }
}

public class GUI extends FrameView {

    public GUI(SingleFrameApplication app) {
        super(app);
        initComponents();
    }
    private void initComponents() {
        //all the GUI stuff is somehow defined here
    }
}


Well, using this in a static method doesn't make sense. this refers to the particular instance of the class, but static means that this is a method that does not require an instance, and as such doesn't have access to any member variables or methods.

Just make showGUI non-static.

public void showGUI() {
    show(new GUI(this));
}


If you need to pass this to another function, e.g. the GUI constructor, you need an object, and showGUI is best left as a non-static method:

@Override protected void startup() {
    showGUI();
}

public void showGUI() {
    show(new GUI(this));
}

If you really need a static method, you need an object to work on:

public static void createApplicationAndShowGUI() {
    Main main = getApplication();
    show(new GUI(main));
}

or even better:

public static void createApplicationAndShowGUI() {
    Main main = getApplication();
    main.startup();
}

or even better, don't create any static method:

// in your context outside of the Main object
Main main = Main.getApplication();
main.showGUI();


'this' means 'current object'. In static methods there is no current object. In your example, try replacing this with new Main().

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜