Java AWT KeyAdapter extend

Introduction

Java provides adapter classes for each listener interface with more than one method.

For example, the MouseAdapter class implements the MouseListener interface.

An adapter class implements empty versions of all its interface's methods.

A listener class may be created quickly by extending an adapter class and overriding only the methods of interest.

import java.awt.FlowLayout;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;

import javax.swing.JFrame;
import javax.swing.JTextField;

public class Main extends JFrame {
   JTextField t = new JTextField(15);

   Main() {/*from ww  w.j  a va 2s  .com*/
      setSize(180, 80);
      setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      setLayout(new FlowLayout());
      add(t);
      t.addKeyListener(new CaseChanger());
      setVisible(true);
   }

   class CaseChanger extends KeyAdapter {
      public void keyReleased(KeyEvent e) {
         if (e.getSource() instanceof JTextField) {
            JTextField t = (JTextField) e.getSource();
            int cp = t.getCaretPosition();
            t.setText(t.getText().toUpperCase());
            t.setCaretPosition(cp);
         }
      }
   }

   public static void main(String args[]) {
      new Main();
   }
}



PreviousNext

Related