Refactoring into a Component

When you design a graphical user interface strait forward (meaning you don’t plan on the final product) you might sometime realise that you have components that would be useful in other GUIs as well. The refactoring of such a component can be tricky especially consearning the preserving of the layout (the optical impression to the user). Therefore this article should shed some light on how to wrap a simple Lable into its component.

First let us define a Shell with a grid layout with two columns.

sShell = new Shell();
sShell.setText("Shell");
sShell.setBackground(new Color(null, 255, 0, 0));
sShell.setLayout(new GridLayout(2,false));
GridData gridData = new GridData(GridData.FILL_HORIZONTAL);
gridData.horizontalAlignment = GridData.FILL;
sShell.setLayoutData(gridData);

Now we add a Label to the shell and surround it with other Labels to let us see the cells:

new Label(sShell,SWT.NULL).setText("---------------------------------------");
new Label(sShell,SWT.NULL).setText("+++++++++++++++++++++++++++++++++++++++");
new Label(sShell,SWT.NULL).setText("local label");
new Label(sShell,SWT.NULL).setText("+++++++++++++++++++++++++++++++++++++++");
new Label(sShell,SWT.NULL).setText("---------------------------------------");
new Label(sShell,SWT.NULL).setText("+++++++++++++++++++++++++++++++++++++++");

Now we create a Composite that holds the Label. This we realise with an inner class:

public class LabelComposite extends Composite{
	public LabelComposite(Composite parent, int style) {
		super(parent, style);
		GridData gd = new GridData();
		gd.horizontalSpan=2;
		setLayoutData(gd);
		GridLayout layout = new GridLayout(1,false);
		layout.horizontalSpacing=0;
		layout.verticalSpacing=0;
		layout.marginWidth=0;
		layout.marginHeight=0;
		setLayout(layout);
		Label lbl = new Label(this,SWT.NONE);
		lbl.setText("composite label...................................................................");
		lbl.setBackground(new Color(null, 0, 255, 0));
	}
}

As you see the inner Label contains only one Control but spans to cells.
Now we add the component into our shell and souround it with labels as above.

new LabelComposite(sShell,SWT.NULL);
new Label(sShell,SWT.NULL).setText("---------------------------------------");
new Label(sShell,SWT.NULL).setText("+++++++++++++++++++++++++++++++++++++++");

If we run this shell the result looks like this:
compositelabel
The code to this example is available here.

Schreibe einen Kommentar