如何在 JTextArea 或 JTextPane 中显示多个插入符

Fre*_*ind 4 java swing jtextpane caret jtextarea

我想使用 JTextArea 或 JTextPane 作为代码更改播放器,并将代码更改和插入符号移动记录在文本文件中。但问题是,它是从支持多选的编辑器中记录的,因此一次会有多个插入符位置。

是否可以在 JTextArea 或 JTextPane 中显示多个插入符?

我尝试使用 JTextPane 并将代码呈现为 HTML,并<span class='caret'>|</span>在代码中插入一些来表示插入符号,它可以工作,但假插入符号占用空间,因此当插入符号更改时,正常字符不会固定在屏幕上。

Sta*_*avL 5

像这样?

import javax.swing.*;
import javax.swing.plaf.TextUI;
import javax.swing.text.BadLocationException;
import javax.swing.text.DefaultCaret;
import java.awt.*;
import java.util.Arrays;
import java.util.List;

public class Main {

    public static void main(String[] args) {
        JFrame fr=new JFrame("Multi caret test");
        JTextArea ta=new JTextArea("Test test test", 20, 40);
        MultiCaret c=new MultiCaret();
        c.setBlinkRate(500);
        c.setAdditionalDots(Arrays.asList(2,4,7));
        ta.setCaret(c);
        fr.add(ta);

        fr.pack();
        fr.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        fr.setLocationRelativeTo(null);
        fr.setVisible(true);
    }
}

class MultiCaret extends DefaultCaret {
    private List<Integer> additionalDots;

    public void setAdditionalDots(List<Integer> additionalDots) {
        this.additionalDots = additionalDots;
    }

    public void paint(Graphics g) {
        super.paint(g);

        try {
            TextUI mapper = getComponent().getUI();
            for (Integer addDot : additionalDots) {
                Rectangle r = mapper.modelToView(getComponent(), addDot, getDotBias());

                if(isVisible()) {
                    g.setColor(getComponent().getCaretColor());
                    int paintWidth = 1;
                    r.x -= paintWidth >> 1;
                    g.fillRect(r.x, r.y, paintWidth, r.height);
                }
                else {
                    getComponent().repaint(r);
                }
            }
        } catch (BadLocationException e) {
            e.printStackTrace();
        }
    }

}
Run Code Online (Sandbox Code Playgroud)