Τετάρτη, 26 Μαΐου 2010

How to customize the caret at Java Swing components

Back to the DOS Age caret was a rectangle having same width as any character. I am not sure why that was happening. Maybe to make it more obvious that the system is waiting for input from the user! Nowadays caret is more discretionary, by default it is a thin vertical line that blinks. This default representation of caret is not enough for all users, there are still user who want a large caret in order to find easier where it blinks! Java Swing API has a simple solution even for this kind of users.
Each JTextComponent has a method named "setCaret", this method is used to set a custom caret. Implementing a absolutely custom Caret is a very hard job, but you can simply extend DefaultCaret! For instance if you want a wider caret use the following code:

myTextField.setCaret(new DefaultCaret() {
{
setBlinkRate(500); // half a second
}
@Override
protected synchronized void damage(Rectangle r) {
if (r == null) {
return;
}
// give values to x,y,width,height (inherited from java.awt.Rectangle)
x = r.x;
y = r.y;
width = 5;
height = getComponent().getHeight();
repaint(); // calls getComponent().repaint(x, y, width, height)
}

@Override
public void paint(Graphics g) {
JTextComponent comp = getComponent();
if (comp == null) {
return;
}

int dot = getDot();
Rectangle r = null;
try {
r = comp.modelToView(dot);
} catch (BadLocationException e) {
return;
}
if (r == null) {
return;
}


if (isVisible()) {
g.setColor(comp.getCaretColor());
g.fill3DRect(r.x, r.y, width, height, true);
}
}
});

Notes:
What is caret navigation?
(source wikipedia)
In computing, caret navigation is a kind of keyboard navigation where a caret (also known as "text cursor", "text insertion cursor", or "text selection cursor") is used to navigate within a text document. It is a fundamental feature for applications that deal with text, for example text editors (the most famous examples: Emacs and Vim), word processors and desktop publishing programs.

How does caret look like?



Δημοσίευση σχολίου

Gadget

Αυτό το περιεχόμενο δεν είναι ακόμα διαθέσιμο μέσω κρυπτογραφημένων συνδέσεων.

LinkWithin

Blog Widget by LinkWithin

Mobile edition