代码之家  ›  专栏  ›  技术社区  ›  Khaled Afify

JComboBox应用程序中的ArrayIndexOutOfBoundsException

  •  0
  • Khaled Afify  · 技术社区  · 10 年前
    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 回复  |  直到 10 年前
        1
  •  3
  •   MadProgrammer    10 年前

    让我们从这样一个事实开始:您指定了两个文件名,但只加载了一个图像

    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]))
    };