我試圖創建一個覆蓋光標。除了當我點擊較早的一行時插入符號消失時,我已經得到了它,然後當我點擊「輸入」換行時,它再次出現。當我創建新行時,無法看到Overwrinting光標
我應該在我的代碼中更改哪些內容來解決此問題?
這裏是我的插入級:
public class Mycaret extends DefaultCaret {
protected static final int MIN_WIDTH = 8;
protected DefaultCaret dc = null;
JTextComponent com = null;
public Mycaret(int rate, DefaultCaret dc) {
this.dc = dc;
super.setBlinkRate(rate);
}
protected synchronized void damage(Rectangle r) {
if (r != null) {
try {
JTextComponent comp = getComponent();
TextUI mapper = comp.getUI();
char dotChar = 0;
if(comp.getText().length()>0){
dotChar = comp.getText().charAt(comp.getText().length()-1);
}
this.com = comp;
Rectangle r2 = mapper.modelToView(comp, getDot() + 1);
int width = r2.x - r.x;
if (width == 0) {
width = MIN_WIDTH;
}
comp.repaint(r.x, r.y, width, r.height);
this.x = r.x;
this.y = r.y;
this.width = width;
this.height = r.height;
}
catch (BadLocationException e) {
}
}
}
public void paint(Graphics g) {
char dotChar;
if (isVisible()) {
try {
JTextComponent comp = getComponent();
TextUI mapper = comp.getUI();
Rectangle r1 = mapper.modelToView(comp, getDot());
Rectangle r2 = mapper.modelToView(comp, getDot() + 1);
g = g.create();
g.setColor(comp.getForeground());
g.setXORMode(comp.getBackground());
int width = r2.x - r1.x;
dotChar = comp.getText(getDot(), 1).charAt(0);
if (width == 0 ) {
width = MIN_WIDTH;
}
g.fillRect(r1.x, r1.y, width, r1.height);
g.dispose();
} catch (BadLocationException e) {
}
}
}
}
這是一個示例:
public class MyFrameSample extends JFrame {
DefaultCaret caret=null;
public MyFrameSample() {
JTextArea text = new JTextArea(10,20);
caret = new DefaultCaret();
text.setCaret(new Mycaret(500, caret));
add(text);
pack();
setVisible(true);
}
public static void main(String[] args) {
new MyFrameSample();
}
}
我編輯了我的問題 – user3232446
是的,這應該是我的問題:) – user3232446
我想我在這方面有領先。我建議這是因爲'modelToView(comp,getDot()+ 1)'中的陷阱而發生的。請注意,胡蘿蔔只會在非空行的末尾停止渲染*,而不是最後一行*。這些位置正好在'\ n'坐在文檔中的位置。由於胡蘿蔔需要'getDot()'和'getDot()+ 1'之間的寬度,並且'\ n'不可見,所以你會看到一個看不見的胡蘿蔔。 – user1803551