publicclassDemoKeyEvents{publicstaticvoidmain(String[]args){DemoKeyEventsFrameframe=newDemoKeyEventsFrame();frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);frame.setTitle("DemoKeyEvents");frame.pack();frame.setVisible(true);}}classDemoKeyEventsFrameextendsJFrameimplementsKeyListener{privateJTextFieldenterField;publicDemoKeyEventsFrame(){enterField=newJTextField(10);enterField.addKeyListener(this);JPanelpanel=newJPanel();panel.add(newJLabel("Enter some text:"));panel.add(enterField);panel.setBorder(BorderFactory.createEmptyBorder(10,10,10,10));this.setContentPane(panel);}publicvoidkeyPressed(KeyEventke){System.out.println(ke.paramString());finalKeyStrokeBEL=KeyStroke.getKeyStroke(KeyEvent.VK_A,KeyEvent.CTRL_MASK);KeyStrokek=KeyStroke.getKeyStroke(ke.getKeyCode(),ke.getModifiers());if(k==BEL){System.out.println("Ctrl-A pressed!");Toolkit.getDefaultToolkit().beep();}}publicvoidkeyReleased(KeyEventke){System.out.println(ke.paramString());}publicvoidkeyTyped(KeyEventke){System.out.println(ke.paramString());}}
publicclassDemoKeyEvents2{publicstaticvoidmain(String[]args){DemoKeyEvents2Frameframe=newDemoKeyEvents2Frame();frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);frame.setTitle("DemoKeyEvents2");frame.pack();frame.setVisible(true);}}classDemoKeyEvents2FrameextendsJFrameimplementsKeyListener{privateJTextFieldpro;privateJTextFieldcon;// constructorpublicDemoKeyEvents2Frame(){// construct and configure componentspro=newJTextField(10);con=newJTextField(10);// add listenerspro.addKeyListener(this);con.addKeyListener(this);// arrange components// add components to panelsJPanelbanner=newJPanel();banner.add(newJLabel("WHAT'S YOUR OPINION ON ANCHOIVES?"));JPanelproPanel=newJPanel();proPanel.add(newJLabel("Pro:"));proPanel.add(pro);JPanelconPanel=newJPanel();conPanel.add(newJLabel("Con:"));conPanel.add(con);// put panels in a content pane panelJPanelcontentPane=newJPanel();contentPane.setLayout(newGridLayout(3,1));contentPane.add(banner);contentPane.add(proPanel);contentPane.add(conPanel);// make panel this JFrame's content panethis.setContentPane(contentPane);}publicvoidkeyPressed(KeyEventke){}// do nothingpublicvoidkeyReleased(KeyEventke){}// do nothingpublicvoidkeyTyped(KeyEventke){Objectsource=ke.getSource();// check if event occurred on pro componentif(source==pro)System.out.println("Pro : "+ke.paramString());// check if event occurred on con componentelseif(source==con)System.out.println("Con : "+ke.paramString());}}
publicclassDemoKeyEvents3{publicstaticvoidmain(String[]args){DemoKeyEvents3Frameframe=newDemoKeyEvents3Frame();frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);frame.setTitle("DemoKeyEvents3");frame.pack();frame.setVisible(true);}}classDemoKeyEvents3FrameextendsJFrame{privateJTextFieldenterField;// constructorpublicDemoKeyEvents3Frame(){enterField=newJTextField(10);enterField.addKeyListener(newKeyListener(){publicvoidkeyPressed(KeyEventke){System.out.println(ke.paramString());finalKeyStrokeBEL=KeyStroke.getKeyStroke(KeyEvent.VK_A,KeyEvent.CTRL_MASK);KeyStrokek=KeyStroke.getKeyStroke(ke.getKeyCode(),ke.getModifiers());if(k==BEL){System.out.println("Ctrl-A pressed!");Toolkit.getDefaultToolkit().beep();}}publicvoidkeyReleased(KeyEventke){System.out.println(ke.paramString());}publicvoidkeyTyped(KeyEventke){System.out.println(ke.paramString());}});JPanelpanel=newJPanel();panel.add(newJLabel("Enter some text:"));panel.add(enterField);panel.setBorder(BorderFactory.createEmptyBorder(10,10,10,10));this.setContentPane(panel);}}
No hay que redefinir todos los métodos de KeyListener
Los métodos de KeyAdapter están definidos pero vacíos
classDemoKeyEvents4FrameextendsJFrame{privateJTextFieldenterField;// constructorpublicDemoKeyEvents4Frame(){enterField=newJTextField(10);enterField.addKeyListener(newKeyAdapter(){@OverridepublicvoidkeyPressed(KeyEventke){System.out.println(ke.paramString());finalKeyStrokeBEL=KeyStroke.getKeyStroke(KeyEvent.VK_A,KeyEvent.CTRL_MASK);KeyStrokek=KeyStroke.getKeyStroke(ke.getKeyCode(),ke.getModifiers());if(k==BEL){System.out.println("Ctrl-A pressed!");Toolkit.getDefaultToolkit().beep();}}@OverridepublicvoidkeyReleased(KeyEventke){System.out.println(ke.paramString());}@OverridepublicvoidkeyTyped(KeyEventke){System.out.println(ke.paramString());}});JPanelpanel=newJPanel();panel.add(newJLabel("Enter some text:"));panel.add(enterField);panel.setBorder(BorderFactory.createEmptyBorder(10,10,10,10));this.setContentPane(panel);}}
importjava.awt.BorderLayout;importjava.awt.event.KeyAdapter;importjava.awt.event.KeyEvent;importjava.util.HashMap;importjavax.swing.JFrame;importjavax.swing.JTextField;publicclassTest{@FunctionalInterfaceinterfaceKeyAction{publicvoiddoAction();//un sólo método abstracto}publicstaticvoidmain(String[]args){HashMap<Integer,KeyAction>keyDispatcher=newHashMap<Integer,KeyAction>();//Crear instancias de FunctionalInterface mediante lambdaskeyDispatcher.put(KeyEvent.VK_W,()->moveUp());keyDispatcher.put(KeyEvent.VK_S,()->moveDown());keyDispatcher.put(KeyEvent.VK_A,()->moveLeft());keyDispatcher.put(KeyEvent.VK_D,()->moveRight());// Using a JTextField out of simplicityJTextFieldfield=newJTextField();field.addKeyListener(newKeyAdapter(){@OverridepublicvoidkeyPressed(KeyEventarg0){try{keyDispatcher.get(arg0.getKeyCode()).doAction();}catch(NullPointerExceptione){System.out.println("That button doesn't do anything yet...");}}});JFrameframe=newJFrame("Listener Frame");frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);frame.add(field,BorderLayout.NORTH);frame.pack();frame.setVisible(true);}privatestaticvoidmoveUp(){System.out.println("Moving up");}privatestaticvoidmoveDown(){System.out.println("Moving down");}privatestaticvoidmoveLeft(){System.out.println("Moving left");}privatestaticvoidmoveRight(){System.out.println("Moving right");}}
importjava.awt.*;importjava.awt.event.*;importjavax.swing.*;/** * This simple Swing program demonstrates how to use Lambda expressions in * action listener. * * @author www.codejava.net */publicclassListenerLambdaExampleextendsJFrame{privateJButtonbutton=newJButton("Click Me!");publicListenerLambdaExample(){super("Listener Lambda Example");getContentPane().setLayout(newFlowLayout());getContentPane().add(button);// Java 7 - tradicional, sin lambdasbutton.addActionListener(newActionListener(){publicvoidactionPerformed(ActionEventevt){System.out.println("Handled by anonymous class listener");}});// Java 8 - con lambdasbutton.addActionListener(e->System.out.println("Handled by Lambda listener"));button.addActionListener(e->{System.out.println("Handled Lambda listener");});setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);setSize(300,100);setLocationRelativeTo(null);}publicstaticvoidmain(String[]args){SwingUtilities.invokeLater(newRunnable(){publicvoidrun(){newListenerLambdaExample().setVisible(true);}});}}