Posts Tagged ‘SWT’

WindowBuilder with Eclipse 4.2 / 3.8 (Linux)

Saturday, January 14th, 2012

Currently, if you trying to use WindowBuilder under Linux with Eclipse 3.8 / Eclipse 4.2, it renders incorrectly.

Add the following line to the end of your eclipse.ini file to fix this:

-Dorg.eclipse.swt.internal.gtk.useCairo=false

This is a small bug in SWT and properly will be fixed soon. See Bug Report for details.

Eclipse SWT – Creating an email in the default email client

Tuesday, August 30th, 2011

As many of you properly know SWT has the nice Program.launch() method which allows to start programs associated with an URI.

Example:

// This works for Windows
	public void openMailWindows(String to, String subject,String body, List<File> attachments) {
		String mailto = "mailto:" + enc(to) + "?subject=" + enc(subject) + "&body=" + enc(body);
		for (File f : attachments) {
			mailto += "&attach=" + f.getAbsolutePath();
		}
		Program.launch(mailto);
	}

	private String enc(String p) {
		if (p == null)
			p = "";
		try {
			return URLEncoder.encode(p, "UTF-8").replace("+", "%20");
		} catch (UnsupportedEncodingException e) {
			throw new RuntimeException();
		}
	}

Unfortunately this does not seem to be working on Linux. So if you are working under Linux you have to use the Java runtime directly. Unfortunately this requires you in my humble opinion to code against a a specific application.

// This works for Linux with Thunderbird
	public void openMailLinux(String to, String subject,String body, List<File> attachments) {
		String mailto = "mailto:" + enc(to) + "?subject=" + enc(subject) + "&body=" + enc(body);
		for (File f : attachments) {
			mailto += "&attach=" + f.getAbsolutePath();
		}
		Program.launch(mailto);
		try {
			// For using the parameters check the following description
			// http://kb.mozillazine.org/Command_line_arguments_%28Thunderbird%29
			Runtime.getRuntime().exec("thunderbird -compose");
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

I hope this helps.

You find me also on Twitter and Google+.

SWT Style Bits – Bitwise Or and Bitwise And

Tuesday, January 25th, 2011

Ever wondered how SWT Style bits work? It is actually very simple. The style bits are a multitud of 2

SWT.NONE = 0, // 00000000 binary
SWT.MULTI = 2, // 00000010 binary
SWT.SINGLE = 4; // 00000100 binary
SWT.READ_ONLY = 8; // 00001000 binary

Via the bitwise OR operator | you combine the bits

SWT.NONE | SWT.MULTI | SWT.READ_ONLY results in 00001010

To get later the information if a bit was set use the bitwise AND operation &.

if (SWT.WRAP==(result & SWT.WRAP)){
System.out.println(“SWT.WRAP available”);
}

Here is a small code snippets to run a little test.


package de.vogella.swt.widgets;

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

public class SWTbitwiseOr {
	public static void main(String[] args) {
		Display display = new Display();
		Shell shell = new Shell(display);
		new Text(shell, SWT.NONE);
		System.out.println(SWT.NONE);
		System.out.println(SWT.MULTI);
		System.out.println(SWT.SINGLE);
		System.out.println(SWT.READ_ONLY);
		System.out.println(SWT.WRAP);
		System.out.println(SWT.SEARCH);
		System.out.println(SWT.ICON_CANCEL);
		System.out.println(SWT.ICON_SEARCH);
		System.out.println(SWT.LEFT);
		System.out.println(SWT.RIGHT);
		System.out.println(SWT.PASSWORD);
		System.out.println(SWT.CENTER);

		// Lets see what we have 

		int result = SWT.MULTI | SWT.WRAP;
		System.out.println(result);
		if (SWT.MULTI==(result & SWT.MULTI)){
			System.out.println("SWT.MULI available");
		}
		if (SWT.WRAP==(result & SWT.WRAP)){
			System.out.println("SWT.WRAP available");
		}
		if (SWT.SINGLE==(result & SWT.SINGLE)){
			System.out.println("SWT.SINGLE available");
		} else {
			System.out.println("SWT.SINGLE available");
		}

	}
}

For more information please see Bitwise Operators.

If you are located in Germany you may be interested in my Eclipse RCP training which I deliver together with Ralf Ebert.

Browser Tales – Java to JavaScript and vice versa with the SWT Browser Widget

Monday, December 21st, 2009

The SWT Browser widget makes it very easy to run HTML and JavaScript within Eclipse. This widget encapsulates a browser (system dependent) into a SWT widget.

The following screenshot is from the second example below. This example is based on a blog entry from Ian Bull and SWT Snippet 307.

swtexample

The following coding will be defining views for Eclipse RCP or via Eclipse plugins so I assume you are familiar with these topics.

Lets start with a simple example. Via the following coding you can setup a View in your Eclipse RCP and inject some JavaScript from your Java Code.

package de.vogella.javascript.simple;

import org.eclipse.swt.SWT;
import org.eclipse.swt.browser.Browser;
import org.eclipse.swt.browser.ProgressEvent;
import org.eclipse.swt.browser.ProgressListener;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.ui.part.ViewPart;

public class View extends ViewPart {
	public static final String ID = "de.vogella.javascript.simple.view";

	public void createPartControl(Composite parent) {
		// You need XULRunner installed to use this line
//		final Browser b = new Browser(parent, SWT.MOZILLA);
		final Browser b = new Browser(parent, SWT.NONE); // Uses IE on MS Windows
		b.setUrl("http://www.vogella.de");
		b.addProgressListener(new ProgressListener() {
			@Override
			public void completed(ProgressEvent event) {
				System.out.println("Page loaded");
				try {
					Thread.sleep(2000);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
				// Execute JavaScript in the browser
				b.execute("alert(\"JavaScript, called from Java\");");
			}
			@Override
			public void changed(ProgressEvent event) {
			}
		});
	}

	/**
	 * Passing the focus request to the viewer's control.
	 */
	public void setFocus() {
	}
}

The next example is a bit more complex (it is the example from the screenshot). This demonstarte how JavaScript can also call back to your Java Code.


package de.vogella.javascript.maps;

import java.io.File;

import org.eclipse.swt.SWT;
import org.eclipse.swt.browser.Browser;
import org.eclipse.swt.browser.BrowserFunction;
import org.eclipse.swt.custom.SashForm;
import org.eclipse.swt.events.ControlEvent;
import org.eclipse.swt.events.ControlListener;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.List;
import org.eclipse.ui.part.ViewPart;

public class View extends ViewPart {

	public static final String ID = "de.vogella.javascript.maps.view";
	private static List list;

	public void createPartControl(Composite parent) {
		SashForm sash = new SashForm(parent, SWT.HORIZONTAL);

		File f = new File("C:/temp/demofile/map.html");
		final Browser browser = new Browser(parent, SWT.NONE); // Uses IE on MS

		browser.addControlListener(new ControlListener() {
			public void controlResized(ControlEvent e) {
				// Use Javascript to set the browser width and height
				browser
						.execute("document.getElementById('map_canvas').style.width= "
								+ (browser.getSize().x - 20) + ";");
				browser
						.execute("document.getElementById('map_canvas').style.height= "
								+ (browser.getSize().y - 20) + ";");
			}

			public void controlMoved(ControlEvent e) {
			}
		});

		 new CustomFunction (browser, "theJavaFunction");

		    Composite c = new Composite(sash, SWT.BORDER);
		    c.setLayout(new GridLayout(2, true));
		    Button b = new Button(c, SWT.PUSH);
		    b.setText("Where Am I ?");
		    b.addSelectionListener(new SelectionAdapter() {
		        public void widgetSelected(SelectionEvent e) {
		            double lat = ((Double) browser.evaluate("return map.getCenter().lat();")).doubleValue();
		            double lng = ((Double) browser.evaluate("return map.getCenter().lng();")).doubleValue();
		            list.add(lat + " : " + lng);
		        }
		    });

		    Button addMarker = new Button(c, SWT.PUSH);
		    addMarker.setText("Add Marker");
		    addMarker.addSelectionListener(new SelectionAdapter() {
		        public void widgetSelected(SelectionEvent e) {
		            browser.evaluate("createMarker();");

		        }
		    });
		    list = new List(c, SWT.BORDER | SWT.V_SCROLL | SWT.H_SCROLL);
		    GridData gridData = new GridData(SWT.FILL, SWT.FILL, true, true);
		    gridData.horizontalSpan=2;
		    list.setLayoutData(gridData);

		    browser.setUrl(f.toURI().toString());
//		    sash.setWeights(new int[] {4,1});
	}

	/**
	 * Passing the focus request to the viewer's control.
	 */
	public void setFocus() {

	}

	 // Called by JavaScript
	 class CustomFunction extends BrowserFunction {
	    CustomFunctionData data = new CustomFunctionData(null);

		CustomFunction (Browser browser, String name) {
	        super (browser, name);
	        this.data.browser = browser;
	    }
	    public Object function (Object[] arguments) {
	        double lat = ((Double) arguments[0]).doubleValue();
	        double lng = ((Double) arguments[1]).doubleValue();
	        list.add(lat + " : " + lng);
	        data.browser.execute("document.getElementById('map_canvas').style.width= "+ (data.browser.getSize().x - 20) + ";");
	        data.browser.execute("document.getElementById('map_canvas').style.height= "+ (data.browser.getSize().y - 20) + ";");
	        return null;
	    }
	 }
}

The coding above reads a HTML (with some JavaScript code) file “C:/temp/demofile/map.html”. If you save it somewhere else you need to adjust line 28 in the coding above.

<!DOCTYPE html "-//W3C//DTD XHTML 1.0 Strict//EN" 

 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">

  <head>

    <meta http-equiv="content-type" content="text/html; charset=utf-8"/>

    <title>Google Maps JavaScript API Example</title>

    <script src="http://maps.google.com/maps?file=api&amp;v=2&amp;key=abcdefg&sensor=false"
            type="text/javascript"></script>
    <script type="text/javascript">

	var map;

    function initialize() {
      if (GBrowserIsCompatible()) {
        map = new GMap2(document.getElementById("map_canvas"));
        map.setCenter(new GLatLng(37.4419, -122.1419), 13);
        map.setUIToDefault();

		// Callback to Java from JavaScript
	    theJavaFunction(map.getCenter().lat(), map.getCenter().lng());

      }

    }

    function createMarker(){
		var lat = map.getCenter().lat();
		var lng = map.getCenter().lng();
        var point = new GLatLng(lat,lng);
		var d=new Date();

		var marker = new GMarker(point, {draggable: true});

		GEvent.addListener(marker, "dragstart", function() {
			map.closeInfoWindow();
		});

		GEvent.addListener(marker, "dragend", function() {
		});

		map.addOverlay(marker);
		addMassiveData();

    }

	function addMassiveData(){
	// Add 10 markers to the map at random locations
		var bounds = map.getBounds();
        var southWest = bounds.getSouthWest();
        var northEast = bounds.getNorthEast();
        var lngSpan = northEast.lng() - southWest.lng();
        var latSpan = northEast.lat() - southWest.lat();
        for (var i = 0; i < 100; i++) {
         var point = new GLatLng(southWest.lat() + latSpan * Math.random(),
               southWest.lng() + lngSpan * Math.random());
        map.addOverlay(new GMarker(point));
		}
	}

    </script>

  </head>

  <body onload="initialize()" >

    <div id="map_canvas" style="width: 600px; height: 400px"></div>

  </body>

</html>

This should demonstrate how easy you can integrate HTML and JavaScript into Eclipse. This is something the Eclipse E4 OpenSocial Gadget project also targets.

Check it out! The Open Social Gadgets with Eclipse E4 – Tutorial tries to give a little introduction.

JavaScript in the SWT Browser widget

Thursday, October 29th, 2009

At the Eclipse Summit Europe I listened to a talk of Boris Bokowski about Eclipse and the Web.

Among other things I learned that you can execute JavaScript directly on the SWT Browser Widget and I wanted to give a tiny example for this.

This Eclipse view will for example load my webpage and then execute a tiny JavaScript (alert(“1″);) in the browser.


package de.vogella.swtbrowser;

import org.eclipse.swt.SWT;
import org.eclipse.swt.browser.Browser;
import org.eclipse.swt.browser.ProgressEvent;
import org.eclipse.swt.browser.ProgressListener;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.ui.part.ViewPart;

public class View extends ViewPart {

	public static final String ID = "de.vogella.swtbrowser.view";

	public void createPartControl(Composite parent) {
		final Browser b = new Browser(parent, SWT.NONE);
		b.setUrl("www.vogella.de");
		b.addProgressListener(new ProgressListener() {
			@Override
			public void completed(ProgressEvent event) {
				System.out.println("Page loaded");
				System.out.println(b.execute("alert(\"1\");"));
			}
			@Override
			public void changed(ProgressEvent event) {
			}
		});
	}

	/**
	 * Passing the focus request to the viewer's control.
	 */
	public void setFocus() {
	}
}

Thanks to Boris for the great talk.

SWT – Putting a file into the clipboard

Friday, September 4th, 2009

I recently got the question how you can put a file into the system clipboard.

SWT makes this trivial:


package de.vogella.desktop.clipboard;

import org.eclipse.swt.dnd.Clipboard;
import org.eclipse.swt.dnd.FileTransfer;
import org.eclipse.swt.dnd.Transfer;
import org.eclipse.swt.widgets.Display;

/**
 * Utility class for putting files into the system clipboard
 *
 * @author Lars Vogel
 */

public final class CopyFileToClipboard {

	private CopyFileToClipboard() {
		// Utility class, prevent instantiation
	}

	/**
	 * Copy a file into the clipboard
	 * Assumes the file exists -> no additional check
	 * @param fileName - includes the path
	 */

	public static void copytoClipboard(String fileName) {
		Display display = Display.getCurrent();
		Clipboard clipboard = new Clipboard(display);
		String[] data = { fileName };
		clipboard.setContents(new Object[] { data },
				new Transfer[] { FileTransfer.getInstance() });
		clipboard.dispose();
	}
}

Afer calling the method with a correct filename you should be able to paste the file, e.g. Strg+V into your system file browser.


Switch to our mobile site