我收到一個NullPointerException異常,我不知道爲什麼。如果有人可以查看我的代碼並告訴我它有什麼問題,那就太好了。將ArrayList中的按鈕添加到JPanel中的NullPointerException
提示:構建按鈕的金字塔的 1)塊寬度 2)塊高度 3)行號
import java.awt.*;
import java.util.*;
import javax.swing.*;
public class BlockPyramidBuilder extends JPanel{
public static int height;
public static int width;
public static int rowNum;
public static JFrame frame = new JFrame();
public static Graphics g;
public static BlockPyramidBuilder test;
public static void main(String[]Args){
Scanner inputReader = new Scanner(System.in);
System.out.print("Block Height ------->");
height = inputReader.nextInt();
System.out.print("Block Width ------->");
width = inputReader.nextInt();
System.out.print("Row Num ------->");
rowNum = inputReader.nextInt();
test = new BlockPyramidBuilder(height, width, rowNum);
frame.add(test);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setVisible(true);
}
public BlockPyramidBuilder(int height, int width, int rowNum){
ArrayList<MyBox> array = new ArrayList<MyBox>();
int center = frame.getWidth();
int x = 0;
int y = 0;
for(int i = 1; i <= rowNum; i++){
y = height * (i-1);
for(int j = 1; j <= i; j++){
x = center + (width/2) * j;
System.out.println("x: " + x + " y: " + y);
MyBox r = new MyBox(x, y, width, height);
array.add(r);
}
}
for(int i = 0; i < array.size(); i++){
test.add(array.get(i));
}
}
}
class MyBox extends JButton{
public MyBox(int x, int y, int height, int width){
super();
setBackground(new java.awt.Color(37, 80, 130));
setFont(new java.awt.Font("Trebuchet MS", 0, 24));
setForeground(new java.awt.Color(38,38,38));
setSize(height, width);
setLocation(x, y);
}
}
代碼得到正確的座標輸入到繪製的框,但是有將MyBox添加到JPanel時出錯。另外,我想知道
'還有,我想知道嗎?想知道什麼?想知道如何在沒有堆棧的情況下幫助你? – nhgrif