I'm having a problem where i am making a simple combo box program that when it runs shows a pic, you can have a drop down box to select a different pic, very simple. I have an array for the file name of each, and a second array to store the pics themselves.
The error i am getting is "array out of bounds index 1" However i don't see how this can be happening.

THIS IS MY CLASS TO RUN IT

import javax.swing.JFrame;


public class apples 
{

    public static void main(String []args)
    {


      Gui go=new Gui();//New Gui object
      go.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);//Closes the program
      go.setSize(300,300);//Dimensions
      go.setVisible(true);//Makes it visible

    }





}

THIS IS THE MAIN CODE

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

public class Gui extends JFrame

{

   private JComboBox box; //This will be our list
   private JLabel picture;//This will be our picture        


   //We need 2 arrays the first will store the file name
   //The second will store the picture itself

   private static String[] filename={"ones.png","one.png"};
   //An array of string type as it stores the file name which is text
   //We now have an array called filename with 2 elements , the two pics

   private Icon[] pics = {new ImageIcon (getClass().getResource(filename[0]))};
   //This array will store the pictures



   public Gui()
   {

       super("The title");//Menu title
       setLayout(new FlowLayout());//Default layout

       box=new JComboBox(filename);//Will set up our combo box 
       //Will then put any filename pics as an option we have 2 this time

       box.addItemListener(new ItemListener()//This makes an anonymous inner 
       //Class the class is below, instead of a seperate handler class
       {

         @Override
         public void itemStateChanged(ItemEvent event)
         {

       if(event.getStateChange()==ItemEvent.SELECTED)
       picture.setIcon(pics[box.getSelectedIndex()]);
       //If the item is selected then get index ("whatever index")



         }
       }
               );

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


   }

}

Solved. I had left out the second element here
private Icon[] pics = {new ImageIcon (getClass().getResource(filename[0]))};
Should have been
private Icon[] pics = {new ImageIcon (getClass().getResource(filename[0])),new ImageIcon (getClass().getResource(filename[1]))};

For anyone interested!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.