Java JComboBox handle action event

Description

Java JComboBox handle action event

// 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;//from w w w.j ava2  s.c  o m
   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