Monday, 28 November 2016

SWT: List widget

List widget is used to display collection of items, where user can select an item from the list. A list can be single (or) multi selected. In a multi selected list, you can select more than one item.

You can apply following styles to a List.
Style
Description
SINGLE
Style constant for single selection behavior in lists and single line support on text fields.
MULTI
Style constant for multi-selection behavior in lists and multiple line support on text fields.

Only one of SINGLE and MULTI may be specified. To add items to a list, you can use the setItems() method, or the add() method.

Ex:
List list1 = new List(shell, SWT.MULTI | SWT.H_SCROLL | SWT.V_SCROLL);
list1.setItems(countries);

list1.setBounds(xPosition + 150, 20, 150, 100);
package swt_app;

import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.List;
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 = 30;

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

  private static String[] countries = { "India", "Germany", "Canada", "Japan", "Sri Lanka", "Singpore", "Russia" };

  private static void addWidgetsToShell(Shell shell) {

    Label label = new Label(shell, SWT.NONE);
    label.setText("Select your Country : ");
    label.setLocation(xPosition, yPosition);
    label.setSize(150, height);

    List list1 = new List(shell, SWT.MULTI | SWT.H_SCROLL | SWT.V_SCROLL);
    list1.setItems(countries);
    list1.setBounds(xPosition + 150, 20, 150, 100);

    yPosition += 100;

    Button button1 = new Button(shell, SWT.PUSH);
    button1.setText("Submit");
    button1.setLocation(xPosition + 100, yPosition);
    button1.setSize(100, 20);

    button1.addSelectionListener(new SelectionAdapter() {
      public void widgetSelected(SelectionEvent e) {
        System.out.println("Country Selected Index is : " + countries[list1.getSelectionIndex()]);
      }
    });

  }

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

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


Select any country in the list and click the submit button, you can able to see the country selected by you in the console.



Previous                                                 Next                                                 Home

Why to use static factory methods over constructors

By using constructors, we can create objects to any class. There is also another way to create objects to a class. By using static factory methods, you can create instances to a class. Static factory method is a static method that returns instance of this class.

For example, following are some of the static factory methods provided by Java.

public static Integer valueOf(int i) //Return Integer object
public static Float valueOf(String s) throws NumberFormatException //Return Float object
public static Boolean valueOf(String s)//Return Boolean object

Let’s see the advantages of defining static factory methods.

a.   By providing the meaningful name to static factory method, we can give meaningful context to the developer (or) to the reader who is reading the source code.
b.   By using static factory methods we can control number of instances to a class
c.    Static factory methods provide flexibility that, it can return object of any subtype.

By providing the meaningful name to static factory method, we can give meaningful context to the developer (or) to the reader who is reading the source code.

Employee.java
public class Employee {
 private int id;
 private String firstName;
 private String lastName;
 private boolean permanentEmployee;

 private Employee(int id, String firstName, String lastName, boolean permanentEmployee) {
  this.id = id;
  this.firstName = firstName;
  this.lastName = lastName;
  this.permanentEmployee = permanentEmployee;
 }

 public boolean isPermanentEmployee() {
  return permanentEmployee;
 }

 public void setPermanentEmployee(boolean permanentEmployee) {
  this.permanentEmployee = permanentEmployee;
 }

 public int getId() {
  return id;
 }

 public void setId(int id) {
  this.id = id;
 }

 public String getFirstName() {
  return firstName;
 }

 public void setFirstName(String firstName) {
  this.firstName = firstName;
 }

 public String getLastName() {
  return lastName;
 }

 public void setLastName(String lastName) {
  this.lastName = lastName;
 }

 public static Employee getPermanentEmployee(int id, String firstName, String lastName) {
  return new Employee(id, firstName, lastName, true);
 }

 public static Employee getContractEmployee(int id, String firstName, String lastName) {
  return new Employee(id, firstName, lastName, false);
 }

 @Override
 public String toString() {
  StringBuilder builder = new StringBuilder();
  builder.append("Employee [id=").append(id).append(", firstName=").append(firstName).append(", lastName=")
    .append(lastName).append(", permanentEmployee=").append(permanentEmployee).append("]");
  return builder.toString();
 }

}

Notify above example, I provided two static factory methods to return permanent and contract employee instances. By looking at following method signatures, user can get an idea about the instance.

public static Employee getPermanentEmployee(int id, String firstName, String lastName);
public static Employee getContractEmployee(int id, String firstName, String lastName);

Test.java
public class Test {
 
 public static void main(String args[]){
  Employee permEmp = Employee.getPermanentEmployee(1, "Shanmukh", "Kummari");
  Employee contractEmp = Employee.getContractEmployee(2, "Hari Krishna", "Gurram");
  
  System.out.println(permEmp);
  System.out.println(contractEmp);
 }
 
}

Output
Employee [id=1, firstName=Shanmukh, lastName=Kummari, permanentEmployee=true]
Employee [id=2, firstName=Hari Krishna, lastName=Gurram, permanentEmployee=false]

By using static factory methods we can control number of instances to a class
By restricting access to the constructors of a class and by providing static factory method to get the instance, you can control the number of instances to the class at any given point of time.

Connection.java
public class Connection {
 private static Connection conn = new Connection();

 private Connection() {

 }

 public static Connection getConnection() {
  return conn;
 }

}

Test.java
public class Test {

 public static void main(String args[]) {
  Connection conn1 = Connection.getConnection();
  Connection conn2 = Connection.getConnection();

  System.out.println("(conn1 == conn2) : " + (conn1 == conn2));
  System.out.println("conn1.equals(conn2) : " + conn1.equals(conn2));
 }

}

Output
(conn1 == conn2) : true
conn1.equals(conn2) : true

Static factory methods provide flexibility that, it can return object of any subtype.

ShapeFactory.java
public class ShapeFactory {
 public interface Shape {
  public default void print() {
   System.out.println("Default implementaiton of shape");
  }
 }

 private static class Circle implements Shape {
  public void print() {
   System.out.println("I am inside circle");
  }
 }

 private static class Square implements Shape {
  public void print() {
   System.out.println("I am inside Square");
  }
 }

 private static class DefaultShape implements Shape {

 }

 public static Shape getShape(String shapeType) {
  switch (shapeType) {
  case "Square":
   return new Square();
  case "Circle":
   return new Circle();
  default:
   return new DefaultShape();
  }
 }
}

As you see 'ShapeFactory' class, it exposes the 'Shape' interface by making it as public and hides the implemebtations of Shape (Circle, Square, and DefaultShape) by making them as private.

Test.java
public class Test {

 public static void main(String args[]) {
  ShapeFactory.Shape shape1 = ShapeFactory.getShape("");
  ShapeFactory.Shape shape2 = ShapeFactory.getShape("Circle");
  ShapeFactory.Shape shape3 = ShapeFactory.getShape("Square");

  shape1.print();
  shape2.print();
  shape3.print();
 }

}

Friday, 25 November 2016

SWT: Add event handler to button

Event handlers are used to get notification when particular events happened on SWT widget.

Ex:
button1.addSelectionListener(new SelectionAdapter() {
         public void widgetSelected(SelectionEvent e) {
                 System.out.println("Submit button was clicked");
         }
});

By using addSelectionListener, you can get notifications, whenever a button is clicked.
package swt_app;

import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Text;

public class Test {

  private static int xPosition = 30;
  private static int yPosition = 30;
  private static int width = 500;
  private static int height = 30;
  private static int scrollWidth = 500;
  private static int scrollHeight = 350;

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

  private static void addWidgetsToShell(Shell shell) {

    Text text1 = new Text(shell, SWT.BORDER);
    text1.setText("You can't edit me");
    text1.setBounds(xPosition, yPosition, width, height);
    text1.setEditable(false);

    yPosition += 40;

    Text text2 = new Text(shell, SWT.BORDER | SWT.H_SCROLL | SWT.V_SCROLL);
    text2.setText("Bordered scrolled text box");
    text2.setBounds(xPosition, yPosition, scrollWidth, scrollHeight);

    yPosition += 80;

    Button button1 = new Button(shell, SWT.PUSH);
    button1.setText("Submit");
    button1.setLocation(xPosition + 130, yPosition + 300);
    button1.setSize(100, 20);

    Button button2 = new Button(shell, SWT.PUSH);
    button2.setText("Cancel");
    button2.setLocation(xPosition + 260, yPosition + 300);
    button2.setSize(100, 20);

    button1.addSelectionListener(new SelectionAdapter() {
      public void widgetSelected(SelectionEvent e) {
        System.out.println("Submit button was clicked");
      }
    });

    button2.addSelectionListener(new SelectionAdapter() {
      public void widgetSelected(SelectionEvent e) {
        System.out.println("Cancel button was clicked");
      }
    });

  }

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

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



Experiment by clicking Submit, Cancel buttons, you can able to see the messages in console.


Previous                                                 Next                                                 Home

SWT: Button: Create a button

Button widget is used to create a button, and clicked by user to perform some processing.

Ex:
Button button1 = new Button(shell, SWT.PUSH);
button1.setText("Submit");
button1.setLocation(0, 0);
button1.setSize(100, 20);

Above statements create a button with text ‘Submit’. You can also set the style, background, image and more by using set methods.

You can apply following styles to Button element.
Style
Description
SWT.ARROW
Style constant for arrow button behavior
SWT.CHECK
Style constant for check box behavior
SWT.PUSH
Style constant for push button behavior
SWT.RADIO
Style constant for radio button behavior
SWT.TOGGLE
Style constant for toggle button behavior
SWT.FLAT
Style constant for flat appearance.
SWT.WRAP
Style constant for automatic line wrap behavior.
SWT.UP
Style constant for align up behavior
SWT.DOWN
Style constant for align down behavior
SWT.LEFT
Style constant for align left behavior
SWT.RIGHT
Style constant for align right behavior
SWT.CENTER
Style constant for align center behavior

Note
a.   Only one of the styles ARROW, CHECK, PUSH, RADIO, and TOGGLE may be specified.
b.   Only one of the styles LEFT, RIGHT, and CENTER may be specified.
c.    Only one of the styles UP, DOWN, LEFT, and RIGHT may be specified when the ARROW style is specified.

package swt_app;

import org.eclipse.swt.SWT;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Text;

public class Test {

  private static int xPosition = 30;
  private static int yPosition = 30;
  private static int width = 500;
  private static int height = 30;
  private static int scrollWidth = 500;
  private static int scrollHeight = 350;

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

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

    Text text1 = new Text(shell, SWT.BORDER);
    text1.setText("You can't edit me");
    text1.setBounds(xPosition, yPosition, width, height);
    text1.setEditable(false);

    yPosition += 40;

    Text text2 = new Text(shell, SWT.BORDER | SWT.H_SCROLL | SWT.V_SCROLL);
    text2.setText("Bordered scrolled text box");
    text2.setBounds(xPosition, yPosition, scrollWidth, scrollHeight);

    yPosition += 80;

    Button button1 = new Button(shell, SWT.PUSH);
    button1.setText("Submit");
    button1.setLocation(xPosition + 130, yPosition + 300);
    button1.setSize(100, 20);

    Button button2 = new Button(shell, SWT.PUSH);
    button2.setText("Cancel");
    button2.setLocation(xPosition + 260, yPosition + 300);
    button2.setSize(100, 20);

  }

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

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



Previous                                                 Next                                                 Home