在 Java 中出错,不知道我做错了什么
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/23175680/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Getting error in Java, Have no idea what I'm doing wrong
提问by user3552670
I'm new to Java and I was trying to do the following on eclipse:
我是 Java 新手,我试图在 Eclipse 上执行以下操作:
import javax.swing.*;
public class Hello_World {
public class HelloWorld extends JFrame
{
public static void main(String[] args) {
JFrame frame = new HelloWorld();
frame.setSize( 300, 200 );
frame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
frame.setTitle( "Hello world" );
frame.setVisible( true );
}
}
}
I have no idea what I doing wrong here. The compiler gives me following error:
我不知道我在这里做错了什么。编译器给了我以下错误:
Main method not found in class Hello_World, please define the main method as:
public static void main(String[] args)
or a JavaFX application class must extend javafx.application.Application
Can someone tell me what I'm doing wrong?
有人能告诉我我做错了什么吗?
采纳答案by merlin2011
The compiler is complaining because you have defined your main
method inside a nested class, instead of directly in the class that you are compiling.
编译器抱怨是因为您main
在嵌套类中定义了您的方法,而不是直接在您正在编译的类中定义。
Just move the main
method into the HelloWorld
class.
只需将main
方法移动到HelloWorld
类中即可。
import javax.swing.*;
public class Hello_World {
public static class HelloWorld extends JFrame
{
}
public static void main(String[] args) {
JFrame frame = new HelloWorld();
frame.setSize( 300, 200 );
frame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
frame.setTitle( "Hello world" );
frame.setVisible( true );
}
}
回答by user6325799
Here is a better solution:
这是一个更好的解决方案:
package hello_world;
import javax.swing.*;
public class Hello_World extends JFrame {
public static void main(String[] args) {
JFrame frame = new Hello_World();
frame.setSize( 300, 200 );
frame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
frame.setTitle( "Hello world" );
frame.setVisible( true );
}
}