Link to home
Start Free TrialLog in
Avatar of glynco
glynco

asked on

How can I add a Listener that responds to ENTER key?

How can I add a Listener that responds to ENTER key instead of clicking Print button?
//  SimpleList.java
//
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
 
public class NewClass extends JPanel {
    String label[] = { "Zero","One","Two","Three","Four","Five","Six",
                       "Seven","Eight","Nine","Ten","Eleven" };
    JList list;
 
    public NewClass( ) {
        this.setLayout(new BorderLayout( ));
        list = new JList(label);
        JScrollPane pane = new JScrollPane(list);
        JButton button = new JButton("Print");
        button.addActionListener(new PrintListener( ));
 
        add(pane, BorderLayout.CENTER);
        add(button, BorderLayout.SOUTH);
    }
 
    
    
    class PrintListener implements ActionListener {
        public void actionPerformed(ActionEvent e) {
            int selected[] = list.getSelectedIndices( );
            System.out.println("Selected Elements:  ");
 
            for (int i=0; i < selected.length; i++) {
                String element =
                      (String)list.getModel( ).getElementAt(selected[i]);
                System.out.println("  " + element);
            }
        }
    }
 
    
    public static void main(String s[]) {
         JFrame frame = new JFrame("Simple List Example");
         frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
         frame.setContentPane(new NewClass( ));
         frame.setSize(250, 200);
         frame.setVisible(true);
    }
    
    
    
}
 
    
    // An inner class to respond to clicks of the Print button

Open in new window

ASKER CERTIFIED SOLUTION
Avatar of n_sachin1
n_sachin1
Flag of India image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial