我正在學習使用java.swing庫。我正在嘗試創建一個非常簡單的計算器佈局。我已經添加了addNumbers方法。我試圖在計算器中顯示按鈕,並且我用於loops.buttons不出現我得到nullpointerexception。按鈕不出現,空指針異常
import java.awt.*;
import javax.swing.*;
public class Calculator extends JFrame{
/**
* @param args
*/
//dEFINE WIDTH AND HEIGHT
private static final int WIDTH = 400;
private static final int HEIGHT = 600;
//Values for buttons having numbers
private JButton[] numButton;
public static void main(String[] args) {
// TODO Auto-generated method stub
Calculator myCalculator = new Calculator();
}
public Calculator(){
setTitle("Simple Calculator");
setSize(WIDTH,HEIGHT);
setVisible(true);
setDefaultCloseOperation(EXIT_ON_CLOSE);
Container Pane = getContentPane();
Pane.setLayout(new GridLayout(3,3));
//Add numbers to screen now
addNumbers(Pane);
}
//Function to add numbers on screen
public void addNumbers(Container P){
for(int i = 1; i <= 9; i++){
numButton[i] = new JButton(String.valueOf(i));
P.add(numButton[i]);
}
}
}
你可以添加錯誤消息和堆棧跟蹤 –
你的錯誤在哪行代碼? – OPK
可能的重複:[什麼是空指針異常,以及如何解決它?](http://stackoverflow.com/questions/218384/what-is-a-null-pointer-exception-and-how-do -i-fix-it) – Pshemo