Tuesday 22 November 2016

SWT: Adding border to labels

By using the constant SWT.BORDER, you can add borders to labels.

Ex:
Label labelCenter = new Label(shell, SWT.CENTER | SWT.BORDER);

Above statement adds border to label and make the alignment center.

Following is the complete working application.
package swt_app;

import org.eclipse.swt.SWT;
import org.eclipse.swt.graphics.Color;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Shell;

public class Test {

 private static int xPosition = 30;
 private static int yPosition = 30;
 private static int width = 500;
 private static int height = 40;

 private static int shellWidth = 600;
 private static int shellHeight = 300;

 private static void addLabelsToShell(Display display, Shell shell) {

  Label labelCenter = new Label(shell, SWT.CENTER | SWT.BORDER);
  labelCenter.setText("Label Center");
  labelCenter.setBounds(shell.getClientArea());
  labelCenter.setSize(width, height);
  labelCenter.setLocation(xPosition, yPosition);
  yPosition += 50;

  Label labelLeft = new Label(shell, SWT.LEFT | SWT.BORDER);
  labelLeft.setText("Label left");
  labelLeft.setBounds(shell.getClientArea());
  labelLeft.setSize(width, height);
  labelLeft.setLocation(xPosition, yPosition);
  yPosition += 50;

  Label labelRight = new Label(shell, SWT.RIGHT | SWT.BORDER);
  labelRight.setText("Label Right");
  labelRight.setBounds(shell.getClientArea());
  labelRight.setSize(width, height);
  labelRight.setLocation(xPosition, yPosition);

 }

 public static void main(String[] args) {

  /* Instantiate Display object, it represents SWT session */
  Display display = new Display();

  /*
   * Define Shell, it represent a window, You can add more than one shell
   * to Display
   */
  Shell shell = new Shell(display);
  shell.setSize(shellWidth, shellHeight);

  addLabelsToShell(display, shell);

  /* Open shell window */
  shell.open();

  /*
   * Run the event dispatching loop until an exit condition occurs, which
   * is typically when the main shell window is closed by the user.
   */

  while (!shell.isDisposed()) {
   if (!display.readAndDispatch())
    display.sleep();
  }

  /* Dispose the display */
  display.dispose();
 }
}


Run above application, you can able to see following window.






Previous                                                 Next                                                 Home

No comments:

Post a Comment