繁体   English   中英

Jframe不处理

[英]Jframe not Disposing

所以我正在用Ready for Java开发一款基于文本的游戏。 我能够找到一种在屏幕上放置图像的方法,但是当我尝试使用frame.dispose(); 删除图像,它给了我NullPointerException

我试图寻找答案,但没有发现任何东西。 谁能伸出援手?

// 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

不要shadow “ frame”变量。

您已将变量定义为实例变量,该变量为null,然后再次将其定义为局部变量。 摆脱局部变量:

//JFrame frame = new JFrame ("JFrame"); //the pictures
frame = new JFrame ("JFrame"); //the pictures

另外,您课堂的整体结构是错误的。 您不应该使用静态变量和方法。 这是班级设计不良的标志。

你有阴影问题...

首先,您声明对framestatic引用。

static JFrame frame;

然后在static Screens方法中,创建frame的本地实例并构建UI。

public static void Screens (String jail_time)
{
    // Local reference here...
    JFrame frame = new JFrame ("JFrame"); //the pictures

这意味着当您尝试在main引用它时,它仍然为null ...

public static void main (String[] args)
{
    Screens ("guard2.jpg");// the first picture
    // I'm still null...
    frame.dispose ();

尝试删除Screens的本地声明

public static void Screens (String jail_time)
{
    //JFrame frame = new JFrame ("JFrame"); //the pictures
    frame = new JFrame ("JFrame"); //the pictures

另外,请查看“ 初始线程” ,并确保您在事件调度线程的上下文中创建UI。

您正在遮蔽类成员JFrame frame ,这使其未初始化,从而在您尝试调用该类成员框架时引发NullPointerException 代替

JFrame frame = new JFrame ("JFrame"); 

frame = new JFrame ("JFrame"); 

在main方法的第一行中,更改

JFrame frame =新的JFrame(“ JFrame”); //图片

frame =新的JFrame(“ JFrame”);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM