How can we catch a double click and enter key events for a JList in Java?

AWTJavaObject Oriented ProgrammingProgrammingSwing

A JList can extend JComponent class that allows the user to choose either a single or multiple selections. A JList can generate a ListSelectiionListener interface and it includes one abstract method valueChanged(). A JList can also generate a MouseListener interface to catch a double click event in the list and generates a KeyListener interface to catch an enter key event.

Example

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
import java.util.*;
public class JListTest extends JFrame {
   public JListTest() {
      setTitle("JList Test");
      setLayout(new FlowLayout());
      Vector v = new Vector();
      for (int i = 1; i < 15; i++) {
         v.addElement("Item #" + i);
      }
      add(new JLabel("Double-clicked on: "));
      final JTextField dblTextField = new JTextField(15);
      add(dblTextField);
      add(new JLabel("Enter key on: "));
      final JTextField entTextField = new JTextField(15);
      add(entTextField);
      final JList list = new JList(v);
      // catch double-click events
      list.addMouseListener(new MouseAdapter() {
         public void mouseClicked(MouseEvent me) {
            if (me.getClickCount() == 2) {
               dblTextField.setText(""+list.getSelectedValue());
            }
         }
      });
      // catch enter-key events
      list.addKeyListener(new KeyAdapter() {
         public void keyReleased(KeyEvent ke) {
            if(ke.getKeyCode() == KeyEvent.VK_ENTER) {
               entTextField.setText(""+list.getSelectedValue());
            }
         }
      });
      add(new JScrollPane(list));
      setSize(375, 250);
      setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      setLocationRelativeTo(null);
      setVisible(true);
   }
   public static void main(String[] args) {
      new JListTest();
   }
}

Output

raja
Published on 16-Jul-2019 22:43:53
Advertisements