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

When I try to check music.png it gives me this error

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)
        ...
dimo414
  • 47,227
  • 18
  • 148
  • 244
  • Please post the full stack trace, rather than a partial screeshot. – dimo414 Aug 26 '14 at 06:53
  • 1) A single blank line of white space is *always* enough. Blank lines after `{` or before `}` are also typically redundant. 2) Always copy/paste error or exception output (as opposed to a link to a screenshot showing your IDE & part of the stack trace). 3) See also [What is a stack trace, and how can I use it to debug my application errors?](http://stackoverflow.com/q/3988788/418556) – Andrew Thompson Aug 26 '14 at 06:53
  • @dimo414 to trace the error http://pastebin.com/b5U1gN5x – Khaled Afify Aug 26 '14 at 07:00
  • am sorry this first post in stackoverflow i will post full stack trace in the next time thanks for edit :) – Khaled Afify Aug 26 '14 at 07:07
  • *"am sorry"* No need to be sorry at all. :) *"i will post full stack trace in the next time"* ..because that is way better. +1. And welcome to Stack Overflow. – Andrew Thompson Aug 26 '14 at 07:09
  • @Andrew Thompson thanks brother :) – Khaled Afify Aug 26 '14 at 07:20

1 Answers1

3

Let's start with the fact that you've specified two file names, but only loaded one image

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

Try loading both images...

private Icon[] pics = {
    new ImageIcon(getClass().getResource(filename[0])),
    new ImageIcon(getClass().getResource(filename[1]))
};
MadProgrammer
  • 343,457
  • 22
  • 230
  • 366