所以我尝试编写简单的编辑器。我想将所有字符之间的所有字符都涂成灰色。字符之间的片段是:
class MainPanel extends JPanel {
private int WIDTH = 800;
private int HEIGHT = 500;
private JTextPane codePane = new JTextPane(); //Pole, w które wpisywany jest kod
private JLabel codeLabel = new JLabel("JNotepad");
private StyledDocument doc = codePane.getStyledDocument();
private final String[] keywords; //Słowa kluczowe
private final Map<String, String> shortcuts = new HashMap<>(); //syso -> System.out.println() itp.
MainPanel() {
setPreferredSize(new Dimension(WIDTH, HEIGHT));
setLayout(new BorderLayout());
//Dodanie głównego pola w polu przewijanym
JScrollPane scroll = new JScrollPane(codePane);
add(scroll, BorderLayout.CENTER);
add(codeLabel, BorderLayout.SOUTH);
codePane.addKeyListener(new KeyHandler());
codePane.setFont(new Font("Monospaced", Font.PLAIN, 15));
//Załadowanie słów kluczowych
Scanner in = new Scanner(getClass().getResourceAsStream("res/keywords.txt"));
List<String> words = new LinkedList<>();
while (in.hasNext()) {
words.add(in.nextLine());
}
keywords = words.toArray(new String[words.size()]);
in.close();
}
private class KeyHandler extends KeyAdapter {
@Override
public void keyReleased(KeyEvent ev) {
highlight();
}
private void highlight() {
String code = codePane.getText();
//Zmiana koloru słów kluczowych
String[] words = code.replaceAll("\\(|\\)|\\{|\\}|\\[|\\]", " ").split("\\s");
int lastIndex = 0;
for (int a = 0; a < words.length; a++) {
SimpleAttributeSet set = new SimpleAttributeSet();
if (Arrays.asList(keywords).contains(words[a])) {
StyleConstants.setForeground(set, Color.BLUE);
}
doc.setCharacterAttributes(lastIndex, lastIndex + words[a].length(), set, true);
//Zwiekszenie ostatniego indexu
lastIndex += words[a].length() + 1; //+1 bo jeszcze spacja
}
}
}
}
当 " 出现时,它会将字符涂成灰色,但它会在第一个 " 符号之后绘制所有字符。这段代码有什么问题?编辑:给你,这是完整的代码。