我正在設計一個計算器控制檯,將採取兩個值,創建一個類的新實例AdditionProblem它將返回問題的2個加數的JLabel數組,金額和金額從每個地方(它顯示的工作)攜帶。我有一個自定義類,它擴展了JPanel和一個JPanel的ArrayList,它們在點擊添加按鈕後代表Solved問題的每一行。 AdditionProblem類和Main類一樣好。在創建控制檯類以顯示答案後,單擊添加按鈕時,我在第44行「row.add(new JPanel)」上得到一個空指針異常。如果您需要查看我的代碼的其餘部分,請讓我知道,我會發布它,但爲了節省時間,我將發佈Console類,因爲其他類一直在正常工作,直到我將代碼移到此類中。NullPointerException ArrayList <JPanel>計算器圖形用戶界面
package Main;
import java.awt.Color;
import java.awt.Dimension;
import java.util.ArrayList;
import javax.swing.BoxLayout;
import javax.swing.JLabel;
import javax.swing.JPanel;
import Aritmathic.AdditionProblem;
public class Console extends JPanel {
private int width = 230, height = 260;
private ArrayList<JPanel> rows;
private ArrayList<JLabel> columns;
private void init(){
this.setPreferredSize(new Dimension(width, height));
this.setBackground(Color.WHITE);
this.setLayout(new BoxLayout(this, BoxLayout.Y_AXIS));
}
public Console(){
init();
}
public void printAnswer(AdditionProblem problem){
int rowIndex = 0;
JLabel[] sumLabels = problem.getSumLabels();
JLabel[] addend1Labels = problem.getAddend1Labels();
JLabel[] addend2Labels = problem.getAddend2Labels();
JLabel[] carriedLabels = problem.getCarriedLabels();
rows.add(new JPanel());
for(int i = 0; i < carriedLabels.length; i++){
rows.get(rowIndex).add(carriedLabels[i]);
}
rowIndex++;
rows.add(new JPanel());
for(int i = 0; i < addend1Labels.length; i++){
rows.get(rowIndex).add(addend1Labels[i]);
}
rowIndex++;
rows.add(new JPanel());
for(int i = 0; i < addend2Labels.length; i++){
rows.get(rowIndex).add(addend2Labels[i]);
}
rowIndex++;
rows.add(new JPanel());
for(int i = 0; i < sumLabels.length; i++){
rows.get(rowIndex).add(new JLabel("__"));
}
rowIndex++;
rows.add(new JPanel());
for(int i = 0; i < sumLabels.length; i++){
rows.get(rowIndex).add(sumLabels[i]);
}
for(int i = 0; i < rows.size(); i++){
this.add(rows.get(i));
}
}
}
哦哇我覺得啞巴哈哈謝謝你! –
Upvote我的問題,所以我可以upvote你的答案:D –