JComboBox应用程序中的ArrayIndexOutOfBoundsException

时间:2014-08-26 06:48:21

标签: java swing jcombobox indexoutofboundsexception

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)
        ...

1 个答案:

答案 0 :(得分:3)

让我们从你指定了两个文件名,但只加载一个图像

这一事实开始
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]))
};