Advertisement
makispaiktis

9. JCombobox - Dropdwon list of images

May 30th, 2022 (edited)
920
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.41 KB | None | 0 0
  1. import java.awt.*;
  2. import java.awt.event.*;
  3. import javax.swing.*;
  4.  
  5. public class Gui extends JFrame{
  6.  
  7.     // Variables
  8.     private JComboBox box;      // dropdown list
  9.     private JLabel picture;
  10.     private static String[] filename = {"b.png", "x.png"};      // Images' names
  11.     private Icon[] pics = {new ImageIcon(getClass().getResource(filename[0])), new ImageIcon(getClass().getResource(filename[1]))};     // Actual images
  12.  
  13.     // Constructor
  14.     public Gui(){
  15.  
  16.         super("JFrame's title");
  17.         setLayout(new FlowLayout());
  18.         box = new JComboBox(filename);      // Puts all array's elements in a dropdown list
  19.         // Functionality with item listener
  20.         box.addItemListener(
  21.                 // Anonymus inner class
  22.                 new ItemListener() {
  23.                     @Override
  24.                     public void itemStateChanged(ItemEvent event) {
  25.                         if(event.getStateChange() == ItemEvent.SELECTED)
  26.                             picture.setIcon(pics[box.getSelectedIndex()]);
  27.                     }
  28.                 }
  29.         );
  30.         add(box);
  31.         picture = new JLabel(pics[0]);      // Default value
  32.         add(picture);
  33.     }
  34.  
  35.     // Main Function
  36.     public static void main(String[] args){
  37.         Gui gui = new Gui();
  38.         gui.setDefaultCloseOperation(EXIT_ON_CLOSE);
  39.         gui.setSize(600, 600);
  40.         gui.setVisible(true);
  41.     }
  42.  
  43. }
  44.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement