如何替换“这个”在 Java 中,有一些有效的东西
我想让 showGUI() 方法工作,编译器说“this”不是静态变量,不能从静态上下文中引用,我将用什么来替换“this”?我尝试过 test.main (测试是它所在的包)。我使用静态方法 showGUI() 的原因是因为我需要从另一个静态方法以及startup() 方法调用该方法。以下是我的两个主要课程。
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
}
}
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
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
那么,在静态方法中使用
this
是没有意义的。this
指的是该类的特定实例,但static
意味着这是一个不需要实例的方法,因此无法访问任何成员变量或方法。只需使
showGUI
非静态即可。Well, using
this
in a static method doesn't make sense.this
refers to the particular instance of the class, butstatic
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.如果您需要将
this
传递给另一个函数,例如 GUI 构造函数,您需要一个对象,而 showGUI 最好保留为非静态方法:如果您确实需要一个静态方法,则需要一个要处理的对象:
或者更好:
或者更好,不要创建任何静态方法:
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:If you really need a static method, you need an object to work on:
or even better:
or even better, don't create any static method:
“this”的意思是“当前对象”。在静态方法中没有当前对象。在您的示例中,尝试将
this
替换为new Main()
。'this' means 'current object'. In static methods there is no current object. In your example, try replacing
this
withnew Main()
.