按下回车键时添加字符(或字符串)(在 JTextPane 中)
Add a character (or a String) when enter is pressed (in a JTextPane)
所以我有一个 JTextPane 并且我添加了一个 keyListener,这样我就可以知道是否按下了输入按钮 :
JTextPane textPane = new JTextPane();
textPane.addKeyListener(new KeyListener() {
@Override
public void keyTyped(KeyEvent e) {
}
@Override
public void keyPressed(KeyEvent e) {
if(e.getKeyCode() == KeyEvent.VK_ENTER){
// add there the code to add a character to the textPane!
}
}
@Override
public void keyReleased(KeyEvent e) {
}
});
但是现在我很困惑,如何添加一个字符'}'到textPane?
(不是任何地方,就在光标位置之后,到下面...)
正如@HovercraftFullOfEels 在上面的评论中所建议的,不要使用 KeyListener
来收听 enter 键,而是使用 KeyBindings or a DocumentListener. Here's an 来自使用键绑定的气垫船,虽然它没有 JTextPane
但你可以从那里得到一般的想法。
要在插入符位置附加文本,您可以尝试 JTextPane#replaceSelection(String)
文档中的内容:
Replaces the currently selected content with new content represented by the given string. If there is no selection this amounts to an insert of the given text. If there is no replacement text this amounts to a removal of the current selection. The replacement text will have the attributes currently defined for input at the point of insertion. If the document is not editable, beep and return.
所以我有一个 JTextPane 并且我添加了一个 keyListener,这样我就可以知道是否按下了输入按钮 :
JTextPane textPane = new JTextPane();
textPane.addKeyListener(new KeyListener() {
@Override
public void keyTyped(KeyEvent e) {
}
@Override
public void keyPressed(KeyEvent e) {
if(e.getKeyCode() == KeyEvent.VK_ENTER){
// add there the code to add a character to the textPane!
}
}
@Override
public void keyReleased(KeyEvent e) {
}
});
但是现在我很困惑,如何添加一个字符'}'到textPane?
(不是任何地方,就在光标位置之后,到下面...)
正如@HovercraftFullOfEels 在上面的评论中所建议的,不要使用 KeyListener
来收听 enter 键,而是使用 KeyBindings or a DocumentListener. Here's an JTextPane
但你可以从那里得到一般的想法。
要在插入符位置附加文本,您可以尝试 JTextPane#replaceSelection(String)
文档中的内容:
Replaces the currently selected content with new content represented by the given string. If there is no selection this amounts to an insert of the given text. If there is no replacement text this amounts to a removal of the current selection. The replacement text will have the attributes currently defined for input at the point of insertion. If the document is not editable, beep and return.