"Change modifier" frame "to" static "in Java

I am told Eclipse to change the modifier of my string variable to static. I do not understand why. I think that I declare everything correctly, but I am not sure. Here is my code. The problem occurs on both lines 12 and 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);

    }


}
+3
source share
2 answers

You define it frameas an instance variable, but use it as a static variable. There are two solutions for this:

1) You can change the frame modifier to static

2) Create an instance of your class, for example:

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

frame - MainClass, , MainClass . . , , .

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 / (EDT), invokeLater.

+5

All Articles