FileDocCategorySizeDatePackage
KeyEventDemo.javaAPI DocExample3225Tue Dec 12 18:58:54 GMT 2000None

KeyEventDemo

public class KeyEventDemo extends JApplet implements ActionListener, KeyListener

Fields Summary
JTextArea
displayArea
JTextField
typingArea
static final String
newline
Constructors Summary
Methods Summary
public voidactionPerformed(java.awt.event.ActionEvent e)
Handle the button click.

        //Clear the text components.
        displayArea.setText("");
        typingArea.setText("");

        //Return the focus to the typing area.
        typingArea.requestFocus();
    
protected voiddisplayInfo(java.awt.event.KeyEvent e, java.lang.String s)

        String charString, keyCodeString, modString, tmpString;

        char c = e.getKeyChar();
        int keyCode = e.getKeyCode();
        int modifiers = e.getModifiers();

        if (Character.isISOControl(c)) {
            charString = "key character = "
                       + "(an unprintable control character)";
        } else {
            charString = "key character = '"
                       + c + "'";
        }

        keyCodeString = "key code = " + keyCode
                        + " ("
                        + KeyEvent.getKeyText(keyCode)
                        + ")";

        modString = "modifiers = " + modifiers;
        tmpString = KeyEvent.getKeyModifiersText(modifiers);
        if (tmpString.length() > 0) {
            modString += " (" + tmpString + ")";
        } else {
            modString += " (no modifiers)";
        }

        displayArea.append(s + newline
                           + "    " + charString + newline
                           + "    " + keyCodeString + newline
                           + "    " + modString + newline);
    
public voidinit()


       
        JButton button = new JButton("Clear");
        button.addActionListener(this);

        typingArea = new JTextField(20);
        typingArea.addKeyListener(this);

        displayArea = new JTextArea();
        displayArea.setEditable(false);
        JScrollPane scrollPane = new JScrollPane(displayArea);
        scrollPane.setPreferredSize(new Dimension(375, 125));

        JPanel contentPane = new JPanel();
        contentPane.setLayout(new BorderLayout());
        contentPane.add(typingArea, BorderLayout.NORTH);
        contentPane.add(scrollPane, BorderLayout.CENTER);
        contentPane.add(button, BorderLayout.SOUTH);
        setContentPane(contentPane);
    
public voidkeyPressed(java.awt.event.KeyEvent e)
Handle the key pressed event from the text field.

        displayInfo(e, "KEY PRESSED: ");
    
public voidkeyReleased(java.awt.event.KeyEvent e)
Handle the key released event from the text field.

        displayInfo(e, "KEY RELEASED: ");
    
public voidkeyTyped(java.awt.event.KeyEvent e)
Handle the key typed event from the text field.

        displayInfo(e, "KEY TYPED: ");