SWT / JFace displays different fonts and font colors in the same Label component

When doing Eclipse plug-in development, sometimes you need to highlight or highlight a word in a label, as follows:

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();

	}
}


operation result:
Insert picture description here

Published 89 original articles · praised 83 · views 3511

Guess you like

Origin blog.csdn.net/devin_xin/article/details/105252534