Java JComboBox create from array of String

Description

Java JComboBox create from array of String

// Demonstrate JComboBox. 
import java.awt.FlowLayout;

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

class Demo extends JPanel {
   JLabel jlab;/* w ww.  ja  v  a 2  s.c  om*/
   public Demo() {
    
      JComboBox<String> jcb;

      String options[] = { "CSS", "HTML", "Java", "Javascript" };

      setLayout(new FlowLayout());

      jcb = new JComboBox<String>(options);
      add(jcb);

      jcb.addActionListener(e->{
            String s = (String) jcb.getSelectedItem();
            jlab.setIcon(new ImageIcon(s + ".png"));
      });

      // Create a label and add it to the content pane.
      jlab = new JLabel(new ImageIcon("css.png"));
      add(jlab);
   }
}

public class Main {
   public static void main(String[] args) {
      Demo panel = new Demo();

      JFrame application = new JFrame();

      application.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

      application.add(panel);
      application.setSize(250, 250);
      application.setVisible(true);
   }
}



PreviousNext

Related