Error: Syntax error on token “setDefaultCloseOperation”, Identifier
expected after this token
Current Code:
package me.geekplaya.Launcher;
import javax.swing.*;
public class Launcher {
//Create and setup the window.
JFrame frame = new JFrame("Simple GUI");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JLabel textLabel = new JLabel("I'm a label in the window", SwingConstants.CENTER);
textLabel.setPrefferedSize(new Dimension(300, 100));
frame.getContentPane().add(textLabel, BorderLayout.CENTER);
//Display the window.
frame.setLocationRelativeTo(null);
frame.pack();
frame.setVisible(true);
}
A Class body can only contain: variable definitions, method definitions, or inner class definitions. A method body contains zero or more statements. Your statements must be put inside a method body. You have them defined in the class body. For example:
The compiler is trying to tell you that it doesn’t recognize those statements as one of those possible choices (variable def, method def, or inner class def). The reason it’s on the 2nd line and not the first is because the first line could be defining an instance variable. Local variables and instance variables can have the same syntax. Variables defined in the Class body are instance variables (unless marked static), and variables defined in a method body are local variables to that method.
Just as an aside you don’t have to set the preferred width of the JLabel. JLabel will resize itself to fix the text it’s given. It’s usually better to let JLabel pick its size based on its content because that content could change, and if you hard code 300 pixels wide and 100 pixels tall that might not be enough depending on the label’s content:
If you want the window to be bigger set the preferred size of the JFrame and remove the pack() call. JFrame.pack() tells the JFrame to set its size based on the size of the contents in the JFrame. If you want the JFrame to be in control of its dimensions just set them directly.