做Eclipse插件开发中,有时候需要高亮或者突出一个label中某个字,方式如下:
package com.devin.eclipse.TextStyleDemo;
import org.eclipse.swt.SWT;
import org.eclipse.swt.graphics.Color;
import org.eclipse.swt.graphics.Font;
import org.eclipse.swt.graphics.FontData;
import org.eclipse.swt.graphics.TextLayout;
import org.eclipse.swt.graphics.TextStyle;
import org.eclipse.swt.layout.FillLayout;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Listener;
import org.eclipse.swt.widgets.Shell;
public class ColorfullFontInLabel {
public static void main(String[] args) {
final Display display = new Display();
final Shell shell = new Shell(display);
shell.setLayout(new FillLayout());
shell.setSize(200, 100);
Label label = new Label(shell, SWT.NONE);
// label.setText("Blue and bold");
// Set color text style
Color blue = display.getSystemColor(SWT.COLOR_BLUE);
Font boldFont = new Font(label.getDisplay(), new FontData( "Corbel", 16, SWT.BOLD ) );
final TextLayout layout = new TextLayout(display);
layout.setText("Blue and bold");
final TextStyle style1 = new TextStyle(display.getSystemFont(), blue, null);
final TextStyle style2 = new TextStyle(boldFont, null, null);
label.addListener(SWT.Paint, new Listener() {
@Override
public void handleEvent(Event event) {
layout.setStyle(style1, 0, 3);
layout.setStyle(style2, 9, 12);
layout.draw(event.gc, event.x, event.y);
}
});
// shell.pack();
shell.open();
while (!shell.isDisposed()) {
if (!display.readAndDispatch()) {
display.sleep();
}
}
display.dispose();
}
}
运行结果: