Welcome to our active community of Eclipse RCP developers! Visit the tutorials Table of Contents or search for the topics you need help with. Then return the favor by contributing your own tip or trick. Don't hesitate, get sharing right away. It's easy!

Thursday, May 28, 2009

Using Simple JFace Message Boxes in an Eclipse RCP Application

This article shows how to use JFace messages boxes in an RCP application and builds off of a clean RCP Application with a View. The full source code is found at the end of the article. Most if not all GUI applications frequently use message boxes to give or get information to or from the user. Jface provides us with 5 commonly used message boxes which can be conveniently used via a single static method. The available message boxes are:

  • MessageDialog.openQuestion()
  • MessageDialog.openInformation()
  • MessageDialog.openWarning()
  • MessageDialog.openConfirm()
  • MessageDialog.openError()
Each method takes as arguments a Shell that the message box belongs to, the title of the message box, and the message to be displayed in the message box. They each display an icon such as a question mark or a exclamation mark, etc. (For some reason the openQuestion message box displayes an exclamation point on a Mac?!?) and a button or buttons for the user to close the box or respond to a question. The openQuestion and openConfirm message boxes return a boolean corresponding to the users selection.

To demonstrate the JFace Message Boxes used in an Eclipse RCP application, a view containing a single button is created. When the button is clicked, a Question message box pops up, and depending on the boolean value returned, opens up either a Warning or an Information message box.

Step 0: Create a Hello World Eclipse RCP Application and add a View to it.

Step 1: Add code to the createPartControl() method in the application's view to add a button and set its action listener, coding the calls to the JFace message box static methods.


package com.eclipsercptutorials.jfacemessageboxes;

import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.layout.RowLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.part.ViewPart;

public class MainView extends ViewPart {

public static final String ID = "com.eclipsercptutorials.JFaceMessageBoxes.MainView"; // the ID needs to match the id set in the view's properties

public MainView() {}

public void createPartControl(Composite parent) {

Composite lMainViewComposite = new Composite(parent, SWT.NONE);

Button lButton = new Button(lMainViewComposite, SWT.PUSH);
lButton.setText("Question");
lButton.addSelectionListener(new SelectionAdapter(){
public void widgetSelected(SelectionEvent event){

Shell lShell = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell();

boolean isHavingFun = MessageDialog.openQuestion(lShell, "Information", "Are you having fun?");

if(isHavingFun){

MessageDialog.openInformation(lShell, "Information", "You are having fun! Java is awesome.");

}else{

MessageDialog.openWarning(lShell, "Warning", "You are NOT having fun! Go for a walk and get some fresh air.");

}
}
});

lMainViewComposite.setLayout(new RowLayout()); // this sets a Layout for the view's Composite

}

public void setFocus() {}

}


Step 2. Run the application and test if everything worked. Your application should now have a view with a single button that triggers a JFace question message box to pop up, and depending on the boolean value returned, opens up either a Warning or an Information message box:



Piece of Cake!!

Get the code: com.eclipsercptutorials.JFaceMessageBoxes.zip
<--- Previous - Add a Menu to a View in an Eclipse RCP Application
Also see: Eclipse RCP Tutorial Table of Contents
Read more...

Wednesday, May 20, 2009

Add a Menu to a View in an Eclipse RCP Application

This article shows how to add a menu to a View and builds off of a clean RCP Application with a View. The full source code is found at the end of the article. Eclipse RCP applications such as the Eclipse IDE, can have a toolbar and/or, as demonstrated here, a drop down menu located at the top of any View. With just a few lines of code you can easily add a menu to a View. By the way, see the article for adding a Toolbar to a View with this link.

Step 0: Create a Hello World Eclipse RCP Application and add a View to it.

Step 1: Create an Action that defines what will happen when the action in the menu is clicked. Make a new class that extends org.eclipse.jface.action.Action and implements IWorkbenchAction. The class needs a private static final String property used to set the ID in the constructor. Inside the run() method is where you put your custom code. In this "CustomAction" example, code is added to the run() method that opens up a JFace MessageDialog box using a handy static convenience method of the MessageDialog class.

package com.eclipsercptutorials.addviewmenu;

import org.eclipse.jface.action.Action;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.actions.ActionFactory.IWorkbenchAction;

public class CustomAction extends Action implements IWorkbenchAction{

private static final String ID = "com.timmolter.helloWorld.CustomAction";

public CustomAction(){
setId(ID);
}

public void run() {

Shell shell = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell();
String dialogBoxTitle = "Message";
String message = "You clicked the custom action from the menu!";
MessageDialog.openInformation(shell, dialogBoxTitle, message);
}

public void dispose() {}

}


Step 2: Add the menu with its Action and icon to the View. In the View's createPartControl method new-up the CustomAction, and set the Action's tool-tip text and icon. In this example, a .png icon image called "bomb.png" was added to the icons folder in the plugin project. To find out where to find nice icons for Eclipse RCP projects see: Add an Icon to an Eclipse RCP Application View. Add the Action to the View's ToolBarManager using the getViewSite().getActionBars().getMenuManager().add(lCustomAction) method. Here the CustomAction was added to the same menu three times just to fill out the menu a bit, but you would of course add a set of several different Actions. Use a Separator in the menu to organize the Actions.

package com.eclipsercptutorials.addviewmenu;

import org.eclipse.jface.action.Separator;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.ui.part.ViewPart;

public class MainView extends ViewPart {

public static final String ID = "com.eclipsercptutorials.addViewMenu.MainView"; // the ID needs to match the id set in the view's properties

public MainView() { }

public void createPartControl(Composite parent) {

// Custom Action for the View's Menu
CustomAction lCustomAction = new CustomAction();
lCustomAction.setText("Open Dialog Box");
lCustomAction.setImageDescriptor(Activator.getImageDescriptor("icons/bomb.png"));
getViewSite().getActionBars().getMenuManager().add(lCustomAction);
getViewSite().getActionBars().getMenuManager().add(new Separator()); //Add a horizontal separator
getViewSite().getActionBars().getMenuManager().add(lCustomAction);
getViewSite().getActionBars().getMenuManager().add(lCustomAction);

}

public void setFocus() { }

}


Step 3: Run the application and test if everything worked. Your application should now have a View with a menu containing several Actions with a Separator. Clicking on one of the Actions opens up a MessageDialog. If you're not seeing it, nor the View's tab and title for that matter, make sure you specify that the title of the View should be shown in the layout.addStandaloneView() method of the Perspective's createInitialLayout() method - the second argument of the addStandaloneView() should be set to true.

package com.eclipsercptutorials.addviewmenu;

import org.eclipse.ui.IPageLayout;
import org.eclipse.ui.IPerspectiveFactory;

import com.eclipsercptutorials.addviewmenu.MainView;

public class Perspective implements IPerspectiveFactory {

public void createInitialLayout(IPageLayout layout) {

layout.addStandaloneView(MainView.ID, true, IPageLayout.LEFT, 1.0f, layout.getEditorArea());
layout.setEditorAreaVisible(false); //hide the editor in the perspective
}

}




Piece of Cake!!

Get the code: com.eclipsercptutorials.addViewMenu.zip
<--- Previous - Add a Toolbar to a View in an Eclipse RCP Application
---> Next - Using Simple JFace Message Boxes in an Eclipse RCP Application
Also see: Eclipse RCP Tutorial Table of Contents
Read more...

Saturday, May 16, 2009

Add a Toolbar to a View in an Eclipse RCP Application

This article shows how to add a toolbar to a View and builds off of a clean RCP Application with a View. The full source code is found at the end of the article. Eclipse RCP applications such as the Eclipse IDE, can have a drop down menu and/or, as demonstrated here, a toolbar located at the top of any View. With just a few lines of code you can easily add an icon to a View's toolbar and have it activate an Action when clicked. By the way, see the article for adding a Menu to a View with this link.

Step 0: Create a Hello World Eclipse RCP Application and add a View to it.

Step 1: Create an Action that defines what will happen when the icon in the toolbar is clicked. Make a new class that extends org.eclipse.jface.action.Action and implements IWorkbenchAction. The class needs a private static final String property used to set the ID in the constructor. Inside the run() method is where you put your custom code. In this "CustomAction" example, code is added to the run() method that opens up a JFace MessageDialog box using a handy static convenience method of the MessageDialog class.

package com.eclipsercptutorials.addviewtoolbar;

import org.eclipse.jface.action.Action;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.actions.ActionFactory.IWorkbenchAction;

public class CustomAction extends Action implements IWorkbenchAction{

private static final String ID = "com.timmolter.helloWorld.CustomAction";

public CustomAction(){
setId(ID);
}

public void run() {

Shell shell = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell();
String dialogBoxTitle = "Message";
String message = "You clicked something!";
MessageDialog.openInformation(shell, dialogBoxTitle, message);

}

public void dispose() {}

}


Step 2:Add the toolbar with its Action and icon to the View. In the View's createPartControl method new-up the Action, and set the Action's tool-tip text and icon. In this example, a .png icon image called "bomb.png" was added to the icons folder in the plugin project. To find out where to find nice icons for Eclipse RCP projects see: Add an Icon to an Eclipse RCP Application View. Add the Action to the View's ToolBarManager using the getViewSite().getActionBars().getToolBarManager().add(lCustomAction) method.

package com.eclipsercptutorials.addviewtoolbar;

import org.eclipse.swt.widgets.Composite;
import org.eclipse.ui.part.ViewPart;

public class MainView extends ViewPart {

public static final String ID = "com.eclipsercptutorials.addViewToolBar.MainView"; // the ID needs to match the id set in the view's properties

public MainView() { }

public void createPartControl(Composite parent) {

// Custom Action for the View's Menu
CustomAction lCustomAction = new CustomAction();
lCustomAction.setText("Open Dialog Box");
lCustomAction.setImageDescriptor(Activator.getImageDescriptor("icons/bomb.png"));
getViewSite().getActionBars().getToolBarManager().add(lCustomAction);

}

public void setFocus() { }

}

Step 3: Run the application and test if everything worked. Your application should now have a View with an icon in the View's toolbar, which opens up a MessageDialog when clicked. If you're not seeing it, nor the View's tab and title for that matter, make sure you specify that the title of the View should be shown in the layout.addStandaloneView() method of the Perspective's createInitialLayout() method - the second argument of the addStandaloneView() should be set to true.

package com.eclipsercptutorials.addviewtoolbar;

import org.eclipse.ui.IPageLayout;
import org.eclipse.ui.IPerspectiveFactory;

public class Perspective implements IPerspectiveFactory {

public void createInitialLayout(IPageLayout layout) {

layout.addStandaloneView(MainView.ID, true, IPageLayout.LEFT, 1.0f, layout.getEditorArea());
layout.setEditorAreaVisible(false); //hide the editor in the perspective

}
}




Piece of Cake!!

Get the code: com.eclipsercptutorials.addViewToolBar.zip
---> Next - Add a Menu to a View in an Eclipse RCP Application
<--- Previous - Animation in Eclipse RCP Applications - A Bouncing Ball
Also see: Eclipse RCP Tutorial Table of Contents
Read more...

Tuesday, April 21, 2009

Animation in Eclipse RCP Applications - A Bouncing Ball

This article shows how to add animation to an Eclipse RCP Application and builds off of a clean RCP Application with a View. The full source code is found at the end of the article. To demonstrate the animation, code is created that makes an image of the moon bounce around the view, using real physics equations to control the acceleration and spin. If you want a more in depth explanation of adding an image or updating the GUI from a worker thread please see the previous articles: Add an Image to an Eclipse RCP Application and Updating a Widget in an Eclipse RCP Application from a Worker Thread.

Step 0: Create a Hello World Eclipse RCP Application and add a View to it.

Step 1: Add an Image to the view . For this tutorial, an image of the moon with a transparent background called moon.png was prepared and added to the project.


Step 2: Create an inner class that implements Runnable, that updates the contents of the view at a regular interval. Later, during the initialization of the view, this worker thread is started, which calls the update() method of the view every ~15 milliseconds. The speed of the animation can be controlled by the TIMER_INTERVAL variable, which defines how long the thread should sleep before waking up and calling the update() method again.


class AnimatorThread implements Runnable{

// The timer interval in milliseconds
private static final int TIMER_INTERVAL = 14;

public void go(){

Thread t = new Thread(this);
t.start();

}

public void run() {
try {
while(true){
animate();
Thread.sleep(TIMER_INTERVAL);
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}


Step 3: Create the view's contents and start the worker thread. In the createPartControl() method of the view, create a Canvas where the image will be painted. Set the canvas's background color and add a paintListener to it with code defining where the image of the moon should be painted. Finally, new up the worker thread class and start it.


public void createPartControl(Composite parent) {

parent.setBackground(new Color(parent.getDisplay(), 205, 38, 38));

// Create the canvas for drawing
canvas = new Canvas(parent, SWT.DOUBLE_BUFFERED);
canvas.setBackground(new Color(parent.getDisplay(), 0,0,0));
canvas.addPaintListener( new PaintListener() {

public void paintControl(PaintEvent e) {

GC gc = e.gc;
Transform trans = new Transform(e.display );
gc.getTransform( trans );
trans.translate( x, y );
trans.translate( IMAGE_WIDTH / 2f, IMAGE_WIDTH / 2f );
trans.rotate( a );
trans.translate( -IMAGE_WIDTH / 2f, -IMAGE_WIDTH / 2f );
gc.setTransform( trans );
trans.dispose();

gc.drawImage( moon, 0, 0, moon.getBounds().width, moon.getBounds().height, 0, 0, IMAGE_WIDTH, IMAGE_WIDTH); // Draw the moon

}
});

AnimatorThread at = new AnimatorThread();
at.go();
}


Step 4: Create the physics for the bouncing of the ball. Add some constants and variables as private members of the view class and an animate() method which calculates the next position of the moon. Last but not least, force a redraw of the canvas at the end of the animate() method. This invokes the code that was defined in the canvas's PaintListener.


public void animate() {

Display.getDefault().asyncExec(new Runnable(){

public void run(){

try{

float left = x;
float top = y;

// Determine the ball's location
directionY += GRAVITY;
x += directionX;
y += directionY;
a += directionA;

// Determine out of bounds
Rectangle rect = canvas.getClientArea();
if ( x > rect.width - IMAGE_WIDTH ) {
x = rect.width - IMAGE_WIDTH;
directionX = -directionX;
directionA -= ( directionY - directionA ) * FRICTION_WALL;
}
if ( x < 0 ) {
x = 0;
directionX = -directionX;
directionA += ( directionY - directionA ) * FRICTION_WALL;
}

if ( y > rect.height - IMAGE_WIDTH ) {
directionY = (int) ( -GRAVITY * Math.sqrt( ( 1 + 8 * ( rect.height - IMAGE_WIDTH ) / GRAVITY ) ) / 2 );
y = rect.height - IMAGE_WIDTH;
directionA += ( directionX - directionA ) * FRICTION_FLOOR;
}

float right = left + IMAGE_WIDTH;
float bottom = top + IMAGE_WIDTH;
if ( x < left )
left = x;
else
right = x + IMAGE_WIDTH;
if ( y < top )
top = y;
else
bottom = y + IMAGE_WIDTH;

// Force a redraw
canvas.redraw( (int) Math.floor( left ) - 1, (int) Math.floor( top ) - 1, (int) ( Math.ceil( right ) - Math.floor( left ) ) + 2, (int) ( Math.ceil( bottom ) - Math.floor( top ) ) + 2, false );

}catch(SWTException e){
//eat it!
}
}
});

}


Step 5: Run the application and test if everything worked. Your application should now have an image of the moon in the view that bounces back and forth across the view. As you resize the view, the moon's boundaries are recalculated.


Here's the full code of the view:

package com.eclipsercptutorials.animation;

import org.eclipse.swt.SWT;
import org.eclipse.swt.SWTException;
import org.eclipse.swt.events.PaintEvent;
import org.eclipse.swt.events.PaintListener;
import org.eclipse.swt.graphics.Color;
import org.eclipse.swt.graphics.GC;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.graphics.Rectangle;
import org.eclipse.swt.graphics.Transform;
import org.eclipse.swt.widgets.Canvas;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Display;
import org.eclipse.ui.part.ViewPart;

public class MainView extends ViewPart {

public static final String ID = "com.eclipsercptutorials.animation.mainView"; // the ID needs to match the id set in the view's properties

// The image
private Image moon;

// The image width
private static int IMAGE_WIDTH = 85;

// Rate of downward acceleration per frame
private static final float GRAVITY = .25f;

// Coefficient of friction
private static final float FRICTION_FLOOR = 5f / 9f;
private static final float FRICTION_WALL = 5f / 11f;

// The location of the "ball"
private float x = 0;
private float y = 0;
private float a = 0;

// The direction the "ball" is moving
private float directionX = 4;
private float directionY = 0;
private float directionA = 0;

// We draw everything on this canvas
private Canvas canvas;

public MainView() {

moon = Activator.getImageDescriptor("icons/moon.png").createImage();

}

public void createPartControl(Composite parent) {

parent.setBackground(new Color(parent.getDisplay(), 205, 38, 38));

// Create the canvas for drawing
canvas = new Canvas(parent, SWT.DOUBLE_BUFFERED);
canvas.setBackground(new Color(parent.getDisplay(), 0,0,0));
canvas.addPaintListener( new PaintListener() {

public void paintControl(PaintEvent e) {

GC gc = e.gc;
Transform trans = new Transform(e.display );
gc.getTransform( trans );
trans.translate( x, y );
trans.translate( IMAGE_WIDTH / 2f, IMAGE_WIDTH / 2f );
trans.rotate( a );
trans.translate( -IMAGE_WIDTH / 2f, -IMAGE_WIDTH / 2f );
gc.setTransform( trans );
trans.dispose();

gc.drawImage( moon, 0, 0, moon.getBounds().width, moon.getBounds().height, 0, 0, IMAGE_WIDTH, IMAGE_WIDTH); // Draw the moon

}
});

AnimatorThread at = new AnimatorThread();
at.go();
}

public void animate() {

Display.getDefault().asyncExec(new Runnable(){

public void run(){

try{

float left = x;
float top = y;

// Determine the ball's location
directionY += GRAVITY;
x += directionX;
y += directionY;
a += directionA;

// Determine out of bounds
Rectangle rect = canvas.getClientArea();
if ( x > rect.width - IMAGE_WIDTH ) {
x = rect.width - IMAGE_WIDTH;
directionX = -directionX;
directionA -= ( directionY - directionA ) * FRICTION_WALL;
}
if ( x < 0 ) {
x = 0;
directionX = -directionX;
directionA += ( directionY - directionA ) * FRICTION_WALL;
}

if ( y > rect.height - IMAGE_WIDTH ) {
directionY = (int) ( -GRAVITY * Math.sqrt( ( 1 + 8 * ( rect.height - IMAGE_WIDTH ) / GRAVITY ) ) / 2 );
y = rect.height - IMAGE_WIDTH;
directionA += ( directionX - directionA ) * FRICTION_FLOOR;
}

float right = left + IMAGE_WIDTH;
float bottom = top + IMAGE_WIDTH;
if ( x < left )
left = x;
else
right = x + IMAGE_WIDTH;
if ( y < top )
top = y;
else
bottom = y + IMAGE_WIDTH;

// Force a redraw
canvas.redraw( (int) Math.floor( left ) - 1, (int) Math.floor( top ) - 1, (int) ( Math.ceil( right ) - Math.floor( left ) ) + 2, (int) ( Math.ceil( bottom ) - Math.floor( top ) ) + 2, false );

}catch(SWTException e){
//eat it!
}
}
});

}


public void setFocus() {}

class AnimatorThread implements Runnable{

// The timer interval in milliseconds
private static final int TIMER_INTERVAL = 14;

public void go(){

Thread t = new Thread(this);
t.start();

}

public void run() {
try {
while(true){
animate();
Thread.sleep(TIMER_INTERVAL);
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}




Piece of Cake!!

Get the code: com.eclipsercptutorials.animation.zip
<--- Previous - Updating a Widget in an Eclipse RCP Application from a Worker Thread
---> Next - Add a Toolbar to a View in an Eclipse RCP Application
Also see: Eclipse RCP Tutorial Table of Contents

Read more...

Saturday, April 4, 2009

Updating a Widget in an Eclipse RCP Application from a Worker Thread

This article shows how to update an Eclipse RCP Application widget from a worker thread and builds off of a clean RCP Application with a View. When programming GUI applications, it's often necessary to run a background processes to do some calculations or coordinate timed events. If these processes run on the main (GUI) thread, the GUI will be unresponsive to users' clicks during the process, leading to a bad user experience. To get around this problem, worker threads can be created to do the processing, leaving the GUI thread responsive to user input. The catch though is that you can't update any GUI components (SWT or JFace widgets in this case) from the worker thread. If you try to you get an exception such as: Exception in thread "Thread-3" org.eclipse.swt.SWTException: Invalid thread access. And worse, the compiler won't warn you of this pitfall. In this tutorial an Eclipse RCP application with a view is created, and a label is updated every second from a worker thread.

Step 0: Create a Hello World Eclipse RCP Application and add a View to it.

Step 1: Create a worker thread class. The following class called WorkerThread implements Runnable and is passed a reference to the MainView class. In its run method, which must be implemented, a counter is initialized to zero and is incremented by one followed by a one second pause. Right before the incrementation the updateLabelText method in the MainView is called. A go() method is added to the class to create the thread and call the run method.


package com.eclipsercptutorials.workerthread;

class WorkerThread implements Runnable{

// The timer interval in milliseconds
private static final int TIMER_INTERVAL = 1000;

private MainView mainView;

public WorkerThread(MainView mainView){
this.mainView = mainView;
}

public void go(){

Thread t = new Thread(this);
t.start();

}

public void run() {
int counter = 0;
try {
while(mainView != null){
mainView.updateLabelText("Counter = " + counter);
counter++;
Thread.sleep(TIMER_INTERVAL);
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}

Step 2: Add a label to the MainView and start the worker thread in the createPartControl method.

public void createPartControl(Composite parent) {

label = new Label(parent, SWT.None); //new up a Label widget
WorkerThread workerThread = new WorkerThread(this);
workerThread.go();
}

Step 3: Add a method in the MainView class that updates the label's text and is called by the worker thread. The method called updateLabelText in MainView uses the Display's asyncExec method to post a Runnable that is executed in the main thread enabling the update of the Label widget from the worker thread. In the Runnable's run method make sure the widget isn't null or disposed first.

package com.eclipsercptutorials.workerthread;

import org.eclipse.swt.SWT;
import org.eclipse.swt.SWTException;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Label;
import org.eclipse.ui.part.ViewPart;

public class MainView extends ViewPart {

public static final String ID = "com.eclipsercptutorials.workerThread.mainView"; // the ID needs to match the id set in the view's properties

public Label label;

public MainView() {}

public void createPartControl(Composite parent) {

label = new Label(parent, SWT.None); //new up a Label widget
WorkerThread workerThread = new WorkerThread(this);
workerThread.go();
}

public void setFocus() {}

public void updateLabelText(final String labelText){

try{
Display.getDefault().asyncExec(new Runnable(){
public void run(){
if(!label.isDisposed() && label !=null){
label.setText(labelText);
}
}
});
}catch(SWTException e){
//eat it!
}
}
}


Step 3: Run the application and test if everything worked. Your application should now have a label in the view that updates its value each second and look something like this:
Piece of cake!!

Get the code: com.eclipsercptutorials.workerThread.zip
<--- Previous - Add an Image to an Eclipse RCP Application
---> Next - Animation in Eclipse RCP Applications - A Bouncing Ball
Also see: Eclipse RCP Tutorial Table of Contents
Read more...

Sunday, March 29, 2009

Add an Image to an Eclipse RCP Application

This article shows how to add an image to a view in an Eclipse RCP application and builds off of a clean RCP Application with a View. Images used in an RCP application are managed by an ImageRegistry that is global to the scope of a plugin. If your project has a class that extends AbstractUIPlugin, then there is a static method you can use called getImageDescriptor() to access ImageDescriptors given a path to the image. The Activator class ectending AbstractUIPlugin is automatically generated if you used the wizard to create a Hello World Eclipse RCP Application. The ImageRegistery is the preferred means of handling images in your application because it handles the lazy loading of the images and disposes of them properly when needed. The image is added to a view by adding a canvas to the view's parent composite and adding the image from the image descriptor to the canvas through its addPaintListener method. It may sound confusing, but in practice it's really simple.

Step 0: Create a Hello World Eclipse RCP Application and add a View to it.

Step 1: Add the image into the RCP plugin project. In this example an image called moon.png is added to the "icons" folder inside the plugin project. Whether you use this folder or not is really not important - you can organize your images any way you want. In the next step, the path to the image's location is used to get the image.


Step 2: Add the image to the view. In the view's class where you want the image to appear, add a global Image field and set it in the view's constructor calling the Activator.getImageDescriptor("icons/moon.png").createImage(); method. Adjust the path accordingly to locate your image. The path is relative to the plugin. In the createPartControl method, add a Canvas to the view's parent Composite and define its PaintEvent to draw the image. In the drawImage method, give it the image and the x and y coordinates where it should be drawn.


package com.eclipsercptutorials.addimagetoview;

import org.eclipse.swt.SWT;
import org.eclipse.swt.events.PaintEvent;
import org.eclipse.swt.events.PaintListener;
import org.eclipse.swt.graphics.GC;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.widgets.Canvas;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.ui.part.ViewPart;

public class MainView extends ViewPart {

public static final String ID = "com.eclipsercptutorials.addimagetoview.mainView"; // the ID needs to match the id set in the view's properties

private Image image;

public MainView() {

image = Activator.getImageDescriptor("icons/moon.png").createImage();
}

@Override
public void createPartControl(Composite parent) {

// Create the canvas for drawing
Canvas canvas = new Canvas( parent, SWT.NONE);
canvas.addPaintListener( new PaintListener() {
public void paintControl(PaintEvent e) {
GC gc = e.gc;
gc.drawImage( image,10,10); // Draw the moon
}
});
}


public void setFocus() {}

}



Step 3: Run the application and test if everything worked. Your application should now have an image in the view and look something like this:

Piece of cake!!

Get the code: com.eclipsercptutorials.addimagetoview.zip
<--- Previous - Import and Export an Eclipse RCP Application Project
---> Next - Updating a Widget in an Eclipse RCP Application from a Worker Thread
Also see: Eclipse RCP Tutorial Table of Contents
Read more...

Monday, March 23, 2009

Import and Export an Eclipse RCP Application Project

This article shows how to import and export an Eclipse RCP application to and from the Eclipse IDE workbench. Importing is necessary for example, when you want to download a sample RCP project from the internet and run it yourself. Also, you may need to export your RCP project if you are working on a team of developers and you need to get your code to someone. Importing and exporting an RCP project is easily done by following these steps.


Import

Step 0: Download, transfer and/or locate the RCP project. If you need a practice RCP project, here's on for you: com.eclipsercptutorials.addMenu.zip. If you download this, you'll need to unzip it. Or you can download any of the projects found at the end of most of the tutorials on this website.


Step 1: Choose File ---> Import. Or right click somewhere in the package explorer to find the import action.


Step 2: On the first page of the Import wizard choose "Existing Projects into Workspace" in the "General" folder. Click Next.
Step 3: On the second page of the Import wizard choose browse for and select the project folder you want to import. Check "Copy projects into workspace". Click Finish. The project now appears in the package explorer!
Export

Step 0: Right-click on the project you'd like to export and choose "Export".

Step 1: On the first page of the Export wizard choose "File System" in the "General" folder. Click Next.
Step 2: On the second page of the Export wizard click on "Browse..." and select the location where you want to export the project. Click Finish. The project is now exported! Now you can zip up the project folder and email it or archive it for example.

Piece of cake!!

<--- Previous - Verify User Intent Before Closing an Eclipse RCP Application
---> Next - Add an Image to an Eclipse RCP Application
Also see: Eclipse RCP Tutorial Table of Contents
Read more...

Sunday, March 22, 2009

Verify User Intent Before Closing an Eclipse RCP Application

This article shows how ask the user if s/he really intends to close a RCP application and builds off of a clean Hello World Eclipse RCP Application. Use this feature sparingly with your applications because it can be an annoying "feature". The best solution would be to add a preference to the application where the user could decide if s/he wanted the reminder or not. Look for a tutorial on how to ad the preferences soon.

Step 0: Create a HelloWorld RCP application.

Step 1: Add code to create the dialog box when the close application action is triggered. In the ApplicationWorkbenchAdvisor class that was automatically generated during step 0, you need to override the preShutdown() method. The method returns a boolean where, if true, the application will shut down, and if false, the application will continue running. You need to add code in that method that opens up a dialog box, gets user input, and returns what the user selected. Eclipse's JFace library contains a nice little class called MessageDialog where we can easily make a dialog box pop up, ask a question, and get the yes/no answer. We use the MessageDialog.openQuestion() method and pass it three parameters: a Shell, the dialog box's title, and the question we want to ask.


package com.eclipsercptutorials.verifyintent;

import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.application.IWorkbenchWindowConfigurer;
import org.eclipse.ui.application.WorkbenchAdvisor;
import org.eclipse.ui.application.WorkbenchWindowAdvisor;

public class ApplicationWorkbenchAdvisor extends WorkbenchAdvisor {

private static final String PERSPECTIVE_ID = "com.eclipsercptutorials.verifyIntent.perspective";

public WorkbenchWindowAdvisor createWorkbenchWindowAdvisor(IWorkbenchWindowConfigurer configurer) {
return new ApplicationWorkbenchWindowAdvisor(configurer);
}

public String getInitialWindowPerspectiveId() {
return PERSPECTIVE_ID;
}


public boolean preShutdown(){

Shell shell = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell();
String dialogBoxTitle = "Question";
String question = "Are you sure you want to close this application?";
return MessageDialog.openQuestion(shell, dialogBoxTitle, question);

}

}


Step 2: Run the application and test if everything worked. Your application should now have a dialog box that verifies user intent when the application is closed and look something like this:


Piece of Cake!

Get the code: com.eclipsercptutorials.verifyIntent.zip
---> Next - Import and Export an Eclipse RCP Application Project
<--- Previous - Add a Custom Menu Action to an Eclipse RCP Application
Also see: Eclipse RCP Tutorial Table of Contents
Read more...

Add a Custom Menu Action to an Eclipse RCP Application

This article shows how to add a custom menu item to a menu in an Eclipse RCP application and builds off of a clean Hello World Eclipse RCP Application. As shown in the article Add a Menu to an Eclipse RCP Application, it is very easy to add a File menu containing the Exit action. Here a custom menu action is added to the File menu that opens a dialog box when clicked.

Step 0: Create a HelloWorld RCP application.

Step 1: Make the custom action. Create a new class that extends org.eclipse.jface.action.Action and implements IWorkbenchAction. The class needs a private static final String property used to set the ID in the constructor. Inside the run() method is where you put your custom code. In this example, code is added that opens up a message dialog box.

package com.eclipsercptutorials.customaction;

import org.eclipse.jface.action.Action;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.actions.ActionFactory.IWorkbenchAction;

public class CustomAction extends Action implements IWorkbenchAction{

private static final String ID = "com.timmolter.helloWorld.CustomAction";

public CustomAction(){
setId(ID);
}

public void run() {

Shell shell = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell();
String dialogBoxTitle = "Message";
String message = "You clicked the custom action from the menu!";
MessageDialog.openInformation(shell, dialogBoxTitle, message);
}

public void dispose() {}

}
Step 2: In the ApplicationActionBarAdvisor class add the CustomAction as a private field. In the makeActions() method, new up the custom action, set its text and accelerator and register it. The accelerator is of course optional and it simply adds a keyboard shortcut, in this case CTRL+T. In the fillMenuBar() method, add the action to a File Menu.

package com.eclipsercptutorials.customaction;

import org.eclipse.jface.action.IMenuManager;
import org.eclipse.jface.action.MenuManager;
import org.eclipse.swt.SWT;
import org.eclipse.ui.IWorkbenchWindow;
import org.eclipse.ui.application.ActionBarAdvisor;
import org.eclipse.ui.application.IActionBarConfigurer;

public class ApplicationActionBarAdvisor extends ActionBarAdvisor {

private CustomAction customAction;

public ApplicationActionBarAdvisor(IActionBarConfigurer configurer) {
super(configurer);
}

protected void makeActions(IWorkbenchWindow window) {

//Custom action
customAction = new CustomAction();
customAction.setText("Do custom action!");
customAction.setAccelerator(SWT.CTRL + 'T');
register(customAction);
}

protected void fillMenuBar(IMenuManager menuBar) {

MenuManager fileMenu = new MenuManager("&File", "file"); //create a menuManager to take care of all submenus in "File"
fileMenu.add(customAction); //Add the "customAction" action
menuBar.add(fileMenu); //Add the "File" menu to the menuBar
}

}
Step 3: Run the application and test if everything worked. Your application should now have a File Menu containing a custom action:


When the custom action is clicked or CTRL+T is entered, a messaage box should come up:
Piece of cake!

Get the code: com.eclipsercptutorials.customAction.zip
---> Next - Verify User Intent Before Closing an Eclipse RCP Application
<--- Previous - Add Nested Menu Items to an Eclipse RCP Application
Also see: Eclipse RCP Tutorial Table of Contents
Read more...

Saturday, March 21, 2009

Add Nested Menu Items to an Eclipse RCP Application

This article shows how to add nested menu items to a menu in an Eclipse RCP application and builds off of a clean Hello World Eclipse RCP Application. As shown in the article Add a Menu to an Eclipse RCP Application, it is very easy to add a File menu containing the Exit action. Here the Exit action as well as About and Preferences are added to a submenu called Expand in the File menu to demonstrate nested menu items.

Step 0: Create a HelloWorld RCP application.

Step 1: Add the nested menu actions. Open up the ApplicationActionBarAdvisor class and add the three About, Preferences, and Exit actions as private fields. In makeactions(), define the actions and register them. In the fillMenuBar() method, create two instances of MenuManager, one for the File and one for Expand. Add the three actions to the Expand MenuManager. A Separator is added before the Exit action for the sake of demonstrating this nice menu organizing feature. Next add the Expand MenuManager to the File MenuManager. Finally add the File MenuManager to the menubar.

package com.eclipsercptutorials.nestedmenu;

import org.eclipse.jface.action.IMenuManager;
import org.eclipse.jface.action.MenuManager;
import org.eclipse.jface.action.Separator;
import org.eclipse.ui.IWorkbenchWindow;
import org.eclipse.ui.actions.ActionFactory;
import org.eclipse.ui.actions.ActionFactory.IWorkbenchAction;
import org.eclipse.ui.application.ActionBarAdvisor;
import org.eclipse.ui.application.IActionBarConfigurer;

public class ApplicationActionBarAdvisor extends ActionBarAdvisor {

private IWorkbenchAction aboutAction;
private IWorkbenchAction preferencesAction;
private IWorkbenchAction exitAction;

public ApplicationActionBarAdvisor(IActionBarConfigurer configurer) {
super(configurer);
}

protected void makeActions(IWorkbenchWindow window) {

//ActionFactory Actions, the ActionFactory defines a set of common actions and can be used in our application.
aboutAction = ActionFactory.ABOUT.create(window);
register(aboutAction); //register the action so it is deleted when the Workbench window is closed
preferencesAction = ActionFactory.PREFERENCES.create(window);
register(preferencesAction);
exitAction = ActionFactory.QUIT.create(window);
register(exitAction);
}

protected void fillMenuBar(IMenuManager menuBar) {

MenuManager fileMenu = new MenuManager("&File", "file"); //create a menuManager to take care of all submenus in "File"

MenuManager expandingMenu = new MenuManager("&Expand", "expand");
expandingMenu.add(aboutAction); //Add the "about" action
expandingMenu.add(preferencesAction); //Add the "preferences" action
expandingMenu.add(new Separator()); //Add a horizontal separator
expandingMenu.add(exitAction); //Add the "exit" action

fileMenu.add(expandingMenu); //Add the expanding menu to the "File" menu
menuBar.add(fileMenu); //Add the "File" menu to the menuBar
}

}
Step 2: Run the application and test if everything worked. Your application should now have a new menu containing a group of actions nested in a parent menu:



Piece of cake!

Get the code: com.eclipsercptutorials.nestedmenu.zip
---> Next - Add a custom Menu Action to an Eclipse RCP Application
<--- Previous - Add a Menu to an Eclipse RCP Application
Also see: Eclipse RCP Tutorial Table of Contents

Read more...
Wanted: your Eclipse RCP tips and tricks. We created this website as a place to give back to the Eclipse open source community by offering people help in developing their own Rich Client Platform (RCP) applications. We hope you find value in the tutorials found here. Visit the share page for information on how to contribute a unique RCP Application tutorial or code snippet and give back to the community! The style of the tutorials are designed to be quick and easy to create by contributors and to understand by the people learning from them. Import the RCP projects found at the end of the tutorials and export your contributed projects as shown in Import and Export an Eclipse RCP Application Project.


Enter your email address to automatically
receive the newest articles:

 

Eclipse RCP Tutorials - beta Copyright © 2009