我有以下两段代码
第一个代码:
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)