So i'm working on a text based game in Ready for Java. I was able to find a way to put an image on screen, but when i try to use frame.dispose();
to remove image it gives me a NullPointerException
.
I have tried looking for an answer but I have not found anything. Can anyone lend a hand?
// The "Pics" class.
import java.awt.*;
import hsa.Console;
import javax.swing.*;
public class Pics extends JPanel
{
static JFrame frame;
static String Continue;
public static void Screens (String jail_time)
{
JFrame frame = new JFrame ("JFrame"); //the pictures
frame.setDefaultCloseOperation (JFrame.DISPOSE_ON_CLOSE);
frame.setSize (773, 480);
JLabel jl = new JLabel (new ImageIcon (jail_time));
frame.getContentPane ().add (jl);
frame.setVisible (true);
frame.pack ();
}
static Console c; // The output console
public static void main (String[] args)
{
c = new Console (30, 60);
Screens ("guard2.jpg");// the first picture
Continue = c.readString ();
frame.dispose ();
Screens ("Jail copy.jpg");//the second picture
// Place your program here. 'c' is the output console
} // main method
} // Pics class
Don't shadow
the "frame" variable.
You have the variable defined as an instance variable, which is null and then you define it again as a local variable. Get rid of the local variable:
//JFrame frame = new JFrame ("JFrame"); //the pictures
frame = new JFrame ("JFrame"); //the pictures
Also, the whole structure of you class is wrong. You should NOT be using static variables and methods. This is the sign of a poorly designed class.
You have a shadowing problem...
First, you declare a static
reference to frame
...
static JFrame frame;
Then in your static
Screens
method, you create a local instance of frame
and build your UI...
public static void Screens (String jail_time)
{
// Local reference here...
JFrame frame = new JFrame ("JFrame"); //the pictures
Which means when you try and reference it in main
, it's still null
...
public static void main (String[] args)
{
Screens ("guard2.jpg");// the first picture
// I'm still null...
frame.dispose ();
Try removing the local declaration in Screens
public static void Screens (String jail_time)
{
//JFrame frame = new JFrame ("JFrame"); //the pictures
frame = new JFrame ("JFrame"); //the pictures
Also, take a look at Initial Threads and make sure you're creating your UI's within the context of the Event Dispatching Thread.
You're shadowing your class member JFrame frame
, which leaves it uninitialized, causing a NullPointerException
anytime you try and call the class member frame. Instead of
JFrame frame = new JFrame ("JFrame");
Do
frame = new JFrame ("JFrame");
In the main method's first line, change
JFrame frame = new JFrame ("JFrame"); //the pictures
to
frame = new JFrame ("JFrame");
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.