Your main method is not static
, and you should make it static
. Check this to see why
public static void main(String [] args)
Question
I have this code. Eclipse tells me that the syntax is correct but when I run the program it gives me this error:
Exception in thread "main" java.lang.NoSuchMethodError: main
What's wrong?
import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class Main extends JFrame {
private static final long serialVersionUID = 1L;
public void main(String[] args){
JFrame Main = new JFrame("TEST");
Main.setSize(600, 600);
Main.setLocationRelativeTo(null);
Main.setVisible(true);
Main.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//Adding JPanel
JPanel panel = new JPanel();
Main.add(panel);
//JPanel settings
panel.setLayout(null);
panel.setBackground(Color.GREEN);
//Adding JButton
JButton button = new JButton("Button 1");
JButton button2 = new JButton("Button2");
panel.add(button);
panel.add(button2);
//Button action
button.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e) {
JPanel panel = new JPanel();
JPanel panel2 = new JPanel();
Main.this.getContentPane().remove(panel);
Main.this.getContentPane().add(panel2);
Main.this.getContentPane().validate();
}
});
//JButton settings
button.setBounds(70, 160, 200, 200);
button2.setBounds(320, 160, 200, 200);
}
}
La solution
Your main method is not static
, and you should make it static
. Check this to see why
public static void main(String [] args)
Autres conseils
Your main method should be static
public static void main(String[] args){
----
}
And see why ??Why is the Java main method static?
The class requires a method with a signature of:
public static void main(String[])
You have to make your main method static:
public static void main(String[] args) {
}
public static void main(String[] args)
instead of
public void main(String[] args)
public
means that the method is visible and can be called from other objects of other types. Other alternatives are private, protected, package and package-private. See here for more details.
static
means that the method is associated with the class, not a specific instance (object) of that class. This means that you can call a static method without creating an object of the class.
void
means that the method has no return value. If the method returned an int you would write int instead of void.
The combination of all three of these is most commonly seen on the main method which most tutorials will include.
Your main method must be static (ie. class-bound not instance-bound) because at the time of starting your app there no class instances that could call your class' main method.
The class requires a method with a signature of like this:
public static void main(String[])