我有一个简单的文本编辑器,它把 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 字母将变为黑色。如何预防?一种解决方案是用 keyReleased 替换 keyTyped,但我不能这样做,因为我打算在按下时做一些事情ENTER,TAB我需要对它们使用消耗方法,这对 keyReleased 不起作用。