我正在研究一个JTextPane
,它几乎与stackoverflow上的标签输入字段一样工作。为此,我会在用户点击输入,制表符或空格时立即将文本转换为组件。当然,我不希望任何这些字符实际输入到文本窗格。我找到了这个解决方案,SSCCE:
import java.awt.Color;
import java.awt.event.ActionEvent;
import javax.swing.AbstractAction;
import javax.swing.BorderFactory;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JTextPane;
import javax.swing.KeyStroke;
import javax.swing.text.BadLocationException;
import javax.swing.text.Element;
import javax.swing.text.StyledDocument;
@SuppressWarnings("serial")
public class TagTextPane extends JTextPane {
public TagTextPane() {
this.getInputMap().put(KeyStroke.getKeyStroke("SPACE"), "finalizeTag");
this.getInputMap().put(KeyStroke.getKeyStroke("ENTER"), "finalizeTag");
this.getInputMap().put(KeyStroke.getKeyStroke("TAB"), "focusNext");
this.getActionMap().put("focusNext", new AbstractAction() {
@Override
public void actionPerformed(ActionEvent arg0) {
finalizeTag();
transferFocus();
}
});
this.getActionMap().put("finalizeTag", new AbstractAction() {
@Override
public void actionPerformed(ActionEvent e) {
finalizeTag();
}
});
}
private void finalizeTag() {
StyledDocument doc = (StyledDocument) getDocument();
Element element = doc.getCharacterElement(getCaretPosition() - 1);
int start = element.getStartOffset();
int len = element.getEndOffset() - start;
String tag = "";
try {
tag = this.getDocument().getText(start, len);
} catch (BadLocationException e) {
}
this.setSelectionStart(start);
this.setSelectionEnd(start + len);
JLabel label = new JLabel(tag);
label.setBorder(BorderFactory.createLineBorder(Color.BLACK));
this.insertComponent(label);
}
public static void main(String[] args) {
JFrame frame = new JFrame("TagTextPaneTest");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
TagTextPane tPane = new TagTextPane();
frame.setSize(400, 100);
frame.getContentPane().add(tPane);
frame.setVisible(true);
}
}
点击" tab"通常会导致插入标签字符并点击"输入"通常会导致换行,以及击中"空间"导致输入空格。奇怪的是,我的代码阻止了换行符和标签输入,但仍然允许在执行预期操作时正常输入空格。
答案 0 :(得分:2)
this.getInputMap().put(KeyStroke.getKeyStroke("SPACE"), "finalizeTag");
这是处理空格字符的keyPressed事件。
您想要处理空格字符的keyTyped事件:
this.getInputMap().put(KeyStroke.getKeyStroke(' '), "finalizeTag");