【问题标题】:JFrame Issue: Syntax error on token "setDefaultCloseOperation"JFrame 问题:令牌“setDefaultCloseOperation”上的语法错误
【发布时间】:2011-11-08 22:45:21
【问题描述】:

错误:令牌“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);
}

【问题讨论】:

    标签: java eclipse swing


    【解决方案1】:

    类主体只能包含:变量定义、方法定义或内部类定义。方法体包含零个或多个语句。您的语句必须放在方法体中。您在类主体中定义了它们。例如:

    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 控制其尺寸,只需直接设置它们即可。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-07-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多