Wednesday, 30 November 2016

SWT: Composite widget

A Composite widget can contain other widgets, the way how you are adding widgets to shell, you can add widgets to Composite.

How to define a Composite?
Composite composite1 = new Composite(shell,SWT.BORDER);

How to add widgets to a composite?
Just like how you are adding widgets to Shell, you can add widgets to composite also.

Label label = new Label(composite1,SWT.NONE);

The position of widgets inside the composite are relative to the composite. You can apply following styles to Composite widget.

Widget
Description
NO_BACKGROUND
Style constant for no background behavior
NO_FOCUS
Style constant for no focus from the mouse behavior
NO_MERGE_PAINTS
Style constant for no paint event merging behavior
NO_REDRAW_RESIZE
Style constant for no redraw on resize behavior
NO_RADIO_GROUP
Style constant for preventing child radio group behavior
EMBEDDED
Style constant to allow embedding
DOUBLE_BUFFERED
Style constant to indicate double buffering

package swt_app;

import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.graphics.Color;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Combo;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Shell;

public class Test {

 private static int xPosition = 30;
 private static int yPosition = 30;

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

 private static int compositeWidth = 250;
 private static int compositeHeight = 250;

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

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

  Composite composite = new Composite(shell, SWT.BORDER);
  composite.setBackground(new Color(display, 102, 153, 153));
  composite.setBounds(10, 10, compositeWidth, compositeHeight);

  Combo combo = new Combo(composite, SWT.DROP_DOWN);
  combo.setItems(countries);
  combo.setBounds(xPosition, 20, 150, 100);
  combo.setText("Select your country");

  yPosition += 100;

  Button button1 = new Button(composite, 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 is : " + countries[combo.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(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();
 }
}


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



Previous                                                 Next                                                 Home

SWT: Combo widget

Combo widget is used to show collection of items (Drop Down list), where user can select an item. The user may also type a value into the combo widget.

A Combo takes less space than a List widget and shows similar information.

You can apply following styles to Combo widget.
Style
Description
DROP_DOWN
Style constant for drop down menu/list behavior
READ_ONLY
Style constant for read-only behavior
SIMPLE
Style constant for simple behavior


Only one of the styles DROP_DOWN and SIMPLE may be specified.
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.Combo;
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 = 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);

    Combo combo = new Combo(shell, SWT.DROP_DOWN);
    combo.setItems(countries);
    combo.setBounds(xPosition + 150, 20, 150, 100);
    combo.setText("Select your country");

    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 is : " + countries[combo.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 and submit, you can able to see the selected country in the console.



Previous                                                 Next                                                 Home

Can I Extend a class with only private constructors?

No, you can’t extend a class that has only private constructors. Let’s see it with an example.

Shape.java
public class Shape {
 private Shape() {
  System.out.println("Inside Shape");
 }
}

Circle.java
public class Circle extends Shape {

}


Try to compile 'Circle.java', Java compiler throws following errors.
C:\Users\Documents>javac Circle.java
Circle.java:1: error: Shape() has private access in Shape
public class Circle extends Shape {
       ^
1 error

This is one of the good interview questions, usually interviewers checks your understanding on OOPS concepts. Same question can be asked like 'How can you make a class as non-extendable without using final keyword'.

You may like



Tuesday, 29 November 2016

Implement Singleton with Enum

In my previous post, I explained how to implement a singleton pattern. This is continuation to my previous post, so I recommend you to go through the post, before reading this.


Singleton pattern restricts the instantiation of a class to one object. That is you can't create more than one object to this class.

Connection.java
package com.sample.singleton;

public class Connection {
 private static final Connection INSTANCE = new Connection();
 private int connId = 0;

 public static Connection getInstance() {
  return INSTANCE;
 }

 private Connection() {
  connId++;
  System.out.println("Connection object is created");
 }

 @Override
 public String toString() {
  StringBuilder builder = new StringBuilder();
  builder.append("Connection [connId=").append(connId).append("]");
  return builder.toString();
 }

}

ConnectionTest.java
package com.sample.singleton;

public class ConnectionTest {
 public static void main(String args[]) {
  Connection conn1 = Connection.getInstance();
  Connection conn2 = Connection.getInstance();
  Connection conn3 = Connection.getInstance();

  System.out.println("conn1 = " + conn1);
  System.out.println("conn2 = " + conn2);
  System.out.println("conn3 = " + conn3);

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

Connection class works absolutely fine until Connection class don't implement Serializable interface. If Connection class implements Serializable interface, whenever application deserialize the object, it return new instance, which violates singleton property. Let's see it by an example.

Connection.java
package com.sample.singleton;

import java.io.Serializable;

public class Connection implements Serializable {
 private static final long serialVersionUID = 1234L;
 private static final Connection INSTANCE = new Connection();
 private int connId = 0;

 public static Connection getInstance() {
  return INSTANCE;
 }

 private Connection() {
  connId++;
  System.out.println("Connection object is created");
 }

 @Override
 public String toString() {
  StringBuilder builder = new StringBuilder();
  builder.append("Connection [connId=").append(connId).append("]");
  return builder.toString();
 }

}

ConnectionTest.java
package com.sample.singleton;

import java.io.*;

public class ConnectionTest {
 public static void serializeObject(Connection conn, String fileName) {
  try (FileOutputStream fos = new FileOutputStream(fileName);
    ObjectOutputStream out = new ObjectOutputStream(fos)) {
   out.writeObject(conn);
  } catch (IOException e) {
   System.out.println("Error while serializing Connection object " + e.getMessage());
  }

 }

 public static Connection deserializeObject(String fileName) {

  try (FileInputStream fis = new FileInputStream("ser.out"); ObjectInputStream in = new ObjectInputStream(fis)) {
   Connection conn = (Connection) in.readObject();
   return conn;
  } catch (Exception e) {
   System.out.println("Error while Deserializing Connection object " + e.getMessage());
  }
  return null;

 }

 public static void main(String args[]) {
  Connection conn1 = Connection.getInstance();
  String fileName = "ser.out";

  serializeObject(conn1, fileName);

  Connection conn2 = deserializeObject(fileName);
  Connection conn3 = deserializeObject(fileName);

  System.out.println("conn1 = " + conn1);
  System.out.println("conn2 = " + conn2);
  System.out.println("conn3 = " + conn3);

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


Output
Connection object is created
conn1 = Connection [connId=1]
conn2 = Connection [connId=1]
conn3 = Connection [connId=1]
conn1 == conn2 : false
conn1 == conn3 : false
conn2 == conn3 : false

As you see the output, the objects conn1, conn2, conn3 are not equal. Every time application deserialize the object, it is returning different object.

How to resolve the issue?
To make singleton pattern works properly, Singleton class must implement the method readResolve. By using readResolve method, you can control what object should be returned on deserialization. Update Connection class like below.

Connection.java
package com.sample.singleton;

import java.io.Serializable;

public class Connection implements Serializable {
 private static final long serialVersionUID = 1234L;
 private static final Connection INSTANCE = new Connection();
 private int connId = 0;

 public static Connection getInstance() {
  return INSTANCE;
 }

 private Connection() {
  connId++;
  System.out.println("Connection object is created");
 }

 @Override
 public String toString() {
  StringBuilder builder = new StringBuilder();
  builder.append("Connection [connId=").append(connId).append("]");
  return builder.toString();
 }

 private Object readResolve() {
  return INSTANCE;
 }

}

Re run ConnectionTest.java, you can able to see following output.
Connection object is created
conn1 = Connection [connId=1]
conn2 = Connection [connId=1]
conn3 = Connection [connId=1]
conn1 == conn2 : true
conn1 == conn3 : true
conn2 == conn3 : true

Better way to provide singleton behavior to Connection class using Enum
From java1.5 onwards, by defining enum type with one element we can create singleton class very easily.

Update Connection class like below.


Connection.java
package com.sample.singleton;

import java.io.Serializable;

public enum Connection implements Serializable {
 INSTANCE;

 private int connId = 0;

 public static Connection getInstance() {
  return INSTANCE;
 }

 private Connection() {
  connId++;
  System.out.println("Connection object is created");
 }

 @Override
 public String toString() {
  StringBuilder builder = new StringBuilder();
  builder.append("Connection [connId=").append(connId).append("]");
  return builder.toString();
 }

}

Re run ConnectionTest.java file, you can able to see following output.
Connection object is created
conn1 = Connection [connId=1]
conn2 = Connection [connId=1]
conn3 = Connection [connId=1]
conn1 == conn2 : true
conn1 == conn3 : true
conn2 == conn3 : true

One advantage of this approach is, you no need to take care of serialization & deserialization issue, java handles it internally. I always prefer to implement singleton using enum.








When to use builder pattern

When a class requires more arguments to instantiate then it is better to go for a builder pattern. Let me explain with an example.

For example, you are developing an application to maintain all the employees’ information of organization ‘ABC’. Initially, I designed Employee model class like below.

Approach 1: Design Employee model class by providing setter and getter methods.

Employee.java
public class Employee {
 private int id;
 private String firstName;
 private String lastName;
 private float salary;
 private String designation;

 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 float getSalary() {
  return salary;
 }

 public void setSalary(float salary) {
  this.salary = salary;
 }

 public String getDesignation() {
  return designation;
 }

 public void setDesignation(String designation) {
  this.designation = designation;
 }

}

There is a problem with this approach. Since Employee class provides setter methods, you can’t make the Employee class immutable.

Approach 2: We can make the class ‘Employee’ immutable, by not providing setter methods and providing different combinations of constructors to initialize instance properties.

Employee.java
public class Employee {
 private int id;
 private String firstName;
 private String lastName;
 private float salary;
 private String designation;

 private static final String DEFAULT_NAME = "no_name";
 private static final int DEFAULT_ID = -1;
 private static final String DEFAULT_DESIGNATION = "Engineer";
 private static final float DEFAULT_SALARY = 25000;

 public Employee() {
  this(DEFAULT_ID, DEFAULT_NAME, DEFAULT_NAME, DEFAULT_SALARY, DEFAULT_DESIGNATION);
 }

 public Employee(int id) {
  this(id, DEFAULT_NAME, DEFAULT_NAME, DEFAULT_SALARY, DEFAULT_DESIGNATION);
 }

 public Employee(int id, String firstName) {
  this(id, firstName, DEFAULT_NAME, DEFAULT_SALARY, DEFAULT_DESIGNATION);
 }

 public Employee(int id, String firstName, String lastName) {
  this(id, firstName, lastName, DEFAULT_SALARY, DEFAULT_DESIGNATION);
 }

 public Employee(int id, String firstName, String lastName, float salary, String designation) {
  this.id = id;
  this.firstName = firstName;
  this.lastName = lastName;
  this.salary = salary;
  this.designation = designation;
 }

 public int getId() {
  return id;
 }

 public String getFirstName() {
  return firstName;
 }

 public String getLastName() {
  return lastName;
 }

 public float getSalary() {
  return salary;
 }

 public String getDesignation() {
  return designation;
 }

}

There is a problem with above model class, As you see the definition of Employee class, I provided 4 different constructors to initialize different combination of properties. What if my class has more instance properties, I will end up in more and more constructor definitions, which is not feasible. We can solve both the problems by providing builder object.

Approach 3: Define Employee model class using builder pattern.

Employee.java
public class Employee {
 private int id;
 private String firstName;
 private String lastName;
 private float salary;
 private String designation;

 private Employee() {

 }

 public int getId() {
  return id;
 }

 public String getFirstName() {
  return firstName;
 }

 public String getLastName() {
  return lastName;
 }

 public float getSalary() {
  return salary;
 }

 public String getDesignation() {
  return designation;
 }

 public static class EmployeeBuilder {

  private static final String DEFAULT_NAME = "no_name";
  private static final int DEFAULT_ID = -1;
  private static final String DEFAULT_DESIGNATION = "Engineer";
  private static final float DEFAULT_SALARY = 25000;

  private int id;
  private String firstName;
  private String lastName;
  private float salary;
  private String designation;

  public EmployeeBuilder() {
   this.id = DEFAULT_ID;
   this.firstName = this.lastName = DEFAULT_NAME;
   this.salary = DEFAULT_SALARY;
   this.designation = DEFAULT_DESIGNATION;
  }

  public EmployeeBuilder id(int id) {
   this.id = id;
   return this;
  }

  public EmployeeBuilder firstName(String firstName) {
   this.firstName = firstName;
   return this;
  }

  public EmployeeBuilder lastName(String lastName) {
   this.lastName = lastName;
   return this;
  }

  public EmployeeBuilder salary(float salary) {
   this.salary = salary;
   return this;
  }

  public EmployeeBuilder designation(String designation) {
   this.designation = designation;
   return this;
  }

  public Employee build() {
   Employee emp = new Employee();
   emp.designation = this.designation;
   emp.firstName = this.firstName;
   emp.id = this.id;
   emp.lastName = lastName;
   emp.salary = salary;
   return emp;
  }
 }

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

}

Test.java
public class Test {

 public static void main(String args[]) {
  
  Employee.EmployeeBuilder builder = new Employee.EmployeeBuilder();
  
  Employee emp = builder.id(553)
       .firstName("Hari krishna")
       .lastName("Gurram")
       .designation("Software Engineer")
       .build();
  
  System.out.println(emp);
 }

}

Output
Employee [id=553, firstName=Hari krishna, lastName=Gurram, salary=25000.0, designation=Software Engineer]

In real world applications, it is always good coding practice to code for an interface. For example, you can define a Builder interface like below, and make the EmployeeBuilder class implements the Builder interface.

public interface Builder<T> {
 public T build();
}

Implement EmployeeBuilder like below.
public static class EmployeeBuilder implements Builder<Employee> {

  private static final String DEFAULT_NAME = "no_name";
  private static final int DEFAULT_ID = -1;
  private static final String DEFAULT_DESIGNATION = "Engineer";
  private static final float DEFAULT_SALARY = 25000;

  private int id;
  private String firstName;
  private String lastName;
  private float salary;
  private String designation;

  public EmployeeBuilder() {
   this.id = DEFAULT_ID;
   this.firstName = this.lastName = DEFAULT_NAME;
   this.salary = DEFAULT_SALARY;
   this.designation = DEFAULT_DESIGNATION;
  }

  public EmployeeBuilder id(int id) {
   this.id = id;
   return this;
  }

  public EmployeeBuilder firstName(String firstName) {
   this.firstName = firstName;
   return this;
  }

  public EmployeeBuilder lastName(String lastName) {
   this.lastName = lastName;
   return this;
  }

  public EmployeeBuilder salary(float salary) {
   this.salary = salary;
   return this;
  }

  public EmployeeBuilder designation(String designation) {
   this.designation = designation;
   return this;
  }

  @Override
  public Employee build() {
   Employee emp = new Employee();
   emp.designation = this.designation;
   emp.firstName = this.firstName;
   emp.id = this.id;
   emp.lastName = lastName;
   emp.salary = salary;
   return emp;
  }
 }