Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Need some java help this program is supposed to use a drop down list to be able

ID: 674798 • Letter: N

Question

Need some java help this program is supposed to use a drop down list to be able to display two different pictures. I haVe my pictures named b.png and x.png. right now only one picture loads and the other gives an exception. Any ideas?? THANKS!!!

import java.awt.FlowLayout;
import java.awt.Font;
import javax.swing.ButtonGroup;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JRadioButton;
import javax.swing.JTextField;
import javax.swing.JPasswordField;
import javax.swing.JOptionPane;

import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;

public class GUI extends JFrame {
  
   private JComboBox box; // created a box
   private JLabel picture;//variable for pic we want on right side of drop box
  
  
   private static String[] filename = {"b.png", "x.png"}; // array of filename
   private Icon[] pics = {new ImageIcon(filename[0])}; //array of images

public GUI() {
   super("the title"); // title of box
   setLayout (new FlowLayout()); // default layout
  
   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);
   }
}

*********************MAIN****************

public class apples {

   public static void main (String[] args) {
      
       GUI go = new GUI();
       go.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
       go.setSize(300,200);
       go.setVisible(true);  
   }
}

Explanation / Answer

Solution:

change the line :  private Icon[] pics = {new ImageIcon(filename[0])}; //array of images

to

private Icon[] pics = {new ImageIcon(filename[0]),new ImageIcon(filename[1])}; //array of images

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote