gpt4 book ai didi

java - HashMap 上的 NullPointerException

转载 作者:行者123 更新时间:2023-11-30 04:10:24 24 4
gpt4 key购买 nike

我有一个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?我知道我不需要显式创建整数。

最佳答案

Integer numb = new Integer(random.nextInt(images.size()));
JButton butt = images.get(1);
centerPanel.add(butt);
images.remove(numb);

在一次迭代中 numb 将等于 1(这可能在任何迭代中发生,因为您检索 0 和 images.size() 之间的随机数,并且这肯定会发生,因为images.size() 从 11 减少到 1),因此索引 1 下的元素将被删除。在下一次迭代中,images.get(1) 返回null。然后您尝试 centerPanel.add(butt); 并获得 NPE。

关于java - HashMap 上的 NullPointerException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19747581/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com