Java Swing How to - Get selected JScrollPane element








Question

We would like to know how to get selected JScrollPane element.

Answer

import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
//from www. j av  a  2s  . co  m
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JList;
import javax.swing.JOptionPane;

public class Main {

  public static void main(String[] args) {
    String[] items = new String[] { "One", "Two", "Three", "Four" };
    JList<String> list = new JList<>(items);
    JFrame f = new JFrame();
    f.add(list, BorderLayout.CENTER);
    JButton btn = new JButton("Get selected");
    btn.addActionListener(new ActionListener() {
      @Override
      public void actionPerformed(ActionEvent e) {
        JOptionPane.showConfirmDialog(f,
            "You Selected : " + list.getSelectedValue(), "Display",
            JOptionPane.PLAIN_MESSAGE);
      }
    });

    f.add(btn, BorderLayout.SOUTH);
    f.pack();
    f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    f.setVisible(true);
  }
}