Main Tutorials

SWT – Label Example

What is Label?

The Label is the most common and frequent use widget, it’s display static information such as String or Image, and no user input involve.

How to create a Label widget?

This code snippet will create a label at position x=100, y=50, width = 300, height = 30, and display “I am Label” text.


Label label = new Label(shell, SWT.BORDER);
label.setSize(300,30);
label.setLocation(100, 50);
label.setText("I am Label");

How to create a separator with Label?

Sometime Label is use to display as a separator between component. Here is how to implement it.

This code snippet will create a Label and draw a horizontal line as separator inside it.


Label shadow_sep_h = new Label(shell, SWT.SEPARATOR | SWT.SHADOW_OUT | SWT.HORIZONTAL);
shadow_sep_h.setBounds(50,80,100,50);

This code snippet will create a Label and draw a vertical line as separator inside it.


Label shadow_sep_v = new Label(shell, SWT.SEPARATOR | SWT.SHADOW_IN | SWT.VERTICAL);
shadow_sep_v.setBounds(50,100,5,100);

Here is the full SWT Label source code.

import org.eclipse.swt.SWT;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Shell;
 
public class SWTLabel {
 
public static void main (String [] args) {
	Display display = new Display ();
	Shell shell = new Shell(display);
 
	Label label = new Label(shell, SWT.BORDER);
	label.setSize(100,30);
	label.setLocation(50, 50);
	label.setText("I am a Label");
	
	Label shadow_sep_h = new Label(shell, SWT.SEPARATOR | SWT.SHADOW_OUT | SWT.HORIZONTAL);
	shadow_sep_h.setBounds(50,80,100,50);
	
	Label shadow_sep_v = new Label(shell, SWT.SEPARATOR | SWT.SHADOW_IN | SWT.VERTICAL);
	shadow_sep_v.setBounds(50,100,5,100);
	
	
	shell.setSize(300,300);
	shell.open ();
	while (!shell.isDisposed ()) {
		if (!display.readAndDispatch ()) display.sleep ();
	}
	display.dispose ();
}
}

What is SWT class?

The SWT class is package as org.eclipse.swt.SWT, it’s used to specify the widget style, like text alignment (SWT.LEFT, SWT.CENTER, SWT.RIGHT), widget shape SWT.BORDER, SWT.SHADOW_IN and so on. This is a very common class, please use Eclipse content assistant (CTRL + space) to list down all it’s members.

Please access SWT API documentation to know more about it
http://help.eclipse.org/stable/nftopic/org.eclipse.platform.doc.isv/reference/api/org/eclipse/swt/SWT.html

About Author

author image
Founder of Mkyong.com, love Java and open source stuff. Follow him on Twitter. If you like my tutorials, consider make a donation to these charities.

Comments

Subscribe
Notify of
3 Comments
Most Voted
Newest Oldest
Inline Feedbacks
View all comments
Mohammad Hadi Mansouri
11 years ago

My question is too:
Is it possible to use HTML in label?

Mostafa Barmshory
12 years ago

Is it possible to use HTML in label? for example:

Label a = new Label(..);
a.setText(“TitleThis is text”);

hello
14 years ago

hello,world!