0

我有以下两段代码

第一个代码:

package guicollection;

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class RectanglePattern extends GUIcollection implements ActionListener {

    JPanel panelForBackGround;
    JButton actionButton;

    void drawRectangle() {

        RectanglePattern outSideCover = new RectanglePattern();
        outSideCover.setSize(500, 500);
        outSideCover.createGUI();
        outSideCover.setVisible(true);

    }

    private void createGUI() {

        setDefaultCloseOperation(EXIT_ON_CLOSE);
        Container window = getContentPane();
        window.setLayout(new FlowLayout());

        panelForBackGround = new JPanel();
        panelForBackGround.setPreferredSize(new Dimension(400, 300));

        panelForBackGround.setBackground(Color.blue);

        window.add(panelForBackGround);

        actionButton = new JButton("Press me");
        window.add(actionButton);
        actionButton.addActionListener(this);


    }

    public void actionPerformed(ActionEvent event) {
        Graphics paper = panelForBackGround.getGraphics();

        paper.drawLine(0, 0, 9, 10);
        paper.drawRect(8, 8, 12, 9);
        paper.drawRect(6, 6, 12, 6);

    }
}

第二个代码:

package guicollection;

import java.awt.*;
import javax.swing.*;

public class RectanglePattern extends GUIcollection{

    JPanel panelForBackGround;
    JButton actionButton;

    void drawRectangle() {

        RectanglePattern outSideCover = new RectanglePattern();
        outSideCover.setSize(500, 500);
        outSideCover.createGUI();
        outSideCover.setVisible(true);

    }

    private void createGUI() {        

        setDefaultCloseOperation(EXIT_ON_CLOSE);
        Container window = getContentPane();
        window.setLayout(new FlowLayout());

        panelForBackGround = new JPanel();
        panelForBackGround.setPreferredSize(new Dimension(400, 300));

        panelForBackGround.setBackground(Color.blue);

        window.add(panelForBackGround);

        actionButton = new JButton("Press me");
        window.add(actionButton);
        actionButton.addActionListener(this);





        Graphics paper = panelForBackGround.getGraphics();

        paper.drawLine(0, 0, 9, 10);
        paper.drawRect(8, 8, 12, 9);
        paper.drawRect(6, 6, 12, 6);


}

}

第二个代码在编译时显示以下错误。它不是必须在上面画一条线和两个矩形panelForBackGround吗?这个错误的原因是什么?

错误:

线程“主”java.lang.NullPointerException 中的异常
    在 guicollection.RectanglePattern.drawRectangle(RectanglePattern.java:20)
    在 guicollection.GUIcollection.main(GUIcollection.java:24)
4

1 回答 1

0

这里的空指针接受通常与未正确创建图形环境有关。尝试调用此方法:

window.setVisible(true);

或者可能是因为您试图在机器还没有时间完全创建的窗口上绘图。我遇到过这个问题。在创建 Graphics 变量之前,尝试告诉程序等待窗口赶上进度:

try{
Thread.sleep(300);
catch(Exception e){
System.out.println(e.printStackTrace());
}

我知道只捕获“异常”而不是特定异常并不是最好的事情,但这是摆脱 xD 的简单方法,哈哈。告诉我这些是否有效。如果不是,我稍后会回来提供更多帮助。

于 2012-12-07T19:03:31.973 回答