"Change modifier of 'frame' to 'static'" in Java
I'm being told by Eclipse to change the modifier of my string variable to static. I don't understand why. I think I'm declaring everything right but I'm not sure. Here's my code. The problem is happening 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);
}
}
frame
is an instance variable of MainClass which means you need an instance of MainClass in order to access it. A static variable belongs to the class and does not require an instance. Generally speaking, you should be avoiding storing things statically as they are hard to modify and test.
Rather create an instance of MainClass in your main method and then access your frame inside an instance method.
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();
}
});
}
}
EDIT Notice that when working with Swing, when you create/touch UI components, you need to do that on the Event Dispatch Thread (EDT) which is what the invokeLater
does.
You are defining frame
as an instance variable, but using it as a static variable. There are two solutions to this:
1) You can change the modifier of frame to static
2) Create an instance of your class, like this:
public static void main (String[] args){
MainClass mc = new MainClass();
mc.frame.setVisible(true);
mc.frame.setSize(500, 500);
}
精彩评论