开发者

JtextPane of one Line

I want to implement a JTextField with custom fonts.I came to know that we cannot do that in JTextField. Now I am using JtextPane i 开发者_如何转开发have a problem How to make sure the carat doesn't go to the next line when the user press enter. ?


Add a DocumentFilter and prevent inserting "\n" chars there.


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

This code works well


Add keyListener to jTextPane and track for enter key in keyPressed(e) method. Key code for enter is 10.


Try key bindings like this:

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

This will override the enter key behavior for textPane and does not do anything if user presses enter.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜