我有一个HashMap<Integer, JButton>
. 问题是当我尝试检索我得到的值时null
,而不是 JButton。当我尝试在最后一行将“butt”添加到 centerPanel 时发生异常。下面是我的代码片段和 2 个类字段,用于透视代码。
public class GUI {
private JPanel centerPanel;
private JButton button;
private JLabel label;
private Image source;
private Image image;
private HashMap<Integer, JButton> images = new HashMap<>();
public GUI() {
centerPanel = new JPanel();
ImageIcon sid = new ImageIcon(GUI.class.getResource("koala.jpg"));
source = sid.getImage();
int ind = 0;
for ( int i = 0; i < 4; i++) {
for ( int j = 0; j < 3; j++) {
if ( j == 2 && i == 3) {
label = new JLabel("");
centerPanel.add(label);
} else {
button = new JButton();
button.addActionListener(this);
images.put(new Integer(++ind), button);
image = createImage(new FilteredImageSource(source.getSource(),
new CropImageFilter(j*width/3, i*height/4,
(width/3)+1, height/4)));
button.setIcon(new ImageIcon(image));
}
}
}
Random random = new Random();
for (int i=0; i<11; i++) {
Integer numb = new Integer(random.nextInt(images.size()));
JButton butt = images.get(1);
centerPanel.add(butt);
images.remove(numb);
}
setSize(1024, 768);
setTitle("Puzzle");
setResizable(false);
setLocationRelativeTo(null);
setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
setVisible(true);
}
public static void main(String[] args) {
new GUI();
}
}
为什么会发生 NullPointerException?我知道我不需要显式创建整数。