停止 JTextPane 接收新的换行符

Stopping a JTextPane from receiving new line feeds

我希望我的 JTextPane 在用户按下 Enter 时具有某些功能,而不仅仅是更改行。现在我明白了如何实现我想要的功能,但我仍然无法取消按 Enter 的换行。我尝试了以下但它似乎不起作用,无论如何都会创建新行。

为了更好地了解我在这里要实现的目标,文本窗格应该包含特定的文件路径,所以我希望用户只能水平滚动而不是垂直添加新行。 JTextPane 组件是否适合这种用途?

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()));
            }
        }
    });

KeyListener 永远不是文本组件的合适解决方案。相反,您应该使用 DocumentFilter 来过滤掉您不想添加到基础 Document.

的内容

有关详细信息,请参阅 Implementing a Document Filter and DocumentFilter Examples

您还可以更改 insert-break 键绑定、更改行为或采取其他操作。

有关详细信息,请参阅

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?

我建议有更好的选择。

如果您只有一行文本,则只需使用 JTextField。要处理 Enter 键,您可以将 ActionListener 添加到文本字段。

如果您确实需要多行,那么我建议您可以使用 JList.