關鍵是要處理FontMetrics API。你可以做的最好的就是看這reference doc。
以下是演示此用法的示例代碼。它根據一系列字符在「Hello world」文本週圍繪製紅色和藍色線條。
的文字是一個JLabel裏面,但你可以在任何組件上適應paint方法(但你必須打電話graphics.drawChars
繪製文本。)
(代碼不是很漂亮,但是它演示FontMetrics對象的使用)
package com.example.swing;
import javax.swing.*;
import java.awt.*;
public class DemoFontMetrics {
public static void main(String[] args){
JFrame frame = new JFrame();
DecoratedLabel label = new DecoratedLabel("hello world !",new int[]{2,4}, new int[]{6,9});
JPanel textContainer = new JPanel(new FlowLayout());
textContainer.setBorder(BorderFactory.createEmptyBorder(5,5,5,5));
textContainer.add(label);
frame.getContentPane().add(textContainer);
frame.pack();
frame.setVisible(true);
}
private static class DecoratedLabel extends JLabel{
int startBlue;
int endBlue;
int startRed;
int endRed;
private DecoratedLabel(String text, int[] blueRange, int[] redRange) {
super(text);
startBlue = blueRange[0];
endBlue = blueRange[1];
startRed = redRange[0];
endRed = redRange[1];
}
@Override
public void paint(Graphics g) {
super.paint(g); //draw text
//set line with : 3
Stroke stroke = new BasicStroke(3f);
((Graphics2D)g).setStroke(stroke);
FontMetrics fm = g.getFontMetrics();
int h = fm.getHeight();
//compute blue line coordonate
fm.stringWidth(getText().substring(0,startBlue));
int x1 = fm.stringWidth(getText().substring(0, startBlue));
int x2 = fm.stringWidth(getText().substring(0, endBlue));
g.setColor(Color.BLUE);
g.drawLine(x1,0,x2,0);// draw blue line
//compute red line coordonates
int x3 = fm.stringWidth(getText().substring(0,startRed));
int x4 = fm.stringWidth(getText().substring(0, endRed));
g.setColor(Color.RED);
g.drawLine(x3,h-1,x4,h-1); // draw redline
}
}
}
是文本編輯?還是僅可見? – assylias 2013-02-25 10:13:42
文本只能查看,這是一個顯示畫布 – tarrasch 2013-02-25 12:09:57
您使用的是Swing嗎?如果是,請按照下面的答案中的建議查看Text-API。 Higlighter是一個選項。爲了更多的靈活性,將其中一個View類繼承下來。通過這個你可以添加特殊的角色裝飾。 API可以從模型(字符索引)轉換爲查看(圖形像素),反之亦然,可以使用任何字體。查看K.Topley的「Core Swing Advanced Programming」(ISBN 978-0130832924)。通過本書,我增強了JTextPane的隱藏文本,更多風格的裝飾和追蹤插入和刪除(cmp。MS Word)。欲瞭解更多信息,請發表評論。 – Claude 2013-03-01 19:49:52