Java JList handle selection change event

Description

Java JList handle selection change event


// JList that displays a list of colors.
import java.awt.Color;
import java.awt.FlowLayout;

import javax.swing.JFrame;
import javax.swing.JList;
import javax.swing.JScrollPane;
import javax.swing.ListSelectionModel;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;

public class Main extends JFrame {
  private final JList<String> colorJList; // list to display colors
  private static final String[] colorNames = { "Black", "Blue", "Cyan", "Dark Gray", "Gray", "Green", "Light Gray",
      "Magenta", "Orange", "Pink", "Red", "White", "Yellow" };
  private static final Color[] colors = { Color.BLACK, Color.BLUE, Color.CYAN, Color.DARK_GRAY, Color.GRAY, Color.GREEN,
      Color.LIGHT_GRAY, Color.MAGENTA, Color.ORANGE, Color.PINK, Color.RED, Color.WHITE, Color.YELLOW };

  public Main() {
    super("List Test");
    setLayout(new FlowLayout());

    colorJList = new JList<String>(colorNames); // list of colorNames
    colorJList.setVisibleRowCount(5); // display five rows at once

    colorJList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);

    // add a JScrollPane containing JList to frame
    add(new JScrollPane(colorJList));

    colorJList.addListSelectionListener(new ListSelectionListener() // anonymous inner class
    {//from ww w . j  a  v a  2s  .  co  m
      // handle list selection events
      @Override
      public void valueChanged(ListSelectionEvent event) {
        getContentPane().setBackground(colors[colorJList.getSelectedIndex()]);
      }
    });
  }

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



PreviousNext

Related