Search code examples
javaswingnetbeansjscrollpanejtextpane

JTextPane and keyboard input


I have an intresting problem.

I have a JTextPane inside of a JScrollPane that is poplated with styled text. The text is generated from an external device that is then passed to the StyledDocument (It looks like a terminal window). I use a key press listener to send each character im typing to the device and the character is then printed to the document from the external device. This is working wonderfully! I couldnt be happier!

EXCEPT!

When i press enter or back space the windows "boink" error sound is played. How can I override the JTextPane to not play the "boink" sound when I press enter or backspace in it?

Thanks!

Current Code for key listener

    addKeyListener(new KeyAdapter() {

        @Override
        public void keyTyped(KeyEvent ke) {
           //Absorb this action.
        }

        @Override
        public void keyReleased(KeyEvent ke) {
            //Absorb this action.
        }

        @Override
        public void keyPressed(KeyEvent evt) {

            char c = evt.getKeyChar();

            if (((byte) c) == 0x0A) {
                c = ((char) 0x0D);
            }

            try {
                rumIO.write(c);
            } catch (Exception e) {
            }
        }
    });

Code that fixed it!

addKeyListener(new KeyAdapter() {
        @Override
        public void keyPressed(KeyEvent evt) {
            InputMap inputMap = getInputMap();
            ActionMap actionMap = getActionMap();
            KeyStroke keyStroke = KeyStroke.getKeyStrokeForEvent(evt);
            inputMap.put(keyStroke, "doNothing");
            actionMap.put("doNothing", new AbstractAction() {

                @Override
                public void actionPerformed(ActionEvent ae) {
                    //Do Nothing
                }
            });


            char c = evt.getKeyChar();

            if (((byte) c) == 0x0A) {
                c = ((char) 0x0D);
            }

            try {
                rumIO.write(c);
            } catch (Exception e) {
            }
        }
    });

Solution

  • JTextPane uses Key Bindings. You may be able to override the default behavior as shown in the tutorial and in this example.