Search code examples
javaswingawtkeylistener

KeyEvent in java does not work for alphabets or numerics but works fine for control, alt,up and down.but was not working for alphabets or numbers


i scanned the internet and couldnot find solution so, i was trying to integrate keypad shortcuts but later realised that the keyevent does not work properly which i could not find the reason for it works for others. but not for me .

here is the code:

import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;

public class KeyHandler implements KeyListener {

    NotePad note;
    public KeyHandler(NotePad note){
        this.note=note;
    }
    @Override
    public void keyTyped(KeyEvent e) {
            System.out.println("some key is pressed");
            if (e.getKeyCode() == KeyEvent.VK_S) {
                System.out.println("s is down");
                note.file.save();
            }
            else if (e.isControlDown()&&e.getKeyCode() == KeyEvent.VK_O)
                note.file.open();
            else if (e.isControlDown()&&e.getKeyCode() == KeyEvent.VK_Z)
                note.functionEdit.undo();
            else if (e.isControlDown()&&e.getKeyCode() == KeyEvent.VK_Y)
                note.functionEdit.redo();

    }

    @Override
    public void keyPressed(KeyEvent e) {

    }

    @Override
    public void keyReleased(KeyEvent e) {

    }
}

in the key typed method i first used it with control down it happens but not with other keys which are alpahbetical or numeric.

i was trying to implement the keypad shortcuts basically fire keypad input like ctrl+s and all and get them to perform certain function . but it does not work.

here is my implementation of keyListener.

public void createTextArea(){
        textArea=new JTextArea();
        textArea.addKeyListener(keyHandler);
        textArea.getDocument().addUndoableEditListener(
                new UndoableEditListener() {
                    @Override
                    public void undoableEditHappened(UndoableEditEvent e) {
                        um.addEdit(e.getEdit());
                    }
                }
        );
        scrollPane=new JScrollPane(textArea,JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
        scrollPane.setBorder(BorderFactory.createEmptyBorder());
        frame.add(scrollPane);

// frame.add(textArea); }


Solution

  • Generally speaking, you're better off making use of the key bindings API. This helps you decouple the functionality as well as control the level of focus under which the events are triggered.

    import java.awt.BorderLayout;
    import java.awt.EventQueue;
    import java.awt.event.ActionEvent;
    import java.awt.event.KeyEvent;
    import javax.swing.AbstractAction;
    import javax.swing.ActionMap;
    import javax.swing.InputMap;
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    import javax.swing.JScrollPane;
    import javax.swing.JTextArea;
    import javax.swing.KeyStroke;
    import javax.swing.event.UndoableEditEvent;
    import javax.swing.event.UndoableEditListener;
    import javax.swing.text.Document;
    import javax.swing.undo.UndoManager;
    
    public class Main {
    
        public static void main(String[] args) {
            new Main();
        }
    
        public Main() {
            EventQueue.invokeLater(new Runnable() {
                @Override
                public void run() {
                    JFrame frame = new JFrame("Test");
                    frame.add(new NotePad());
                    frame.pack();
                    frame.setLocationRelativeTo(null);
                    frame.setVisible(true);
                }
            });
        }
    
        public class NotePad extends JPanel {
    
            private UndoManager undoManager;
    
            public NotePad() {
                undoManager = new UndoManager();
                JTextArea textArea = new JTextArea(20, 10);
                Document doc = textArea.getDocument();
                doc.addUndoableEditListener(new UndoableEditListener() {
                    @Override
                    public void undoableEditHappened(UndoableEditEvent e) {
                        undoManager.addEdit(e.getEdit());
    
                    }
                });
                JScrollPane scrollPane = new JScrollPane(textArea);
                setLayout(new BorderLayout());
                add(scrollPane);
    
                InputMap inputMap = textArea.getInputMap(WHEN_FOCUSED);
                ActionMap actionMap = textArea.getActionMap();
    
                inputMap.put(KeyStroke.getKeyStroke(KeyEvent.VK_S, KeyEvent.CTRL_DOWN_MASK), "Save");
                inputMap.put(KeyStroke.getKeyStroke(KeyEvent.VK_O, KeyEvent.CTRL_DOWN_MASK), "Open");
                inputMap.put(KeyStroke.getKeyStroke(KeyEvent.VK_Z, KeyEvent.CTRL_DOWN_MASK), "Undo");
                inputMap.put(KeyStroke.getKeyStroke(KeyEvent.VK_Y, KeyEvent.CTRL_DOWN_MASK), "Redo");
    
                actionMap.put("Save", new AbstractAction() {
                    @Override
                    public void actionPerformed(ActionEvent e) {
                        System.out.println("Save");
                    }
                });
                actionMap.put("Open", new AbstractAction() {
                    @Override
                    public void actionPerformed(ActionEvent e) {
                        System.out.println("Open");
                    }
                });
                actionMap.put("Undo", new AbstractAction() {
                    @Override
                    public void actionPerformed(ActionEvent e) {
                        if (undoManager.canUndo()) {
                            System.out.println("Undo");
                            undoManager.undo();
                        }
                    }
                });
                actionMap.put("Redo", new AbstractAction() {
                    @Override
                    public void actionPerformed(ActionEvent e) {
                        if (undoManager.canRedo()) {
                            System.out.println("Redo");
                            undoManager.redo();
                        }
                    }
                });
            }
    
            protected void save() {
                System.out.println("Save");
            }
    
            protected void open() {
                System.out.println("Open");
            }
    
            protected void undo() {
                System.out.println("Undo");
            }
    
            protected void redo() {
                System.out.println("Redo");
            }
    
        }
    }