JComboBox that displays a list of image names with Lambda expression - Java Swing

Java examples for Swing:JComboBox

Description

JComboBox that displays a list of image names with Lambda expression

Demo Code

import java.awt.FlowLayout;
import java.awt.event.ItemEvent;

import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;

class ComboBoxFrame extends JFrame 
{
   private final JComboBox<String> imagesJComboBox; // hold icon names
   private final JLabel label; // displays selected icon

   private static final String[] names = 
      {"a.gif", "b.gif",  "c.gif", "d.gif"};
   private final Icon[] icons = { 
      new ImageIcon(getClass().getResource(names[0])),
      new ImageIcon(getClass().getResource(names[1])), 
      new ImageIcon(getClass().getResource(names[2])),
      new ImageIcon(getClass().getResource(names[3])) };

   // ComboBoxFrame constructor adds JComboBox to JFrame
   public ComboBoxFrame()
   {/*from   ww  w .jav a2 s  .  c o  m*/
      super("Testing JComboBox");
      setLayout(new FlowLayout()); // set frame layout     

      imagesJComboBox = new JComboBox<String>(names); // set up JComboBox
      imagesJComboBox.setMaximumRowCount(3); // display three rows

      add(imagesJComboBox);
      label = new JLabel(icons[0]); 
      add(label);
      imagesJComboBox.addItemListener(event -> { 
           if (event.getStateChange() == ItemEvent.SELECTED)
              label.setIcon(icons[imagesJComboBox.getSelectedIndex()]);
           }); 
   }
}
public class Main
{
   public static void main(String[] args)
   { 
      ComboBoxFrame comboBoxFrame = new ComboBoxFrame(); 
      comboBoxFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      comboBoxFrame.setSize(350, 150); 
      comboBoxFrame.setVisible(true); 
   } 
}

Related Tutorials