gpt4 book ai didi

java - JComboBox 应用程序中的 ArrayIndexOutOfBoundsException

转载 作者:行者123 更新时间:2023-12-01 22:45:00 25 4
gpt4 key购买 nike

import java.awt.*;
import java.awt.event.*;
import javax.swing.* ;

public class GUI extends JFrame {
private JComboBox box ;

private JLabel picture ;

private static String[] filename={"Phone.png","Music.png"};

private Icon[] pics={new ImageIcon(getClass().getResource(filename[0]))};

public GUI(){
super("JComboBox");
setLayout(new FlowLayout());
box=new JComboBox (filename);

box.addItemListener(
new ItemListener(){
public void itemStateChanged(ItemEvent event){
if(event.getStateChange()==ItemEvent.SELECTED)
picture.setIcon(pics[box.getSelectedIndex()]);
}
}
);

add(box);
picture=new JLabel(pics[0]);
add(picture);
}
}

当我尝试检查 music.png 时,它给了我这个错误

Exception in thread "AWT-EventQueue-1" java.lang.ArrayIndexOutOfBoundsException: 1
at GUI$1.itemStateChanged(GUI.java:20)
at javax.swing.JComboBox.fireItemStateChanged(JComboBox.java:1222)
at javax.swing.JComboBox.selectedItemChanged(JComboBox.java:1279)
at javax.swing.JComboBox.contentsChanged(JComboBox.java:1326)
...

最佳答案

首先,您指定了两个文件名,但只加载了一张图像

private static String[] filename = {"Phone.png", "Music.png"};
private Icon[] pics = {new ImageIcon(getClass().getResource(filename[0]))};

尝试加载两个图像...

private Icon[] pics = {
new ImageIcon(getClass().getResource(filename[0])),
new ImageIcon(getClass().getResource(filename[1]))
};

关于java - JComboBox 应用程序中的 ArrayIndexOutOfBoundsException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25499667/

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