错误:令牌“setDefaultCloseOperation”,标识符上的语法错误 预计在此标记之后
当前代码:
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);
}
答案 0 :(得分:3)
类主体只能包含:变量定义,方法定义或内部类定义。方法体包含零个或多个语句。您的陈述必须放在方法体内。你在类体中定义了它们。例如:
public class Launcher {
public void method1() {
// this is an instance method you can put code here too.
// Only instances of the class Launcher can call this method.
}
public static void main( String[] args ) {
// this is a class method (i.e. static) it belongs to the class Launcher
// your code must go in here.
}
}
编译器试图告诉您它不会将这些语句识别为可能的选择之一(变量def,方法def或内部类def)。它在第二行而不是第一行的原因是因为第一行可能是定义一个实例变量。局部变量和实例变量可以具有相同的语法。在类体中定义的变量是实例变量(除非标记为静态),方法体中定义的变量是该方法的局部变量。
除此之外,您不必设置JLabel的首选宽度。 JLabel将调整自己的大小来修复它给出的文本。通常最好让JLabel根据其内容选择其大小,因为内容可能会发生变化,如果硬编码300像素宽,100像素高,根据标签的内容可能不够:
textLabel.setPrefferedSize(new Dimension(300, 100)); // this can be removed
如果您希望窗口更大,请设置JFrame的首选大小并删除pack()调用。 JFrame.pack()告诉JFrame根据JFrame中内容的大小设置其大小。如果您希望JFrame控制其尺寸,只需直接设置它们。