我有一个简单的文本编辑器,可以将 JAVA 关键字设置为蓝色。这是代码:
class MainPanel extends JPanel {
private int WIDTH = 800;
private int HEIGHT = 500;
private JFrame frame;
private JTextPane codePane = new JTextPane();
private StyledDocument doc = codePane.getStyledDocument();
MainPanel(JFrame frame) {
this.frame = frame;
setPreferredSize(new Dimension(WIDTH, HEIGHT));
setLayout(new BorderLayout());
JScrollPane scroll = new JScrollPane(codePane);
add(scroll, BorderLayout.CENTER);
codePane.addKeyListener(new MainPanel.KeyHandler());
codePane.setFont(new Font("Monospaced", Font.PLAIN, 15));
//Loading key words..
//...
}
private class KeyHandler extends KeyAdapter {
@Override
public void keyTyped(KeyEvent ev) {
String code = codePane.getText();
SimpleAttributeSet set = new SimpleAttributeSet();
StyleConstants.setForeground(set, Color.BLACK);
doc.setCharacterAttributes(0, code.length(), set, true);
//Change keywords color
int lastIndex = 0;
for (int a = 0; a < words.length; a++) {
set = new SimpleAttributeSet();
if (Arrays.asList(keywords).contains(words[a])) {
StyleConstants.setForeground(set, Color.BLUE);
}
doc.setCharacterAttributes(lastIndex, words[a].length(), set, true);
lastIndex += words[a].length() + 1; //+1 bo jeszcze spacja po słowie
}
}
}
}
我的问题是文本突出显示(在 keyTyped 事件中)发生在将字母放入文本区域之前。因此,当我输入:“int”时,它不会将其着色为蓝色,但是当我再输入一个字符“int”时,它将被着色为蓝色,例如。 “intR”、“int”将被着色为蓝色,R 字母将被着色为黑色。如何预防呢?一种解决方案是将 keyTyped 替换为 keyReleased 但我不能这样做,因为我计划在按下 ENTER 和 TAB 时执行一些操作,并且我需要在它们不适用于 keyReleased。
最佳答案
One solution is to replace keyTyped with keyReleased
不要使用 KeyListener。您应该使用 DocumentListener。请参阅 Swing 教程中关于 How to Write a Document Listener 的部分了解更多信息。
Im planning to do some things while ENTER and TAB
您应该使用按键绑定(bind)。查看上面链接中的目录,您将找到关于如何使用键绑定(bind)
的部分。
关于java - JTextPane 中的字母在延迟后着色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15204295/