Monday, 16 January 2017

jFace: Message Dialog

jface provides MessageDialog class to display message dialogs to user. MessageDialog class provides following constructor to instantiate.

MessageDialog(Shell parentShell, String dialogTitle, Image dialogTitleImage, String dialogMessage, int dialogImageType, String[] dialogButtonLabels, int defaultIndex)

Following table summarizes the parameters.
Parameter
Description
parentShell
Parent shell
dialogTitle
Title of the message dialog
dialogTitleImage
Dialog title Image
dialogMessage
Dialog message
dialogImageType
It can be one of the following values:
MessageDialog.NONE for a dialog with no image
MessageDialog.ERROR for a dialog with an error image
MessageDialog.INFORMATION for a dialog with an information image
MessageDialog.QUESTION for a dialog with a question image
MessageDialog.WARNING for a dialog with a warning image
dialogButtonLabels
An array of labels for the buttons in the button bar
defaultIndex
The index in the button label array of the default button

Note
a.   You must call the open method on the MessageDialog to open, else it is not displayed on the screen.

Ex:
Image IMAGE_APP_LOGO = new Image(null, "C:\\Users \\Documents\\Study\\app_logo.png");
                
MessageDialog dialog = new MessageDialog(Display.getDefault().getActiveShell(), "Hello", IMAGE_APP_LOGO,"Hello Message", MessageDialog.INFORMATION, buttons, 2);

Following is the complete working application.
package test;

import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Shell;

public class Test {
 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);

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

  String[] buttons = { "OK", "CANCEL", "NOT DECIDED" };
  Image IMAGE_APP_LOGO = new Image(null, "C:\\Users\\Documents\\Study\\app_logo.png");
  MessageDialog dialog = new MessageDialog(Display.getDefault().getActiveShell(), "Hello", IMAGE_APP_LOGO,
    "Hello Message", MessageDialog.INFORMATION, buttons, 2);

  int result = dialog.open();
  System.out.println("You clicked " + buttons[result]);
  /*
   * 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();
 }
}

MessageDialog class provides following static helper methods to quickly open commonly used dialogs.

static boolean openConfirm(Shell parent, String title, String message)
Convenience method to open a simple confirm (OK/Cancel) dialog. Return true if the user presses the OK button, false otherwise

static void openError(Shell parent, String title, String message)
Convenience method to open a standard error dialog.

static void openInformation(Shell parent, String title, String message)
Convenience method to open a standard information dialog.

static boolean openQuestion(Shell parent, String title, String message)
Convenience method to open a simple Yes/No question dialog.

static void openWarning(Shell parent, String title, String message)
Convenience method to open a standard warning dialog.

Ex:
MessageDialog.openConfirm(Display.getDefault().getActiveShell(), "Confirm Title", "This is Confirmation Message");
MessageDialog.openError(Display.getDefault().getActiveShell(), "Error Title", "This is Error Message");
MessageDialog.openInformation(Display.getDefault().getActiveShell(), "Information Title","This is Information Message");
MessageDialog.openQuestion(Display.getDefault().getActiveShell(), "Question Title", "This is Question Message");
MessageDialog.openWarning(Display.getDefault().getActiveShell(), "Warning Title", "This is Warning Message");


Following is the complete working application.
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Shell;

public class Test {
 public static void main(String[] args) {
  System.out.println(System.getProperty("user.home"));

  /* 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);

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

  MessageDialog.openConfirm(Display.getDefault().getActiveShell(), "Confirm Title",
    "This is Confirmation Message");
  MessageDialog.openError(Display.getDefault().getActiveShell(), "Error Title", "This is Error Message");
  MessageDialog.openInformation(Display.getDefault().getActiveShell(), "Information Title",
    "This is Information Message");
  MessageDialog.openQuestion(Display.getDefault().getActiveShell(), "Question Title", "This is Question Message");
  MessageDialog.openWarning(Display.getDefault().getActiveShell(), "Warning Title", "This is Warning Message");
  /*
   * 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();
 }
}




Previous                                                 Next                                                 Home

SWT: JFace

JFace is an UI toolkit built on top of SWT libraries. By using JFace, we can develop UI application with less lines of code as compared to SWT. Subsequent posts explain thw widgets provided by jFace.


Previous                                                 Next                                                 Home

Java9: Allow SafeVarargs on Private Methods

By using @SafeVarargs annotation, we can tell the compiler that the usage of varargs and generics is safe . @SafeVarargs can only be applied to methods which cannot be overridden. Prior to Java9, @SafeVarargs is applied to only
c.    Constructors

Another kind of non-overridable executable is a private method. From Java9 onwards, you can apply @SafeVarargs annotation on top of private methods also.

What are varargs?
In java we can create methods that takes variable number of arguments. This feature is called varargs or variable number of arguments. The method which accepts variable number of arguments is called varargs method.

Syntax
    returnType methodName(dataType … parameterName){

    }

"..." tells the compiler that this is a vararg.
class VarargsEx{
 public void printData(int ... a){
  System.out.println("Parameters are " + a.length);
  for(int i=0; i < a.length; i++)
   System.out.print(a[i] + " ");
  System.out.println();
 }

 public static void main(String args[]){
  VarargsEx obj = new VarargsEx();
  obj.printData(1);
  obj.printData(1,2);
  obj.printData(1,2,3);
 }
}

Output
Parameters are 1
1
Parameters are 2
1 2
Parameters are 3
1 2 3

The syntax of the method printData, tells the compiler, that this method can accept zero or more arguments. So all the calls like below are valid.
    obj.printData(1);
    obj.printData(1,2);
    obj.printData(1,2,3);

A varargs parameter of type T... is converted into a parameter of type T[]. By applying @SafeVarargs on a method or constructor makes sure the compiler these methods don’t perform potentially unsafe operations on its varargs parameter. Applying this annotation to a method or constructor suppresses unchecked warnings about a non-reifiable variable arity (vararg) type and suppresses unchecked warnings about parameterized array creation at call sites.
import java.util.*;
import java.lang.*;

class SafeVarargsEx{
 static void call(List<String>... stringLists) {
  String s = stringLists[0].get(0);
  System.out.println(s);
 }

 public static void main(String args[]){  
  List<String> myList1 = new ArrayList<> ();
  List<String> myList2 = new ArrayList<> ();
  
  myList1.add("Hi");
  myList2.add("Hi");
  
  call(myList1, myList2);
 }
}

When you tries to compile the above program, compiler throws below warning messages.
Note: SafeVarargsEx.java uses unchecked or unsafe operations.
Note: Recompile with -Xlint:unchecked for details.

To suppress the above warnings use @SafeVarargs Annotation.
import java.util.*;
import java.lang.*;

class SafeVarargsEx{
 @SafeVarargs
 static void call(List<String>... stringLists) {
  String s = stringLists[0].get(0);
  System.out.println(s);
 }

 public static void main(String args[]){  
  List<String> myList1 = new ArrayList<> ();
  List<String> myList2 = new ArrayList<> ();
  
  myList1.add("Hi");
  myList2.add("Hi");
  
  call(myList1, myList2);
 }
}

@SafeVarargs can only be applied to methods which cannot be overridden. Prior to Java9, @SafeVarargs is applied to only
a.   Static methods
b.   Final methods
c.    Constructors

Another kind of non-overridable executable is a private method. Therefore, it would be reasonable to allow @SafeVarargs to be applied to private methods too. From Java9 onwards, it is possible to apply @SafeVarargs annotation on private methods.

Reference



Previous                                                 Next                                                 Home

Sunday, 15 January 2017

SWT: FormLayout

FormLayout is the advanced layout out of the four layouts (FillLayout, RowLayout, GridLayout). It gives flexibility to control the position and size of the children of a composite control by using FormAttachments.

Ex:
FormLayout formLayout = new FormLayout();
formLayout.marginWidth = 3;
formLayout.marginHeight = 3;
shell.setLayout(formLayout);

Just like how we used GridData instance to control widgets in GridLayout, there is FormData instance we can use to control the widgets in FormLayout.

How to define FormData object?
By using FormData instance, we can attach the SWT widgets to FormLayout.

Ex:
Composite leftComposite = new Composite(shell, SWT.BORDER);

FormData formData = new FormData();
formData.top = new FormAttachment(0, 10);
formData.left = new FormAttachment(0, 10);
formData.bottom = new FormAttachment(75, 0);
formData.right = new FormAttachment(40, 0);
leftComposite.setLayoutData(formData);

What is FormAttachment?
FormAttachment instances are used to define edges of widget within a FormLayout. We can set FormAttachments to top, bottom, left and right fields of FormData.

What are the constants top, left, bottom, right?
Following table summarizes the constants.

Constant
Description
top
top specifies the attachment of the top of the control (widget).
bottom
bottom specifies the attachment of the bottom of the control.
left
left specifies the attachment of the left side of  the control.
right
right specifies the attachment of the right side of the control.

FormAttachment class provides following constructors.
Constructor
Description
public FormAttachment ()
Constructs a new instance of this class. The numerator is zero, the denominator is 100 and the offset is zero.
public FormAttachment (int numerator)
Constructs a new instance of this class with given numerator, denominator to 100, offset to 0.
public FormAttachment (int numerator, int offset)
Constructs a new instance of this class with given numerator, offset and denominator of 100.
public FormAttachment (int numerator, int denominator, int offset)
Constructs a new instance of this class with given numerator, denominator , offset.
public FormAttachment (Control control)
Constructs a new instance of this class given a control. Since no alignment is specified, the default alignment is to attach the side to the adjacent side of the specified control. Since no offset is specified, an offset of 0 is used.
public FormAttachment (Control control, int offset)
Constructs a new instance of this class given a control. Since no alignment is specified, the default alignment is to attach the side to the adjacent side of the specified control. Since no offset is specified, an offset of 0 is used.
public FormAttachment (Control control, int offset, int alignment)
Constructs a new instance of this class given a control, an offset and an alignment.
Following are the possible alignments.

SWT.TOP : The side will be attached to the top side of the specified control
SWT.BOTTOM : The side will be attached to the bottom side of the specified control
SWT.LEFT : The side will be attached to the left side of the specified control
SWT.CENTER : The side will be attached to the right side of the specified control
SWT.DEFAULT : The side will be attached to the adjacent side of the specified control

What are the numerator and denominators?
A FormAttachment defines where to attach the side of a control by using the equation, y = ax + b. The "a" term represents a fraction of the parent composite's width (from the left) or height (from the top). It can be defined using a numerator and denominator, or just a percentage value. If a percentage is used, the denominator is set to 100. The "b" term in the equation represents an offset, in pixels, from the attachment position


Following is the complete working application.
import org.eclipse.swt.SWT;
import org.eclipse.swt.layout.FillLayout;
import org.eclipse.swt.layout.FormAttachment;
import org.eclipse.swt.layout.FormData;
import org.eclipse.swt.layout.FormLayout;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.layout.RowLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Text;

public class Test {

 private static Composite addLeftComposite(Shell shell) {
  /* Add Left composite to shell */
  Composite leftComposite = new Composite(shell, SWT.BORDER);
  FillLayout fillLayout = new FillLayout();
  fillLayout.type = SWT.VERTICAL;
  leftComposite.setLayout(fillLayout);

  Label label0 = new Label(leftComposite, SWT.NONE);
  label0.setText("File");
  Label label1 = new Label(leftComposite, SWT.NONE);
  label1.setText("Edit");
  Label label2 = new Label(leftComposite, SWT.NONE);
  label2.setText("Source");
  Label label3 = new Label(leftComposite, SWT.NONE);
  label3.setText("Refactor");
  Label label4 = new Label(leftComposite, SWT.NONE);
  label4.setText("Navigate");
  Label label5 = new Label(leftComposite, SWT.NONE);
  label5.setText("Search");
  Label label6 = new Label(leftComposite, SWT.NONE);
  label6.setText("Project");
  Label label7 = new Label(leftComposite, SWT.NONE);
  label7.setText("Run");
  Label label8 = new Label(leftComposite, SWT.NONE);
  label8.setText("Window");
  Label label9 = new Label(leftComposite, SWT.NONE);
  label9.setText("Help");

  FormData formData = new FormData();
  formData.top = new FormAttachment(0, 10);
  formData.left = new FormAttachment(0, 10);
  formData.bottom = new FormAttachment(75, 0);
  formData.right = new FormAttachment(40, 0);
  leftComposite.setLayoutData(formData);

  return leftComposite;
 }

 private static Composite addBottomComposite(Shell shell, Composite leftPanel) {
  RowLayout rowLayout = new RowLayout();

  Composite bottomComposite = new Composite(shell, SWT.NONE);
  bottomComposite.setLayout(rowLayout);

  Button b1 = new Button(bottomComposite, SWT.PUSH);
  b1.setText("File");
  Button b2 = new Button(bottomComposite, SWT.PUSH);
  b2.setText("Edit");
  Button b3 = new Button(bottomComposite, SWT.PUSH);
  b3.setText("Source");
  Button b4 = new Button(bottomComposite, SWT.PUSH);
  b4.setText("Refactor");
  Button b5 = new Button(bottomComposite, SWT.PUSH);
  b5.setText("Navigate");
  Button b6 = new Button(bottomComposite, SWT.PUSH);
  b6.setText("Search");
  Button b7 = new Button(bottomComposite, SWT.PUSH);
  b7.setText("Search");
  Button b8 = new Button(bottomComposite, SWT.PUSH);
  b8.setText("Search");
  Button b9 = new Button(bottomComposite, SWT.PUSH);
  b9.setText("Search");
  Button b10 = new Button(bottomComposite, SWT.PUSH);
  b10.setText("Search");

  FormData formRow = new FormData();
  formRow.top = new FormAttachment(leftPanel, 10);
  formRow.left = new FormAttachment(0, 10);
  formRow.bottom = new FormAttachment(100, -10);
  formRow.right = new FormAttachment(100, -10);
  bottomComposite.setLayoutData(formRow);

  return bottomComposite;

 }

 private static Composite addRightComposite(Shell shell, Composite leftPanel) {

  Composite rightComposite = new Composite(shell, SWT.NONE);

  GridLayout gridLayout = new GridLayout();
  gridLayout.numColumns = 2;
  rightComposite.setLayout(gridLayout);

  Label label1 = new Label(rightComposite, SWT.NONE);
  label1.setText("Name:");
  Text text1 = new Text(rightComposite, SWT.BORDER);

  Label label2 = new Label(rightComposite, SWT.NONE);
  label2.setText("Age:");
  Text text2 = new Text(rightComposite, SWT.BORDER);

  Label label3 = new Label(rightComposite, SWT.NONE);
  label3.setText("Gender:");
  Text text3 = new Text(rightComposite, SWT.BORDER);

  Button button = new Button(rightComposite, SWT.CHECK);
  button.setText("Have you been employed in the past six months?");

  GridData gridData1 = new GridData();
  GridData gridData2 = new GridData();
  GridData gridData3 = new GridData();

  gridData1.widthHint = 60;
  gridData2.widthHint = 60;
  gridData3.widthHint = 60;

  label1.setLayoutData(gridData1);
  label2.setLayoutData(gridData2);
  label3.setLayoutData(gridData3);

  GridData gridData4 = new GridData(GridData.FILL_HORIZONTAL);
  GridData gridData5 = new GridData(GridData.FILL_HORIZONTAL);
  GridData gridData6 = new GridData(GridData.FILL_HORIZONTAL);

  text1.setLayoutData(gridData4);
  text2.setLayoutData(gridData5);
  text3.setLayoutData(gridData6);

  GridData gridData7 = new GridData();
  gridData7.horizontalSpan = 2;
  button.setLayoutData(gridData7);

  FormData formGrid = new FormData();
  formGrid.top = new FormAttachment(0, 10);
  formGrid.left = new FormAttachment(leftPanel, 10);
  formGrid.right = new FormAttachment(100, -10);
  formGrid.bottom = new FormAttachment(leftPanel, 10, SWT.BOTTOM);
  rightComposite.setLayoutData(formGrid);

  return rightComposite;
 }

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

  FormLayout formLayout = new FormLayout();
  formLayout.marginWidth = 3;
  formLayout.marginHeight = 3;

  shell.setLayout(formLayout);

  Composite leftComposite = addLeftComposite(shell);
  addBottomComposite(shell, leftComposite);
  addRightComposite(shell, leftComposite);

  shell.open();

 }

 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(700, 500);
  shell.setText("GridLayout Demo");
  addWidgetsToShell(display, shell);

  /*
   * 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