“在Java中将'frame'的修饰符更改为'static'”

时间:2011-05-25 23:31:46

标签: java static jframe

Eclipse告诉我将我的字符串变量的修饰符更改为static。我不明白为什么。我想我正在宣布一切正确,但我不确定。 这是我的代码。问题出现在第12和第13行。

import java.awt.*;
import javax.swing.*;
public class MainClass {


    Rectangle dot1 = new Rectangle(1,1), dot2 = new Rectangle(1,1);
    JFrame frame = new JFrame("Pythagorean Theorem");


    public static void main (String[] args){

        frame.setVisible(true);
        frame.setSize(500, 500);

    }


}

2 个答案:

答案 0 :(得分:5)

frame是MainClass的实例变量,这意味着您需要一个MainClass实例才能访问它。静态变量属于该类,不需要实例。一般来说,您应该避免静态存储,因为它们很难修改和测试。

而是在main方法中创建MainClass的实例,然后在实例方法中访问您的框架。

public class MainClass {
    Rectangle dot1 = new Rectangle(1,1), dot2 = new Rectangle(1,1);
    JFrame frame = new JFrame("Pythagorean Theorem");

    public void buildUI() {
        frame.setVisible(true);
        frame.setSize(500, 500);
    }

    public static void main (String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                new MainClass().buildUI();
            }
        });
    }
}

编辑请注意,在使用Swing时,在创建/触摸UI组件时,需要在事件调度线程(EDT)上执行此操作,这是{{1确实。

答案 1 :(得分:2)

您将frame定义为实例变量,但将其用作静态变量。有两种解决方案:

1)您可以将框架的修改器更改为静态

2)创建一个类的实例,如下所示:

public static void main (String[] args){
    MainClass mc = new MainClass();
    mc.frame.setVisible(true);
    mc.frame.setSize(500, 500);
}