Java JLabel set icon

Description

Java JLabel set icon

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

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

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

  private static final String[] names = { "1.gif", "2.gif", "3.gif", "4.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])) };

  // Main constructor adds JComboBox to JFrame
  public Main() {
    super("Testing JComboBox");
    setLayout(new FlowLayout()); // set frame layout

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

    imagesJComboBox.addItemListener(new ItemListener() {
      @Override//  ww  w . ja va 2 s .co m
      public void itemStateChanged(ItemEvent event) {
        // determine whether item selected
        if (event.getStateChange() == ItemEvent.SELECTED)
          label.setIcon(icons[imagesJComboBox.getSelectedIndex()]);
      }
    });

    add(imagesJComboBox);
    label = new JLabel(icons[0]);
    add(label);
  }

  public static void main(String[] args) {
    Main Main = new Main();
    Main.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    Main.setSize(350, 150);
    Main.setVisible(true);
  }
}



PreviousNext

Related