当我尝试构建下面的程序时,我收到以下错误:
Exception in thread "main" java.lang.NullPointerException
at java.awt.Container.addImpl(Unknown Source)
at java.awt.Container.add(Unknown Source)
at miniCADFrame$CanvasPanel.<init>(miniCADFrame.java:71)
at miniCADFrame.<init>(miniCADFrame.java:17)
at miniCAD.<init>(miniCAD.java:12)
at miniCAD.main(miniCAD.java:20)
显然我有一些NULL指针问题,但我不确定它们在哪里!我认为代码的来源如下(如果我避免使用下面代码中的类,程序将运行没有问题)。我在下面的问题点添加了行号。
完成后,程序将允许用户按下按钮以绘制各种形状。
import java.awt.BorderLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class miniCADFrame extends JPanel {
private CanvasPanel canvas = new CanvasPanel(); //LINE 17
private ButtonPanel buttons = new ButtonPanel();
public miniCADFrame() {
//Constructor, creates the mother panel
this.setLayout(new BorderLayout());
this.add (canvas,BorderLayout.CENTER);
}
private class ButtonListener implements ActionListener {
@Override
public void actionPerformed(ActionEvent event) { //Paint the figure associated with the button click
canvas.add(new FigurePanel(FigurePanel.OVAL), BorderLayout.CENTER);
canvas.repaint();
}
}
class ButtonPanel extends JPanel {
private JButton[] Jbuttons = new JButton[11];
//Constructor
ButtonPanel() {
setLayout(new GridLayout(4, 4));
// Create buttons to attach to the buttons panel
Jbuttons[0] = new JButton("Change Colour");
Jbuttons[1] = new JButton("Up");
Jbuttons[2] = new JButton("Text");
Jbuttons[3] = new JButton("Left");
Jbuttons[4] = new JButton("Enlarge");
Jbuttons[5] = new JButton("Right");
Jbuttons[6] = new JButton("Rectangle");
Jbuttons[7] = new JButton("Down");
Jbuttons[8] = new JButton("Circle");
Jbuttons[9] = new JButton("Save");
Jbuttons[10] = new JButton("Load");
//Add the buttons to the buttons panel
for (int i=0; i<11; i++) {
Jbuttons[i].addActionListener(new ButtonListener());
buttons.add(Jbuttons[i]);
}
}
}
class CanvasPanel extends JPanel {
//Constructor
CanvasPanel() {
// Create "canvas" to hold a label for the buttons panel along with the button panel itself
this.setLayout(new BorderLayout());
this.add(new JLabel("CONTROL PANEL"),BorderLayout.NORTH);
this.add(buttons, BorderLayout.WEST); //LINE 71 add the button panel to the canvas panel
//test
this.add(new FigurePanel(FigurePanel.RECTANGLE), BorderLayout.CENTER);
}
}
}
答案 0 :(得分:4)
我认为这是因为你在按钮之前实例化了画布。 buttons变量用于CanvasPanel的构造函数