There's a very significant difference between:
JFrame frame = new JFrame();
and
frame = new JFrame();
The first version declares a new local variable (in the context you've given) and assigns it a value. That local variable is completely separate to the instance variable you declared within the Display
class.
The latter snippet assigns a new value to an existing variable - except in this case it won't work because you have an instance variable but no instance of Display
.
If you declare your frame
variable as static
rather than as an instance variable, you can assign to that within your main
method:
public class Display {
public static JFrame frame;
public static void main(String[] args) {
frame = new JFrame();
frame.setSize(800, 600);
frame.setVisible(true);
}
}
Or you could create a new instance of Display
and assign a value to an instance variable within it:
public class Display {
public JFrame frame;
public static void main(String[] args) {
Display display = new Display();
display.frame = new JFrame();
display.frame.setSize(800, 600);
display.frame.setVisible(true);
}
}
However:
- There's no indication that you're going to use the instance/static variable within
Display
anyway - I'd strongly encourage you to always make your fields private