Search code examples
javaswingjtextpane

Stopping a JTextPane from receiving new line feeds


I want my JTextPane to have some functionality when the user presses Enter and not just change the line. Now I understand how to implement the functionality I want, but I still can't negate the line feed from pressing Enter. I have tried the following but it doesn't seem to work, the new line will be created anyway.

To give a better idea of what I'm trying to achieve here, the textpane is supposed to contain a certain filepath, so I want the user to be able to scroll only horizontaly and not add new lines verticaly. Is the JTextPane component suitable for this use?

locationPane = new JTextPane();
    locationPane.addKeyListener(new KeyAdapter() {
        @Override
        public void keyPressed(KeyEvent arg0) {
            if(arg0.getExtendedKeyCode() == KeyEvent.VK_ENTER){
                locationPane.setText(locationPane.getText().substring(0, locationPane.getText().length()));
            }
        }
    });

Solution

  • the textpane is supposed to contain a certain filepath, so I want the user to be able to scroll only horizontaly and not add new lines verticaly. Is the JTextPane component suitable for this use?

    I would suggest there are better options.

    If you only have a single line of text then just use a JTextField. To handle the Enter key you can add an ActionListener to the text field.

    If you do need multiple line then I would suggest you could use a JList.