我有以下代码将JLabels
添加到JPanel
,然后将此JPanel
添加到JFrame
,但我得到的是NullPointerException
我无法解决原因。我的代码如下:
public void createImage(String view) {
String [] viewSplit = view.split("(?!^)");
if(viewSplit.length == 25) {
fiveByFiveLook.setLayout(null);
fiveByFiveLook.setBackground(Color.WHITE);
fiveByFiveLook.setBounds(48, 75, 404, 404);
fiveByFiveLook.setVisible(true);
ArrayList<String> viewArray = new ArrayList<String>(Arrays.asList(viewSplit));
JLabel fiveByFiveLabels[][] = new JLabel[5][5];
for(int i = 0, k = 0; i <= 4; i++, k = k + 80) {
for(int j = 0, l = 0; j <= 4; j++, l = l + 80) {
if(viewArray.get(0).equals("X")) {
fiveByFiveLabels[i][j].setIcon(new ImageIcon("Blank.jpg"));
fiveByFiveLook.add(fiveByFiveLabels[i][j]);
viewArray.remove(0);
}
else if(viewArray.get(0).equals("#")) {
fiveByFiveLabels[i][j].setIcon(new ImageIcon("Wall.jpg"));
fiveByFiveLook.add(fiveByFiveLabels[i][j]);
viewArray.remove(0);
}
else if(viewArray.get(0).equals(".")) {
fiveByFiveLabels[i][j].setIcon(new ImageIcon("Floor.jpg"));
fiveByFiveLook.add(fiveByFiveLabels[i][j]);
viewArray.remove(0);
}
else if(viewArray.get(0).equals("E")) {
fiveByFiveLabels[i][j].setIcon(new ImageIcon("Exit.jpg"));
fiveByFiveLook.add(fiveByFiveLabels[i][j]);
viewArray.remove(0);
}
else if(viewArray.get(0).equals("G")) {
fiveByFiveLabels[i][j].setIcon(new ImageIcon("Gold.png"));
fiveByFiveLook.add(fiveByFiveLabels[i][j]);
viewArray.remove(0);
}
fiveByFiveLabels[i][j].setBounds(l, k, 85, 85);
}
}
humanGameWindow.add(fiveByFiveLook);
}
else if(viewSplit.length == 49) {
sevenBySevenLook.setLayout(null);
sevenBySevenLook.setBackground(Color.WHITE);
sevenBySevenLook.setBounds(48, 75, 404, 404);
sevenBySevenLook.setVisible(true);
JButton sevenBySevenLabels[][] = new JButton[7][7];
for(int i = 0, k = 0; i <= 6; i++, k = k + 57) {
for(int j = 0, l = 0; j <= 6; j++, l = l + 57) {
sevenBySevenLabels[i][j] = new JButton();
sevenBySevenLabels[i][j].setBounds(l, k, 62, 62);
//sevenBySevenLabels[i][j].setIcon(new ImageIcon("Sword copy.jpg"));
sevenBySevenLook.add(sevenBySevenLabels[i][j]);
}
}
humanGameWindow.add(sevenBySevenLook);
}
}
错误是:
java.lang.NullPointerException
at dodGUI.createImage(dodGUI.java:324)
at dodGUI.handleResponse(dodGUI.java:61)
at dodGUI$1.run(dodGUI.java:79)
at java.lang.Thread.run(Thread.java:744)
Null Pointer2: java.lang.NullPointerException
发生在这一行:
fiveByFiveLabels[i][j].setBounds(l, k, 85, 85);
请有人建议为什么会这样:)
答案 0 :(得分:3)
该行
JLabel fiveByFiveLabels[][] = new JLabel[5][5];
创建一个可容纳5 x 5标签的空数组。但里面没有标签。所有数组条目均为null
。
插入此行
for(int i = 0, k = 0; i <= 4; i++, k = k + 80) {
for(int j = 0, l = 0; j <= 4; j++, l = l + 80) {
fiveByFiveLabels[i][j] = new JLabel(); // <--- This one...
并阅读http://docs.oracle.com/javase/tutorial/java/nutsandbolts/arrays.html