gpt4 book ai didi

java - JTextPane 为所有内容而不是几个字符着色

转载 作者:行者123 更新时间:2023-12-04 05:08:38 31 4
gpt4 key购买 nike

所以我想写一个简单的编辑器。我想将所有字符之间的所有字符都涂成灰色“字符。它的片段是:

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
}
}
}

}

当 "出现时,它会将字符涂成灰色,但它会在第一个 "符号之后涂上所有字符。这段代码有什么问题? 编辑:给你,这是完整的代码。

最佳答案

setCharacterAttributes() 方法中的第二个参数是长度,而不是结束索引。这是你的问题。

        boolean isString = false;
char[] text = code.toCharArray();
for (int i = 0; i < text.length; i++) {
if (text[i] == '\"') {
isString = !isString;
if(!isString) {
document.setCharacterAttributes(i, 1, attributes, true);
}
}
if (isString) {
document.setCharacterAttributes(i, 1, attributes, true);
}
}

原始问题较短,只有几行代码,但 mKorbel 是正确的:

... in this case (it's a) job for DocumentFilter, never to use KeyListener for JTextComponent.



你应该检查一下,它可能会有所帮助: How to Write a Document Listener

关于java - JTextPane 为所有内容而不是几个字符着色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15177833/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com