3

我想用自定义字体实现一个 JTextField。我知道我们不能在 JTextField 中做到这一点。现在我正在使用 JtextPane 我有一个问题如何确保当用户按 Enter 时克拉不会转到下一行。?

4

3 回答 3

3

添加一个 DocumentFilter 并防止在那里插入“\n”字符。

于 2011-05-19T11:43:00.033 回答
2
class DocFilter extends DocumentFilter{

        public void insertString(FilterBypass fb, int offset, String string, AttributeSet attr) throws BadLocationException {
            fb.insertString(offset, string.replaceAll("\\n", ""), attr); 
        }

       public void replace(FilterBypass fb, int offset, int length, String string, AttributeSet attr) throws BadLocationException {
            fb.insertString(offset, string.replaceAll("\\n", ""), attr); 
        }
    }

此代码运行良好

于 2011-05-19T14:30:47.893 回答
0

将 keyListener 添加到 jTextPane 并跟踪keyPressed(e)方法中的输入键。输入的键码是 10。


尝试这样的键绑定:

JTextPane pane = new JTextPane();
// Get KeyStroke for enter key
KeyStroke enterKey = KeyStroke.getKeyStroke(KeyEvent.VK_ENTER,0);
// Override enter for a pane
String actionKey = "none";
InputMap map = pane.getInputMap();
map.put(enterKey, actionKey);

这将覆盖 textPane 的 enter 键行为,并且如果用户按下 enter,则不会执行任何操作。

于 2011-05-19T11:32:06.887 回答