Example usage for java.awt.event KeyListener KeyListener

List of usage examples for java.awt.event KeyListener KeyListener

Introduction

In this page you can find the example usage for java.awt.event KeyListener KeyListener.

Prototype

KeyListener

Source Link

Usage

From source file:KeyTest.java

public static void main(String args[]) {
    JFrame frame = new JFrame("Key Listener");
    Container contentPane = frame.getContentPane();

    KeyListener listener = new KeyListener() {
        public void keyPressed(KeyEvent e) {
            dumpInfo("Pressed", e);
        }// www  . j ava 2s. c o  m

        public void keyReleased(KeyEvent e) {
            dumpInfo("Released", e);
        }

        public void keyTyped(KeyEvent e) {
            dumpInfo("Typed", e);
        }

        private void dumpInfo(String s, KeyEvent e) {
            System.out.println(s);
            int code = e.getKeyCode();
            System.out.println("\tCode: " + KeyEvent.getKeyText(code));
            System.out.println("\tChar: " + e.getKeyChar());
            int mods = e.getModifiersEx();
            System.out.println("\tMods: " + KeyEvent.getModifiersExText(mods));
            System.out.println("\tLocation: " + location(e.getKeyLocation()));
            System.out.println("\tAction? " + e.isActionKey());
        }

        private String location(int location) {
            switch (location) {
            case KeyEvent.KEY_LOCATION_LEFT:
                return "Left";
            case KeyEvent.KEY_LOCATION_RIGHT:
                return "Right";
            case KeyEvent.KEY_LOCATION_NUMPAD:
                return "NumPad";
            case KeyEvent.KEY_LOCATION_STANDARD:
                return "Standard";
            case KeyEvent.KEY_LOCATION_UNKNOWN:
            default:
                return "Unknown";
            }
        }
    };

    JTextField text = new JTextField();
    text.addKeyListener(listener);
    contentPane.add(text, BorderLayout.NORTH);
    frame.pack();
    frame.show();
}

From source file:AddingActionCommandActionListenerSample.java

public static void main(String args[]) {
    JFrame frame = new JFrame("Default Example");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    JTextField textField = new JTextField();
    frame.add(textField, BorderLayout.NORTH);

    KeyListener keyListener = new KeyListener() {
        public void keyPressed(KeyEvent keyEvent) {
            printIt("Pressed", keyEvent);
        }/* w w  w. j a  v a2s .  com*/

        public void keyReleased(KeyEvent keyEvent) {
            printIt("Released", keyEvent);
        }

        public void keyTyped(KeyEvent keyEvent) {
            printIt("Typed", keyEvent);
        }

        private void printIt(String title, KeyEvent keyEvent) {
            int keyCode = keyEvent.getKeyCode();
            String keyText = KeyEvent.getKeyText(keyCode);
            System.out.println(title + " : " + keyText);
        }
    };
    textField.addKeyListener(keyListener);
    textField.addKeyListener(keyListener);

    frame.setSize(250, 150);
    frame.setVisible(true);
}

From source file:Main.java

public static void main(String[] args) {
    JFrame aWindow = new JFrame();

    aWindow.setBounds(50, 100, 300, 300);
    aWindow.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    JTextField typingArea = new JTextField(20);
    typingArea.addKeyListener(new KeyListener() {
        /** Handle the key typed event from the text field. */
        public void keyTyped(KeyEvent e) {
            displayInfo(e, "KEY TYPED: ");
        }/*w  ww  . jav  a2s . com*/

        /** Handle the key pressed event from the text field. */
        public void keyPressed(KeyEvent e) {
            displayInfo(e, "KEY PRESSED: ");
        }

        /** Handle the key released event from the text field. */
        public void keyReleased(KeyEvent e) {
            displayInfo(e, "KEY RELEASED: ");
        }

        protected void displayInfo(KeyEvent e, String s) {
            String keyString, modString, tmpString, actionString, locationString;
            int id = e.getID();
            if (id == KeyEvent.KEY_TYPED) {
                char c = e.getKeyChar();
                keyString = "key character = '" + c + "'";
            } else {
                int keyCode = e.getKeyCode();
                keyString = "key code = " + keyCode + " (" + KeyEvent.getKeyText(keyCode) + ")";
            }

            int modifiers = e.getModifiersEx();
            modString = "modifiers = " + modifiers;
            tmpString = KeyEvent.getModifiersExText(modifiers);
            if (tmpString.length() > 0) {
                modString += " (" + tmpString + ")";
            } else {
                modString += " (no modifiers)";
            }

            actionString = "action key? ";
            if (e.isActionKey()) {
                actionString += "YES";
            } else {
                actionString += "NO";
            }

            locationString = "key location: ";
            int location = e.getKeyLocation();
            if (location == KeyEvent.KEY_LOCATION_STANDARD) {
                locationString += "standard";
            } else if (location == KeyEvent.KEY_LOCATION_LEFT) {
                locationString += "left";
            } else if (location == KeyEvent.KEY_LOCATION_RIGHT) {
                locationString += "right";
            } else if (location == KeyEvent.KEY_LOCATION_NUMPAD) {
                locationString += "numpad";
            } else { // (location == KeyEvent.KEY_LOCATION_UNKNOWN)
                locationString += "unknown";
            }

            System.out.println(keyString);
            System.out.println(modString);
            System.out.println(actionString);
            System.out.println(locationString);
        }

    });
    aWindow.add(typingArea);
    aWindow.setVisible(true);
}

From source file:MainClass.java

public static void main(String args[]) throws Exception {
    JFrame frame = new JFrame();
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    JTextField nameTextField = new JTextField();
    frame.add(nameTextField, BorderLayout.NORTH);

    KeyListener keyListener = new KeyListener() {
        public void keyPressed(KeyEvent keyEvent) {
            printIt("Pressed", keyEvent);
        }//from  w  w  w  .j a  v a2s .  c  o m

        public void keyReleased(KeyEvent keyEvent) {
            printIt("Released", keyEvent);
        }

        public void keyTyped(KeyEvent keyEvent) {
            printIt("Typed", keyEvent);
        }

        private void printIt(String title, KeyEvent keyEvent) {
            int keyCode = keyEvent.getKeyCode();
            String keyText = KeyEvent.getKeyText(keyCode);
            System.out.println(title + " : " + keyText + " / " + keyEvent.getKeyChar());
        }
    };
    nameTextField.addKeyListener(keyListener);

    frame.setSize(250, 100);
    frame.setVisible(true);
}

From source file:JTextFieldSample.java

public static void main(String args[]) {
    String title = (args.length == 0 ? "TextField Listener Example" : args[0]);
    JFrame frame = new JFrame(title);
    Container content = frame.getContentPane();

    JPanel namePanel = new JPanel(new BorderLayout());
    JLabel nameLabel = new JLabel("Name: ");
    nameLabel.setDisplayedMnemonic(KeyEvent.VK_N);
    JTextField nameTextField = new JTextField();
    nameLabel.setLabelFor(nameTextField);
    namePanel.add(nameLabel, BorderLayout.WEST);
    namePanel.add(nameTextField, BorderLayout.CENTER);
    content.add(namePanel, BorderLayout.NORTH);

    JPanel cityPanel = new JPanel(new BorderLayout());
    JLabel cityLabel = new JLabel("City: ");
    cityLabel.setDisplayedMnemonic(KeyEvent.VK_C);
    JTextField cityTextField = new JTextField();
    cityLabel.setLabelFor(cityTextField);
    cityPanel.add(cityLabel, BorderLayout.WEST);
    cityPanel.add(cityTextField, BorderLayout.CENTER);
    content.add(cityPanel, BorderLayout.SOUTH);

    ActionListener actionListener = new ActionListener() {
        public void actionPerformed(ActionEvent actionEvent) {
            System.out.println("Command: " + actionEvent.getActionCommand());
        }/*from  ww  w.  ja  v a2 s.co  m*/
    };
    nameTextField.setActionCommand("Yo");
    nameTextField.addActionListener(actionListener);
    cityTextField.addActionListener(actionListener);

    KeyListener keyListener = new KeyListener() {
        public void keyPressed(KeyEvent keyEvent) {
            printIt("Pressed", keyEvent);
        }

        public void keyReleased(KeyEvent keyEvent) {
            printIt("Released", keyEvent);
        }

        public void keyTyped(KeyEvent keyEvent) {
            printIt("Typed", keyEvent);
        }

        private void printIt(String title, KeyEvent keyEvent) {
            int keyCode = keyEvent.getKeyCode();
            String keyText = KeyEvent.getKeyText(keyCode);
            System.out.println(title + " : " + keyText + " / " + keyEvent.getKeyChar());
        }
    };
    nameTextField.addKeyListener(keyListener);
    cityTextField.addKeyListener(keyListener);

    InputVerifier verifier = new InputVerifier() {
        public boolean verify(JComponent input) {
            final JTextComponent source = (JTextComponent) input;
            String text = source.getText();
            if ((text.length() != 0) && !(text.equals("Exit"))) {
                Runnable runnable = new Runnable() {
                    public void run() {
                        JOptionPane.showMessageDialog(source, "Can't leave.", "Error Dialog",
                                JOptionPane.ERROR_MESSAGE);
                    }
                };
                SwingUtilities.invokeLater(runnable);
                return false;
            } else {
                return true;
            }
        }
    };
    nameTextField.setInputVerifier(verifier);
    cityTextField.setInputVerifier(verifier);

    DocumentListener documentListener = new DocumentListener() {
        public void changedUpdate(DocumentEvent documentEvent) {
            printIt(documentEvent);
        }

        public void insertUpdate(DocumentEvent documentEvent) {
            printIt(documentEvent);
        }

        public void removeUpdate(DocumentEvent documentEvent) {
            printIt(documentEvent);
        }

        private void printIt(DocumentEvent documentEvent) {
            DocumentEvent.EventType type = documentEvent.getType();
            String typeString = null;
            if (type.equals(DocumentEvent.EventType.CHANGE)) {
                typeString = "Change";
            } else if (type.equals(DocumentEvent.EventType.INSERT)) {
                typeString = "Insert";
            } else if (type.equals(DocumentEvent.EventType.REMOVE)) {
                typeString = "Remove";
            }
            System.out.print("Type  :   " + typeString + " / ");
            Document source = documentEvent.getDocument();
            int length = source.getLength();
            try {
                System.out.println("Contents: " + source.getText(0, length));
            } catch (BadLocationException badLocationException) {
                System.out.println("Contents: Unknown");
            }
        }
    };
    nameTextField.getDocument().addDocumentListener(documentListener);
    cityTextField.getDocument().addDocumentListener(documentListener);

    frame.setSize(250, 150);
    frame.setVisible(true);
}

From source file:TextLayoutWithCarets.java

public TextLayoutWithCarets() {
    addKeyListener(new KeyListener() {
        public void keyPressed(KeyEvent ke) {
            if (ke.getKeyCode() == KeyEvent.VK_RIGHT) {
                mHit = mLayout.getNextRightHit(mHit.getInsertionIndex());
                if (mHit == null)
                    mHit = mLayout.getNextLeftHit(1);
                repaint();//from  ww  w .j ava 2  s.c om
            } else if (ke.getKeyCode() == KeyEvent.VK_LEFT) {
                mHit = mLayout.getNextLeftHit(mHit.getInsertionIndex());
                if (mHit == null)
                    mHit = mLayout.getNextRightHit(mLayout.getCharacterCount() - 1);
                repaint();
            }
        }

        public void keyTyped(KeyEvent arg0) {
            // TODO Auto-generated method stub

        }

        public void keyReleased(KeyEvent arg0) {
            // TODO Auto-generated method stub

        }
    });

}

From source file:org.nekorp.workflow.desktop.view.resource.imp.MonedaTextField.java

public MonedaTextField() {
    super();// ww  w .  j a  v a2 s . c o  m
    this.addKeyListener(new KeyListener() {

        @Override
        public void keyTyped(KeyEvent e) {
            char car = e.getKeyChar();
            if (car != '.') {
                if ((car < '0' || car > '9')) {
                    e.consume();
                }
            } else {
                if (StringUtils.contains(getText(), '.')) {
                    e.consume();
                }
            }
        }

        @Override
        public void keyPressed(KeyEvent e) {
        }

        @Override
        public void keyReleased(KeyEvent e) {
        }
    });
}

From source file:org.nekorp.workflow.desktop.view.binding.MonedaBindableJTextField.java

public MonedaBindableJTextField() {
    super();//  ww w  .  j a v  a2s.  c o m
    ignore = new LinkedList<>();
    this.addKeyListener(new KeyListener() {

        @Override
        public void keyTyped(KeyEvent e) {
            char car = e.getKeyChar();
            if (car != '.') {
                if ((car < '0' || car > '9')) {
                    e.consume();
                }
            } else {
                if (StringUtils.contains(getText(), '.')) {
                    e.consume();
                }
            }
        }

        @Override
        public void keyPressed(KeyEvent e) {
        }

        @Override
        public void keyReleased(KeyEvent e) {
        }
    });
}

From source file:com.mindcognition.mindraider.ui.swing.dialogs.UpdateOutlineJDialog.java

public UpdateOutlineJDialog(ResourceDescriptor notebookDescriptor) {
    super("Rename or Change Outline Labels", "Update");

    final KeyListener keyListener = new KeyListener() {
        public void keyPressed(KeyEvent keyEvent) {
            if (keyEvent.getKeyCode() == KeyEvent.VK_ENTER) {
                updateNotebook();/*from w  w w . j ava2  s .co m*/
            }
            if (keyEvent.getKeyCode() == KeyEvent.VK_ESCAPE) {
                dispose();
            }
        }

        public void keyReleased(KeyEvent e) {
        }

        public void keyTyped(KeyEvent e) {
        }
    };

    this.oldNotebookDescriptor = notebookDescriptor;
    outlineTitle.setText(notebookDescriptor.getLabel());
    outlineTitle.addKeyListener(keyListener);
    outlineUri.setText(notebookDescriptor.getUri());
    outlineNcName.setText(notebookDescriptor.getUri().substring(notebookDescriptor.getUri().indexOf('#') + 1));

    // initialize categories
    ResourceDescriptor[] notebookFolders = MindRaider.labelCustodian
            .getNotebookFolders(notebookDescriptor.getUri());
    outlineLabels.setText("");
    outlineLabels.addKeyListener(keyListener);
    if (notebookFolders != null && notebookFolders.length > 0) {
        StringBuffer labelBuffer = new StringBuffer();
        for (ResourceDescriptor label : notebookFolders) {
            oldLabels.put(label.getLabel(), label);
            labelBuffer.append(label.getLabel());
            labelBuffer.append(", ");
        }
        if (labelBuffer.length() > 0) {
            outlineLabels.setText(labelBuffer.toString().substring(0, labelBuffer.length() - 2));
        }
    }

    // buttons
    doButton.addActionListener(UpdateNotebookActionListener());
    cancelButton.addActionListener(AbstractNotebookCancelActionListener());

    // show
    pack();
    Gfx.centerAndShowWindow(this);
}

From source file:richtercloud.reflection.form.builder.typehandler.StringTypeHandler.java

@Override
public Pair<JComponent, ComponentHandler<?>> handle(Type type, String fieldValue, String fieldName,
        Class<?> declaringClass, final FieldUpdateListener<FieldUpdateEvent<String>> updateListener,
        ReflectionFormBuilder reflectionFormBuilder)
        throws IllegalArgumentException, IllegalAccessException, FieldHandlingException {
    final JTextField retValue = new JTextField(fieldValue);
    retValue.addKeyListener(new KeyListener() {

        @Override//from   w  w w  . ja va2  s .  c o m
        public void keyTyped(KeyEvent e) {
            updateListener.onUpdate(new FieldUpdateEvent<>(retValue.getText()));
        }

        @Override
        public void keyPressed(KeyEvent e) {
            updateListener.onUpdate(new FieldUpdateEvent<>(retValue.getText()));
        }

        @Override
        public void keyReleased(KeyEvent e) {
            updateListener.onUpdate(new FieldUpdateEvent<>(retValue.getText()));
        }
    }); //action listener doesn't register text change events with keyboard
    return new ImmutablePair<JComponent, ComponentHandler<?>>(retValue, this);
}