《Java2图形设计卷II:Swing》配套光盘源码
源代码在线查看: test.java
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.text.*;
public class Test extends JApplet {
public Test() {
Container contentPane = getContentPane();
JTextArea textArea = new JTextArea(
"File choosers, like option panes, are lightweight\n" +
"components that\n" +
"are meant to be placed ...");
textArea.setCaret(new BoxHighlightingCaret());
textArea.setFont(new Font("Dialog", Font.ITALIC, 24));
contentPane.add(new JScrollPane(textArea),
BorderLayout.CENTER);
}
}
class BoxHighlightingCaret extends DefaultCaret {
private static BoxHighlighterPainter painter =
new BoxHighlighterPainter(null);
public Highlighter.HighlightPainter getSelectionPainter(){
return painter;
}
static class BoxHighlighterPainter
extends DefaultHighlighter.DefaultHighlightPainter {
private Color color;
public BoxHighlighterPainter(Color color) {
super(color);
this.color = color;
}
public Shape paintLayer(Graphics g, int p0, int p1,
Shape shape, JTextComponent comp,
View view) {
Rectangle b = shape.getBounds();
try {
g.setColor(getColor(comp));
Rectangle r1 = comp.modelToView(p0);
Rectangle r2 = comp.modelToView(p1);
g.drawRect(r1.x, r1.y, // x,y
r2.x - r1.x - 1, // width
r1.height - 1); // height
}
catch(BadLocationException ex) {
ex.printStackTrace();
}
return b;
}
private Color getColor(JTextComponent comp) {
return color != null ? color :
comp.getSelectionColor();
}
}
}