The SWT FAQ
The SWT FAQ
If you have questions you believe should go in here, please let us know on
the SWT developer mailing list.
- Q: What packages make up SWT?
- A: Package names in SWT begin with the prefix org.eclipse.swt.
Here is the complete list:
org.eclipse.swt
org.eclipse.swt.accessibility
org.eclipse.swt.awt
org.eclipse.swt.browser
org.eclipse.swt.custom
org.eclipse.swt.dnd
org.eclipse.swt.events
org.eclipse.swt.graphics
org.eclipse.swt.internal.* (Not API, do not reference classes in these packages)
org.eclipse.swt.layout
org.eclipse.swt.opengl
org.eclipse.swt.ole.win32 (Windows only)
org.eclipse.swt.printing
org.eclipse.swt.program
org.eclipse.swt.widgets
Classes that are not in these packages do not belong to SWT.
- Q: Does SWT support JavaBeans?
- A: To the extent that it makes sense, given the constraints of operating system
compatibility, SWT mirrors the beans behavior. An example of this is the use
of standard beans mechanisms for event dispatch (EventListener, EventObject and adapter
classes). Some aspects of the beans paradigm, such as the ability to create beans with
null constructors, run counter to the constraints of the underlying operating systems
that SWT runs on. For example, operating systems do not typically support creating a
widget without specifying its parent.
The essence of the problem is that if you allow a widget to be created with a null
constructor, then you can't actually create the o/s resources at the time the constructor
runs (you would have to wait until later, after the parent has been set). We can not
do this, since we always create the o/s resources in the constructor, and for
performance/efficiency/consistency reasons do not keep slots in the object to hold
whatever state would be required if the object were to be created later.
- Q: Is there a GUI Builder for SWT?
- A: SWT itself does not provide a GUI Builder (also known as "GUI Designer", "GUI Editor",
"Visual Builder", "Visual Designer", "Visual Editor", or "Visual Composition Editor").
However, there is an Eclipse project called WindowBuilder
which integrates an SWT GUI Designer. There are several other mature 'third-party' products listed at
http://http://www.zjjv.com///. Search for "GUI Builder".
- Q: What is a snippet and why do I care?
- A: A snippet is a minimal stand alone program that demonstrates functionality or
lack of functionality.
Why is this important? Posting a snippet to the news group is the
quickest way to get help. Including a snippet in a bug report is the fastest
way to get a bug fixed. Taking the time to construct a snippet helps you understand
the API of the library you are calling and focuses your thinking. For example, the
SWT team uses C and Java snippets internally to prove or disprove problems in the operating system.
Often, something you think is a bug is actually caused by something elsewhere
in your program.
Snippets isolate problems. Code speaks louder than words.
Here is a minimal stand alone SWT program to help you get started:
public static void main (String [] args) {
Display display = new Display ();
Shell shell = new Shell (display);
shell.open ();
while (!shell.isDisposed ()) {
if (!display.readAndDispatch ()) display.sleep ();
}
display.dispose ();
}For a list of sample snippets, see the SWT snippets page.
- Q: Where do I find the SWT source?
- A: SWT's source can be retrieved directly from GIT as described in Using SWT from GIT. It's also included
in eclipse as follows:
eclipse 3.4 and newer:
plugins/org.eclipse.swt.<ws>.<os>.<arch>.source_X.X.X.<version>.jar
eclipse 3.3.2 and earlier: directory
plugins/org.eclipse.rcp.source.<os>.<ws>.<arch>_X.X.X.<version>/src/
- Q: How do I build an SWT jar for my platform?
- A: The SWT jar can be built from the eclipse GIT repository using an Ant task:
Retrieve SWT directly from GIT as described in Using SWT from GIT
Load the projects org.eclipse.swt and org.eclipse.swt.WS.OS.ARCH where WS.OS.ARCH are the names of the
windowing system, operating system and architecture of interest, respectively. For example, org.eclipse.swt.gtk.linux.x86.
In the project org.eclipse.swt.WS.OS.ARCH, locate the file build.xml. This is an Ant script.
Run Ant on the target build.jars. If you are using eclipse as your development environment, you can run
Ant by selecting the file in the Navigator or Packages view, then selecting Run Ant... from the context
menu.
The script will create file swt.jar in the root directory of the org.eclipse.swt.WS.OS.ARCH
project. When it has finished running you can Refresh this project to bring this jar into your eclipse workspace.
- Q: How do I build the SWT Eclipse plug-in for my platform?
- A: The SWT Eclipse plug-in can be built (excluding the signing of the jar) with the steps below.
Retrieve SWT directly from GIT as described in Using SWT from GIT
Load the projects org.eclipse.swt and org.eclipse.swt.WS.OS.ARCH where WS.OS.ARCH are the names of the windowing system, operating system and architecture of interest, respectively. For example, org.eclipse.swt.gtk.linux.x86.
(optional) If you wish to compile SWT in your workspace, in the Navigator view rename the org.eclipse.swt project's .classpath_WS
file to .classpath. This is useful if, for instance, you have a patch to apply to the SWT codebase before building the plug-in.
Invoke the File > Export... menu item, then select the "Plug-in Development" - "Deployable Plug-ins and Fragments" wizard, and press Next.
In the resulting wizard's plug-ins list, select the org.eclipse.swt.WS.OS.ARCH fragment.
Specify a destination for the output.
On the Options tab set the qualifier to the plug-in's desired qualifier string. This will be something like v3655 and must match the
qualifier of Eclipse's SWT plug-in that is being replaced.
Press Finish to export the plug-in.
Important note: Once the plug-in has been exported, the intermediate files that were created in order to make the plug-in jar are not deleted.
As a result, subsequent exports of the same plug-in will NOT recompile the workspace contents, and therefore will not contain any changes that have
been made in the interim. For such changes to be included in a re-export of the plug-in, these intermediate files must be deleted in order to force
their recompilation. The easiest way to do this is to select the org.eclipse.swt.WS.OS.ARCH project, press F5 to refresh it, and
then replace its content with the released content.
- Q: How do I build the SWT JNI libraries for my platform?
- A: SWT uses JNI to interact with the native widgets in the
operating system. The SWT JNI libraries must be compiled for the
windowing system, operating system and hardware architecture of
interest. The libraries can be built either from the code in the GIT
repository or from an eclipse SDK download.
In order to build the required libraries and run Eclipse, you
will require a JDK (Java Development Kit) version that is supported
by Eclipse. Check eclipse.org for details.
Building the SWT JNI libraries from the eclipse SDK download:
Download an Eclipse distribution from
http://http://www.zjjv.com///downloads/index.php.
Unzip the distribution. This will create a directory called eclipse.
This directory is subsequently referred to as <eclipseRoot>.
Copy file <eclipseRoot>/plugins/org.eclipse.swt.<ws>.<os>.<arch>.source_X.X.X.<versionString>.zip
to another directory and unzip it.
Edit the file build.sh (or build.bat on Windows)
in the current directory. Set the environment variables defined in that file to
match the location of your JRE, etc. Save the file and close it.
Run the build command (sh build.sh for UNIX and Linux
platforms, build.bat for Windows). This will create the appropriate
library file(s) in the current directory. For example, this will create
swt-XXXX.dll files on windows, or libswt-XXXX.so files on Linux
and Solaris.
This description was originally contributed by Colin R Devilbiss.
Building the SWT JNI libraries from the eclipse GIT repository:
NOTE: These instructions require you to use Eclipse
Follow these instructions to get SWT from GIT.
Compile the project. This will create a folder called bin under the org.eclipse.swt project.
Change directory into org.eclipse.swt/bin/library
Edit the file build.sh (or build.bat on Windows)
in the current directory. Set the environment variables defined in that file to
match the location of your JRE, etc. Save the file and close it.
Run the build command (sh build.sh for UNIX and Linux
platforms, build.bat for Windows). This will create the appropriate
library file(s) in the current directory. For example, this will create
swt-XXXX.dll files on windows, or libswt-XXXX.so files on Linux
and Solaris.
- Q: How do I add a new native to the SWT JNI libraries for my platform?
- A: For the steps to add new natives to the SWT JNI libraries, see
Generating the SWT JNI Code.
- Q: How do I add a new native to the SWT JNI libraries for Cocoa?
- A: For the steps to add new natives to the SWT Cocoa JNI libraries, see
Generating the SWT PI Code for Cocoa.
- Q: How do I build the Eclipse executable for my platform?
- A: Eclipse is launched by a binary executable which puts up a splash screen and launches a Java VM.
The executable must be compiled for the windowing system, operating system and hardware architecture of interest.
The libraries can be built from an eclipse SDK download.
Building the Eclipse executable from the eclipse SDK download:
In order to build the required libraries and run Eclipse,
you will require a JDK (Java Development Kit) of version 1.4.2 or later.
Download an Eclipse distribution from
http://http://www.zjjv.com///downloads/index.php.
Unzip the distribution. This will create a directory called eclipse.
This directory is subsequently referred to as <eclipseRoot>.
In the directory <eclipseRoot>/plugins/org.eclipse.platform.source_X.X.X/src,
find the launchersrc.zip file under org.eclipse.platform_X.X.X.
Unzip the file launchersrc.zip. This will create a directory called library.
Change directory into library/WS, where WS is the name of the windowing system
e.g. win32, motif, gtk, photon, or carbon.
Modify any incorrect _HOME variables defined at the top of the appropriate .mak file.
Run the build command (sh build.sh for UNIX and Linux, build.bat for Windows).
This will create an executable launcher called eclipse.
Move this eclipse executable to <eclipseRoot>.
As of eclipse 3.3 an eclipse_<version> shared library is also created by the previous step.
Move this library to the appropriate org.eclipse.equinox.launcher.<ws>.<os>.<arch>
fragment.
This description was originally contributed by Colin R Devilbiss.
- Q: How do I build the 64-bit version of SWT GTK?
- A: Follow these steps to extract the 64-bit SWT GTK source code from GIT and produce your own build:
Start Eclipse and retrieve the
org.eclipse.swt
,org.eclipse.swt.gtk.linux.x86_64
andorg.eclipse.swt.tools
projects from dev.eclipse.org (seeHow to use SWT from GIT, use
.classpath_gtk
as the
.classpath
file in theorg.eclipse.swt
project).Note this is not needed for builds after 4.3 M3 as the code was changed to 64-bit. Convert SWT's Java from its 32-bit form to 64-bit:
To convert the Java code in-place, go to the
build.xml
ant script in theorg.eclipse.swt.gtk.linux.x86_64
project and run its "replace.32.to.64" target. Once this target has completed you must refresh (F5)
the
org.eclipse.swt
project in order to pick up the changes.Run the "build_libraries" target in the same
build.xml
file. Refresh (F5)the
org.eclipse.swt.gtk.linux.x86_64
project when this target has completed, to pick up the new libraries.You're done! The
org.eclipse.swt.gtk.linux.x86_64
project will now contain the 64-bit native libraries, and if you'reinterested, the 64-bit source code will now be available in the
org.eclipse.swt.gtk.linux.x86_64/src
folder. - Q: How do I build the 32-bit version of SWT GTK?
- A: Follow these steps to extract the 32-bit SWT GTK source code from GIT and produce your own build:
Start Eclipse and retrieve the
org.eclipse.swt
,org.eclipse.swt.gtk.linux.x86
andorg.eclipse.swt.tools
projects from dev.eclipse.org (seeHow to use SWT from GIT, use
.classpath_gtk
as the
.classpath
file in theorg.eclipse.swt
project).Convert SWT's Java from its 64-bit form to 32-bit:
To convert the Java code in-place, go to the
build.xml
ant script in theorg.eclipse.swt.gtk.linux.x86
project and run its "replace.64.to.32" target. Once this target has completed you must refresh (F5)
the
org.eclipse.swt
project in order to pick up the changes.Run the "build_libraries" target in the same
build.xml
file. Refresh (F5)the
org.eclipse.swt.gtk.linux.x86
project when this target has completed, to pick up the new libraries.You're done! The
org.eclipse.swt.gtk.linux.x86
project will now contain the 32-bit native libraries, and if you'reinterested, the 32-bit source code will now be available in the
org.eclipse.swt.gtk.linux.x86/src
folder. - Q: Which GTK version do I need to run SWT?
- A: SWT requires the following GTK+ versions (or newer) to be installed:
Note that Eclipse/SWT 4.3.x includes early access support for GTK+ 3.x. To use it on a Linux distro with GTK+ 3.x
libraries installed, set Linux environment varable SWT_GTK3=1 before launching your application.
You can determine which version(s) of GTK you have installed with rpm -q gtk2 or rpm -q gtk3.
- Q: How can I decide which Eclipse/SWT port to use on OS X?
- A: It depends on the VM and OS version that you are using and your personal preference. The Eclipse downloads page lists
the following Eclipse platforms:
- Q: On Mac Carbon, how do I run an SWT application from the command line?
- A: If you run a Java application that uses Carbon via JNI, the application is not registered with the OS as
a 'normal' UI application. As a consequence, it has no entry in the dock and it cannot be activated. AWT
(or Swing) based applications don't have this problem because they seem to use undocumented SPI to register
themselves.
To work around this problem you'll have to pass the -XstartOnFirstThread option to the
java executable as follows:
java -XstartOnFirstThread -cp swt.jar:. ControlExample
If you want to run a bundled application, take a look at this
article.
- Q: Why do I get an UnsatisfiedLinkError when launching from the 32-bit Cocoa or Carbon port?
- A: You need to be sure that you are forcing your launch to use a 32-bit VM. Apple ships most of their VMs with 32 and
64-bit binaries. To force the VM to run in 32-bit mode, use the -d32 option as VM argument in your launch configuration.
Note that as of Snow Leopard (OS X v10.6) the default VM is 64-bit.
- Q: Why do I get an UnsatisfiedLinkError when launching from the 64-bit Cocoa port?
- A: You need to be sure that you are forcing your launch to use a 64-bit VM. Apple ships most of their VMs with 32 and
64-bit binaries. To force the VM to run in 64-bit mode, use the -d64 option as VM argument in your launch configuration.
If you are launching with SWT from GIT in your workspace (see
How to use SWT from GIT, use
.classpath_cocoa
as the
.classpath
file in theorg.eclipse.swt
project and make sure you have theorg.eclipse.swt.cocoa.maxosx.x86_64 project in your workspace),
then you also need to modify the
.classpath
file as follows:
attribute value="org.eclipse.swt.cocoa.macosx"change to:
attribute value="org.eclipse.swt.cocoa.macosx.x86_64" - Q: How can I deploy my standalone SWT application with Java Web Start?
- A: For steps that can be used to package and deploy an SWT application with Java Web Start (JWS) see
How to deploy SWT Applications with Java Web Start. A related article
that describes the deployment of SWT applications with JWS (but does not outline the process of packaging SWT) can be found at
http://http://www.zjjv.com///developerworks/opensource/library/os-jws/.
- Q: How do I run SWT on Ubuntu PowerPC?
- A: As of Eclipse 3.7 builds of Eclipse/SWT are no longer produced for 32-bit PowerPC. Builds are still produced
and supported for 64-bit PowerPC. However Ubuntu's 64-bit PowerPC distribution (10.04 LTS) is missing 64-bit compilations
of many libraries required by SWT, so Eclipse/SWT will not run here. To use Eclipse/SWT on Ubuntu PowerPC you either must
use a 32-bit PowerPC release (available for Eclipse versions prior to 3.7), or for 64-bit PowerPC users wishing to use
Eclipse/SWT 3.7 or newer, manually build 64-bit compilations of swt's dependencies.
- Q: What do I need to do to run SWT on the PocketPC?
- A: There is an experimental version of SWT for WinCE devices. If you wish to
give it a try, the following steps may help you with getting started.
Install a VM on your PocketPC.
The port is tested using the J9 VM for ARM WinCE PocketPC.
For information on how to get the J9 VM, see at the WebSphere Studio Device Developer website (which ships J9):
http://http://www.zjjv.com///wdd
For questions on how to use the J9 VM, see the WebSphere newsgroup:
ibm.software.websphere.studio.device-developer
Get the swt.jar and SWT dll for PocketPC. See
Copy the swt.jar and SWT dll to your device.
Copy your SWT app to your device.
For example, compile the following class inside Eclipse and copy the resulting
class file to your device.
import org.eclipse.swt.*;
import org.eclipse.swt.widgets.*;
import org.eclipse.swt.layout.*;
public class HelloWorld {
public static void main(String[] args) {
Display display = new Display();
/*
* Create a Shell with the default style
* i.e. full screen, no decoration on PocketPC.
* Alternative: 'new Shell(display, SWT.CLOSE)'
* to get the Pocket PC 'Ok' button.
*/
Shell shell = new Shell(display);
/*
* Set a text so that the top level Shell
* also appears in the Pocket PC task list
*/
shell.setText("HelloWorld");
/*
* Set a menu bar to follow UI guidelines
* on Pocket PC
*/
Menu mb = new Menu(shell, SWT.BAR);
shell.setMenuBar(mb);
/*
* Add widgets
*/
FillLayout layout = new FillLayout();
layout.type = SWT.VERTICAL;
shell.setLayout(layout);
Label label = new Label(shell, SWT.CENTER);
label.setText("Hello World");
shell.open();
while (!shell.isDisposed()) {
if (!display.readAndDispatch())
display.sleep();
}
}
}
Run your SWT application.
One way to start your application is to create a shortcut file.
On your desktop, create a file 'HelloWorld.lnk'. Insert the following line.
68#\j9\bin\j9.exe -Djava.home=\j9
-cp:\java\swt.jar;\java HelloWorldThis is assuming that you have installed the J9 VM in the folder \j9, and that
you have copied the swt.jar and your application HelloWorld.class into the folder \java.
It also assumes that the SWT dll was copied into the folder \j9\bin where it will be
found by the VM.
Save the shortcut file. Copy the file to your device.
Using the file explorer on your device, click on the shortcut file.
If everything is correctly setup, the SWT app should come up.
- Q: Where is the SWT library for the PocketPC?
- A: There is an experimental version of SWT for WinCE devices. The swt.jar and ARM Pocket PC
dll are available from the Eclipse download page.
Choose which swt.jar fits your project requirements. You can also build a custom
version. A custom version allows you, for example, to exclude image decoders or layouts, to
further reduce the size.
win32-ce-arm-ppc.zip
win32-ce-arm-ppc-j2me.zip
Custom SWT library
From Eclipse, check out the projects org.eclipse.swt and org.eclipse.swt.win32.wce_ppc.arm
from the head stream. These projects reside in the Eclipse repository
Build the swt.jar
Open the file org.eclipse.swt.win32.wce_ppc.arm/build_custom.xml
The file contains indications on how to build the swt.jar as recommended for WinCE PocketPC.
Get the corresponding dll
The latest dll is available under org.eclipse.swt.win32.wce_ppc.arm
- Q: How do I make SWT use the Windows XP themes?
- A: In order for an application to use Windows XP themes, there must be a manifest file
located in the same place as the executable that launches the application.
Here is a sample manifest file to download.
The name of the manifest file must match the name of the executable.
In the case of eclipse, the executable is javaw.exe and the manifest file
must have the name javaw.exe.manifest. The manifest file must be in the
jre\bin folder for the VM you use to launch Eclipse. Note: the
eclipse.exe executable does not launch Eclipse; eclipse.exe
displays a splash screen and then invokes the Java VM.
Note: As of SWT 3.2, the manifest file is no longer needed.
- Q: On GTK, how do I change the default fonts and colors of widgets?
- A: GTK uses a file called .gtkrc which is located in your home directory.
On some versions of Linux, this file is called .gtkrc-2.0.
Here is an example of the content of that file which sets the font and colors for Eclipse:
style "eclipse" {
font_name = "Sans 12"
bg[NORMAL] = "#d6d3ce"
bg[ACTIVE] = "#c7c2bc"
bg[INSENSITIVE] = "#828282"
bg[PRELIGHT] = "#3a6ea5"
fg[NORMAL] = "#000000"
fg[ACTIVE] = "#000000"
fg[INSENSITIVE] = "#d4d0c8"
fg[PRELIGHT] = "#ffffff"
}
class "GtkWidget" style "eclipse"
To turn off anti-aliasing of fonts you should use the facilities
available in your desktop if possible, such as the Gnome Font
Properties dialog. An alternate approach is to ensure that your
~/fonts.conf or system-wide fonts.conf file contains the following:
<match target="font">
<edit mode="assign"><bool>false</bool></edit>
<edit mode="assign"><bool>true</bool></edit>
<edit mode="assign"><bool>false</bool></edit>
</match>
- Q: On motif, how do I change the default fonts and colors of widgets?
- A: Motif uses a file called .Xdefaults which is located in your home directory.
Here is an example of the content of that file which sets the font and colors for Eclipse:
Eclipse*spacing:0
Eclipse*XmForm.background:#e8e7e3
Eclipse*XmList.background:#e8e7e3
Eclipse*XmTextField.background:#e8e7e3
Eclipse*background:#d6d3ce
Eclipse*fontList:-misc-fixed-medium-r-normal-*-10-100-75-75-c-60-iso8859-1
After creating/modifying this file, you must run "xrdb ~/.Xdefaults" or restart X to make the changes take effect.
- Q: Why do I get the error "java.lang.NoClassDefFoundError: org/eclipse/swt/internal/XXX/OS."?
- A: On some platforms such as GTK, SWT is broken into multiple jars. Therefore,
you must ensure that all required jars are on the classpath. The required jars are:
- Q: Why do I get the error "java.lang.UnsatisfiedLinkError: no swt-win32-3232 in java.library.path."?
- A: The SWT JNI libraries must be found at runtime. As of Eclipse/SWT 3.3 this will happen
automatically if the platform-specific SWT jar is on the java classpath. For older Eclipse/SWT
versions you need to place the SWT JNI libraries in a place where the Java Virtual Machine will
find them.
The SWT JNI libraries are included in the SWT download.
A Java application can be informed of the location of the libraries in several ways:
Set the library path in the VM launch arguments.
In the Launch Configuration Dialog of eclipse select the Arguments
page, and in the VM arguments field enter:
-Djava.library.path={runtime-library-path}
Where the runtime-library-path is the absolute path to the directory containing
the native code library (see above).
This solution means that the SWT libraries have to be manually
added to every project that uses SWT.
Set the library location in an environment variable.
For Windows this is done by editing the PATH environment variable to
include the above mentioned runtime-library-path.
in Win 9X this is done by editing the autoexec.bat file,
on NT or 2K the variable is edited through My Computer > Properties > Advanced > Environment Variables.
On linux/unix, modify the LD_LIBRARY_PATH environment variable to include the runtime-library-path.
Copy the SWT library to a directory that is already on the Java library path. For example, the jre/bin directory.
The disadvantage of this solution is that every time you upgrade eclipse you have to remember to copy the native code library.
Starting with Eclipse 3.1, the SWT plugin that comes with Eclipse, includes the JNI libraries in the SWT jar.
This was done to support OSGi and Eclipse RCP. If you are using the plugin you must extract the libraries
to include them in the path.
- Q: Why do I get an error beginning with "...SWTException: Unsupported or unrecognized format" on startup?
- A: There is a bug in the Konqueror decompressor which causes Eclipse to be improperly extracted
if used. To avoid this the Eclipse archive should first be downloaded to your machine and
then extracted using unzip at the command line.
- Q: Why do I get the error "error while loading shared libraries: ./libXm.so.2: file too short" on startup?
- A: You must use unzip, not jar, to extract your eclipse download. Jar does not extract the libXm.so.2 link file properly.
- Q: Why do I get the error "java.lang.UnsatisfiedLinkError: libXm.so.2: cannot open shared object file: No such file or directory."?
- A: On motif, the SWT library links against the open motif library libXm.so.2. On most platforms, the open motif library is installed
and added to the library path by default. However, on some Linux platforms, either open motif is not installed or is not on the default library
path, or lesstif is installed. Eclipse (and the standalone version of SWT) includes the libXm.so.2 library in the root of the Eclipse install.
You need to either launch Eclipse from the installed directory or modify the LD_LIBRARY_PATH environment variable to
include the location of libXm.so.2.
Note
-Djava.library.path
is used by the VM to locate libraries for System.loadLibrary calls. However, it doesnot update the LD_LIBRARY_PATH and therefore does not help libraries locate other libraries.
- Q: Why do I get the warning "XmParseMappingCreate() is not implemented yet" on Linux/Motif?
- A: This warning is shown if you're accessing installed LessTif libraries instead of the
shipped OpenMotif libraries. If you see this warning, add the eclipse install directory
to your LD_LIBRARY_PATH before launching eclipse. For example, if you are using csh:
setenv LD_LIBRARY_PATH /opt/eclipse:${LD_LIBRARY_PATH}
- Q: Why do I get an error beginning with "org.eclipse.swt.SWTError: Font not valid" on startup?
- A: This error occurs if a recognized font cannot be resolved at startup time. The scenario where
this has been observed to sometimes happen is when accessing a remote machine via Reflection X. This
situation can be made to work by changing some settings in Reflection X. For information about how to
do this see .
- Q: Why do I get the error "java.lang.OutOfMemoryError: Java heap space" when I try to create a very large Image?
- A: This error occurs if there is not enough Java heap space to create a very large image, for example:
new Image(display, 10985, 1102);
To allocate more heap space for the Java VM, start eclipse with a VM argument that allocates more heap, for example:
eclipse -vmargs -Xmx400m
allocates 400 Mb of heap space.
- Q: How do I enable debug mode in Eclipse for SWT?
- A: Follow these steps:
Create a .options file in the same directory as your eclipse executable.
Place the following lines in the .options file:
org.eclipse.ui/debug=true
org.eclipse.ui/debug/swtdebugglobal=true
Start up eclipse from the command line with the debug flag: ./eclipse -debug
All messages from SWT will be printed to the console window.
- Q: Can I use Swing or AWT inside Eclipse?
- A: Yes. As of Eclipse 3.2, Swing and AWT can be embedded in SWT on Windows, Motif, GTK and OS X.
However it is important to note that a supporting JDK is required on some platforms in order for this
to work. Specifically, Motif and GTK require that JDK 1.5 or newer be used, and OS X requires that
the JDK specified in be used.
Additionally, AIX and Solaris users must ensure that AWT is using XToolkit, as described in
See this snippet for an example of how to use the API.
- Q: Why does Eclipse (4.2 and greater) on GTK crash with a call to org.eclipse.swt.internal.C.memmove originating from some graphics call?
- A: Eclipse 4.2 (and greater) makes use of functions in cairo that were not present in the 1.0.2 version of cairo that shipped with Eclipse by default. Since all modern Linux distributions that ship GTK will ship a more recent version of the Cairo library, it was decided to stop shipping the library.
If you are running an older Linux distribution that does not include cairo, you will have to install the cairo library (any version greater than 1.2)
- Q: Why can't I subclass SWT widgets like Button and Table?
- A: You can but it is not recommended. The article Creating Your Own Widget using SWT
describes the reasons in detail:
Subclassing Widgets Directly
In extreme circumstances, you may need to subclass a widget other than
Canvas or Composite. We recommend against doing this unless all
other avenues have been explored and exhausted. Try to wrap the widget first,
before subclassing it. Here is why:
Subclasses may inherit a lot of API that makes no sense, and must be
overridden. In Java, you cannot override a method and change the return
type; therefore you cannot reimplement some methods.
Subclassing is typically not the safest way to extend a class that
you do not own. For a simplified list of the common arguments, see the
article by Bill Venners in the Nov '98 issue of Java
World called "Inheritance versus composition: Which one should
you choose?" at:
http://http://www.zjjv.com///javaworld/jw-11-1998/jw-11-techniques.html
Widget subclasses are almost certainly guaranteed to be
platform-specific unless great care is taken to ensure that they work on
all platforms.
Subclassed widgets can be affected by changes in the non-API
implementation of the superclass.
Subclassing may cause bad system-level bugs, and runs the risk of
leaking resources. For example, if a subclass reimplements a method
without making certain that dispose code from the superclass method is
still called, then the new method will leak system resources.
Binary incompatibility across releases becomes possible. If a method
signature or field name changes, or new methods or fields are added,
there may be a name conflict in the widget subclass. Only Canvas
and Composite are guaranteed not to have name conflicts in future
releases.
See any paper by Leonid Mikhajlov on the "Fragile Base Class
Problem". You can find his paper "A Study of The Fragile Base Class
Problem" at: http://www.cas.mcmaster.ca/~emil/publications/fragile/
Subclassing Canvas or Composite is the best way to
ensure that your widget works on all SWT platforms. The 'is-a' test in
this case tests whether your widget is-a basic or compound widget.
Subclassing anything else requires asking if the new widget is an SWT
native widget of the type being subclassed. For example, a 100% Java
portable PictureLabel is not an SWT native Label.
When subclassing anything other than Composite or
Canvas you must override the method protected void
checkSubclass() to do nothing. Make sure you read the method comment
before overriding it.
- Q: Why are some events like Selection not fired in response to programmatic widget changes?
- A: See .
- Q: Why don't SWTError and SWTException override all printStackTrace methods?
- A: SWTError and SWTException each contain a slot which records the original
exception (if it is known) that caused the SWTError or SWTException to be thrown.
The printStackTrace() method in these classes has been overridden to print the
stacktrace of the original exception as well.
The problem with the other two API methods (i.e. printStackTrace(PrintStream) and
printStackTrace(PrintWriter)) is that the classes mentioned in their arguments
(PrintStream and PrintWriter) are not available in the CLDC class library.
Because we need to maintain compatability with CLDC, we can not override them.
- Q: How do I print using my favorite Unix print program?
- A: You can use the External Tools support in Eclipse to print files using external programs.
Just create a new Program launch config from the External Tools dialog that launches your
favorite printing utility and you can pass the selected resource as a parameter.
Type: Print Selected File
in the Name: field.
Type the full path name of your favorite printing program in the Location: field.
For example: /usr/bin/lpr
Type: ${container_loc}/${resource_name}
in the Arguments: field.
Click Apply
Click Run
- Q: How can I tell whether or not there are any printers installed?
- A: The method
org.eclipse.swt.printing.Printer.getPrinterList()
can be used to determinewhether or not there are any printers installed on the system. This method returns an array of
PrinterData
objects. If the length of the array is 0, then there are no printers available.If there are 1 or more elements in the array, then each
PrinterData
object represents aninstalled printer.
- Q: How do I print a snapshot of a widget?
- A: To print an image, the image needs to be created on the printer.
A common mistake is to try to print an image that was created on a display.
First take the snapshot into an image that was created on the display,
and then get the imageData and create a new Image just for printing.
Something like this:
// Take the snapshot into a display Image
Point size = myWidget.getSize();
Image image = new Image(display, size.x, size.y);
GC gc = new GC(myWidget);
gc.copyArea(image, 0, 0);
gc.dispose();
// Get the ImageData and create a new printer Image from it
ImageData imageData = image.getImageData();
Image printImage = new Image(printer, imageData);Then print using printImage.
(Remember to dispose both images when you are done with them).
This is true for all graphic objects that you want to use for printing:
Fonts, Colors, and Images. You need to recreate them on the printer before
you can use them for drawing on the printer GC. You might get lucky sometimes,
if the printer happens to have this font or that color, but you won't get lucky
on all platforms and for all printers, and you won't get lucky for images.
So get into the habit of thinking "Did I create this graphics resource
on the same device that I am now trying to draw to?"
- Q: Why does everything I print seem so small?
- A: When you are printing something from the screen to a printer device, you
need to think about scaling. What is happening is that your figure is being drawn
in something like 72 x 72 dots per inch on the screen, but then you are printing
it to something like a 300 x 300 or 600 x 600 DPI printer. What you have to do is
ask both the screen and the printer what their DPI is, and then figure out what
scale factor you need to use when you draw to the printer GC. The code might look
like this:
Point screenDPI = display.getDPI();
Point printerDPI = printer.getDPI();
int scaleFactor = printerDPI.x / screenDPI.x;
Please see the ImageAnalyzer example in the org.eclipse.swt.examples project
for an example of printing an image to a printer. Look at method
menuPrint(). Note however that this is a pretty rough example, and it does
not take into account what happens if the image is larger than the page - it
just clips.
Text printing takes some thought also. You need to wrap words, put your page
breaks in the right place, know where your margins are, etc. The SWT
StyledText widget does its own text printing. If you need to see a more
complicated example of printing a document, wrapping, margins, multi-page,
etc., then please look at the inner class Printing in StyledText in
org.eclipse.swt.custom. An instance of this class is created by the
StyledText.print(Printer) API method.
Note also that when printing, any graphics objects that you use to draw,
such as fonts, colors, and images, need to be re-created on the printer
device before you can draw them to the printer GC.
We also recommend that you run your print job in a separate thread and not in
the UI thread, because printing a long document to a slow printer can hang
your entire UI while the printer spools.
Unfortunately, printing is not simply a matter of just passing in the
printer GC instead of the screen GC. Printing has to be designed into your
drawing classes. You don't have scrollbars anymore, so you have to either
cut stuff off and print it on another page, or reorganize it, or scale it
down, or wrap it somehow. Maybe you want to give some control to your users,
and let them specify how many inches something should be, or whatever -
maybe give them a ruler. There is no magic bullet - you
will definitely have to give it some thought.
- Q: What does computeTrim mean for a Printer?
- A: The "trim" is the area of the page that the printer cannot print on.
Usually, computeTrim is used as follows:
Rectangle trim = printer.computeTrim(0, 0, 0, 0);
A printer that can print edge-to-edge would have a trim.x and trim.y of 0,0.
The trim.width and trim.height would be the same as the width and height of the physical paper.
A 600 dot per inch printer that cannot print on the leftmost 0.18 inch of the paper would have a trim.x of -108.
So to print starting at precisely 1" from the left edge, take 600 (i.e. 1") and "add" -108 (i.e. subtract 0.18") to get the starting x position.
Trim positions are negative because they are relative to the 0,0 position of the client area (or 'printable area') of the paper.
- Q: How can I implement user interaction tests?
- A: The method
org.eclipse.swt.widgets.Display.post(Event)
can be used to postmouse and keyboard events into the OS, which emulates the user performing the specified action.
This is the typical approach that is used for implementing JUnit test cases.
There are also stand-alone applications available for automating SWT user interaction tests:
- Q: On gtk, why does my widget's selection disappear when it loses focus?
- A: This effect may be seen if KDE color settings are being
utilized. This can be fixed by unchecking the "Apply KDE colors to
non-KDE apps" option in the KDE colors control panel.
- Q: On gtk and motif, why are some widgets hidden when they are visible on Windows or the Macintosh?
- A: The SWT.CENTER, although undefined for composites, has
the same value as SWT.EMBEDDED which is used to embed widgets from
other widget toolkits into SWT. On some operating systems (GTK, Motif), this
may cause the children of this compostite to be obscured. Do not use
the SWT.CENTER style when creating a composite.
- Q: Which platforms have advanced graphics support?
- A:
SWT for Windows uses GDI+ for advanced graphics, which is installed on Windows XP and newer.
Windows 2000 users can download and install a Microsoft package containing GDI+.
SWT for GTK+ and Motif use Cairo for advanced graphics, which is installed on systems with GTK+ 2.8 or newer
(for example RHEL 5).
SWT for OS X uses Quartz for advanced graphics, which is installed on all supported OS X versions.
- Q: What is the SWT Browser widget?
- A: The SWT Browser widget is used to display HTML documents. It is
designed to provide a basic and portable API sufficient for essential
HTML browsing and rendering on the platforms on which it is implemented.
- Q: Which platforms support the SWT Browser, and which native renderers do they use?
- A: The SWT Browser is currently available on the platforms listed below. By default, Browser instances created with style
SWT.NONE
use the following native renderers:
Windows 2000 and newer (Internet Explorer 5.5 and newer)
Mac OS X 10.5 and newer (WebKit)
Linux GTK ()
Solaris-x86 and Solaris 10 SPARC ()
Browsers should typically be created with style
SWT.NONE
as this will attempt to use a native renderer that should not requireadditional software installation. However for clients with specific native browser requirements, the type of native renderer to use can be specified
on a per-instance basis, see and
.
Also note that as of Eclipse/SWT 3.7 it is possible to override the default native renderer that is used for
SWT.NONE
-style Browsers,see .
- Q: How do I specify the default type of native renderer that is used by the Browser?
- A: The default native renderers that are used for
SWT.NONE
-style Browsers are listed in. In general these defaults
should not be overridden because they are chosen with the goal of using a renderer that should not require
additional software installation. However there are situations, such as the potential mixing of Mozilla and WebKit Browsers, where specifying
the default type of native renderer to use can avoid crashes caused by conflicting dependent libraries.
As of Eclipse/SWT 3.7.1 a user can set a property to specify the type of native renderer to use for
SWT.NONE
-style Browsers.Setting this property does not affect Browsers that are created with styles such as
SWT.MOZILLA
orSWT.WEBKIT
.The property name is
org.eclipse.swt.browser.DefaultType
and valid values for it currently include "mozilla
" and"
webkit
". This property must be set before the first Browser instance is created.Note: As of Eclipse/SWT 4.3 a user can specify a comma-separated list of native renderers, in order of preference, for the
org.eclipse.swt.browser.DefaultType
value. Additionally, "ie
" is now a valid native renderer value. The purpose of thesechanges is to enable applications to specify the default use of either Mozilla or WebKit on non-Windows platforms (where conflicting dependent library
problems can occur) without affecting the default renderer that is used on Windows (IE). An application wishing to do this should set this property's
value to either "
ie,webkit
" or "ie,mozilla
". On Windows this will leaveSWT.NONE
-style Browsers to use IE, andon other platforms where IE is not available the second specified renderer in the list will be used for
SWT.NONE
-style Browsers.The best opportunity for a user to set this property is by launching their application with a
-D
VM switch (eg.- add to the end of the eclipse.ini file:
-Dorg.eclipse.swt.browser.DefaultType=webkit
).An alternate approach that an eclipse application may use is to provide a
BrowserInitializer
implementation that sets this property. This implementation will be invoked when the first Browser instance
is about to be created. The steps to do this are:
Create a fragment with host plug-in
org.eclipse.swt
.In this fragment create class
org.eclipse.swt.browser.BrowserInitializer
.Implement a static initializer in this class that sets the
org.eclipse.swt.browser.DefaultType
property. - Q: Which Internet Explorer version do Browsers on Windows use?
- A: Windows machines typically only have one production release of Internet Explorer (IE) installed at a time, so the Browser control
embeds the same native WebBrowser that is used by stand-alone IE. However it's important to note that for Eclipse/SWT releases prior
to 3.7, the default compatibility mode of the Browser control is capped at IE7. This means, for instance, that HTML documents
containing HTML5
canvas
tags will not be shown properly, even if IE9 is installed on the machine. An HTML document can overridethis behavior by including a
X-UA-Compatible
meta tag as described inDefining Document Compatibility, which enables the Browser to use a more modern compatibility mode if an IE version newer than IE7 is installed.
As of Eclipse/SWT 3.7 the Browser control defaults to using the compatibility mode that matches the installed IE version. This behavior will
be overridden in the following two cases:
If an HTML document contains a
X-UA-Compatible
meta tag that specifies an older IE version then the Browser will honorthis request. This will only affect the compatibility mode that is used for showing the document containing the meta tag, it will not
affect the compatibility mode for other documents.
The Browser's default compatibility mode can be overridden by setting java property
org.eclipse.swt.browser.IEVersion
to a valuefrom before the first
Browser instance is created. For example, adding the line
-Dorg.eclipse.swt.browser.IEVersion=7000
to the end ofeclipse's
eclipse.ini
file will revert all IE-based Browsers to use IE7 compatibility mode by default. - Q: What do I need to run the SWT Browser inside Eclipse on Linux?
- A: The browser versions that are supported by each Eclipse release are listed below. Note that Mozilla/XULRunner versions that are not
final releases (eg.- betas, alphas, nightlies) are not supported, even if their version technically satisfies a listed version range.
Also note that the Mozilla/XULRunner must be compiled for the same architecture as the SWT jar that is being used.
Also note that a Firefox release whose contained Gecko version correlates with the Mozilla versions above can also be used
with Eclipse 3.1 and newer (Linux only), provided that it has been compiled with linkable Gecko libraries. It is important to
note that Firefox downloads from mozilla.org do not satisfy this criteria, but Firefox installations that are
included in major Linux distributions often do in the absence of a XULRunner installation. Attempting to use a Firefox install
without linkable Gecko libraries will throw an error with message "No more handles [NS_InitEmbedding...error -2147221164]".
The version of Mozilla or Firefox installed on your system varies with your Linux distribution.
The following Linux distributions meet the minimum Mozilla requirements for using the Browser widget.
RedHat Enterprise Linux 3
Suse 9
If you use the IBM 1.4 VM
In general the Browser control will automatically detect an appropriate native browser to use. However if you wish to point at a specific
XULRunner or Mozilla install to use then this can be specified as described in Can I specify which XULRunner installation
gets used? or .
- Q: What do I need to run the SWT Browser inside Eclipse on Solaris?
- A: The Browser is supported on OpenSolaris (x86) and Solaris 10 (SPARC). The Mozilla versions that are supported by each Eclipse release are:
OpenSolaris (x86)
Eclipse 3.5.0: Mozilla 1.7.x GTK2, XULRunner 1.8.x - 1.9.1.x
Eclipse 3.5.2 and newer: Mozilla 1.7.x GTK2, XULRunner 1.8.x - 1.9.2.x and 3.6.x
Note that a Firefox release whose contained Gecko version correlates with the Mozilla versions above can also be used.
Unlike other platforms, since Sun's compiler does not produce statically-linked libraries, Firefox builds downloaded from mozilla.org
can be used on Solaris.
Solaris 10 (SPARC)
Eclipse 3.5.1 and newer: the Mozilla version that is shipped with the OS in
/usr/sfx/lib/
- Q: What do I need to run the SWT Browser in a standalone application on Linux or Solaris?
- A: Follow the steps below to use the SWT Browser widget in your standalone SWT application.
A supported native browser must be installed () ().
If a supported WebKitGTK and/or XULRunner is installed then it should be found automatically at runtime with no additional effort. For other native Mozilla-based browsers:
Set the environment variable MOZILLA_FIVE_HOME to the native browser's installation folder. e.g.
setenv MOZILLA_FIVE_HOME /usr/lib/mozilla
Set the environmnent variable LD_LIBRARY_PATH to include MOZILLA_FIVE_HOME. e.g.
setenv LD_LIBRARY_PATH ${MOZILLA_FIVE_HOME}:${LD_LIBRARY_PATH}
Your standalone SWT application can now use the Browser widget.
If you use the IBM 1.4 VM
- Q: How do I explicitly use WebKit as the Browser's underlying renderer?
- A: To specify that a WebKit renderer be used by a Browser instance, create it with style
SWT.WEBKIT
(@since 3.7). The runtime requirements forusing WebKit-based Browsers are listed below. Note that failure to meet these runtime requirements will cause the Browser instantiation to fail.
Windows:
32-bit SWT
Safari must be installed
For OSs older than XP+SP1, the path to the Apple Application Support installation must be prepended to Windows' "Path" environment variable
before running eclipse. This installation will be in a location like "
C:\Program Files\Safari\Apple Application Support
" or"
C:\Program Files\Common Files\Apple\Apple Application Support
". If more than one of these directories are found then choosethe one with "Safari" in its directory ancestry.
Linux: WebKitGTK 1.2.0 or newer must be in the library load path. Examples of Linux distros that meet this requirement by default
include Red Hat Enterprise Linux 6 and Ubuntu 10.04.
OS X: No additional runtime requirements, the default renderer is WebKit-based.
It is important to note that conflicts have been reported between the dependent libraries of WebKit and Mozilla. As a result it is advised that Browser
instances with these respective types not be mixed in an application. If a Browser with one of these types must be used in an application then
java property
org.eclipse.swt.browser.DefaultType
should also be set to this type to ensure thatSWT.NONE
-style Browsersdo not cause the libraries from the other native browser renderer to be loaded (see
).
- Q: How do I explicitly use Mozilla as the Browser's underlying renderer?
- A: A Browser can be created with style
SWT.MOZILLA
to specify that its renderer must be Mozilla-based (@since 3.3). The runtime requirements forusing Mozilla-based Browsers are listed below. Note that failure to meet these runtime requirements will cause the Browser instantiation to fail.
Runtime Platform:
Windows (x86): Any XULRunner release with version 1.8.0.x - 3.6.x or 10.x
Windows (x86_64): (@since 4.3) Any XULRunner release with version 1.9.2.x - 3.6.x or 10.x, and the Visual C++ 2010 runtime must be installed
OS X (32-bit): Any XULRunner release with version 1.8.1.2 - 3.6.x or 10.x, and the JRE must be "Java for Mac OS X 10.4, Release 5" or newer
OS X (x86_64): (@since 3.6) Any XULRunner release with version 1.8.1.2 - 3.6.x or 10.x
Linux and Solaris: See
To use XULRunner it must be detectable by the Browser. For XULRunner versions 1.8.0.x - 3.6.x
this is facilitated by either it or by
For XULRunner versions newer than 3.6.x the only way to do this is by explicitly specifying its location.
The installed/specified XULRunner version must be 1.8.1.2 - 3.6.x to make use of JavaXPCOM
It is important to note that conflicts have been reported between the dependent libraries of WebKit and Mozilla. As a result it is advised that Browser
instances with these respective types not be mixed in an application. If a Browser with one of these types must be used in an application then
java property
org.eclipse.swt.browser.DefaultType
should also be set to this type to ensure thatSWT.NONE
-style Browsersdo not cause the libraries from the other native browser renderer to be loaded (see
).
- Q: How do I use the WebKit renderer on Linux-GTK?
- A: In Eclipse/SWT 3.7 and newer the Browser attempts to use WebKitGTK for SWT.NONE-style Browsers created on GTK. For this to succeed, WebKitGTK
1.2.0 or newer must be in the library load path. Examples of Linux distros that meet this requirement by default include Red Hat
Enterprise Linux 6 and Ubuntu 10.04. Linux installations that do not meet this requirement will fall back to using Mozilla for SWT.NONE-style Browsers.
Eclipse/SWT 3.6.x can also use WebKitGTK for SWT.NONE-style Browsers created on GTK, but the user must explicitly request this by setting java property
"
org.eclipse.swt.browser.UseWebKitGTK
" to "true
". In the absence of this property being set, Mozilla is used for all SWT.NONE-styleBrowsers. (Note that Eclipse/SWT 3.6.x is only able to use WebKitGTK 1.2.x; it will fail if a newer WebKitGTK release is found.)
- Q: How can I get the SWT Browser to work with the IBM 1.4 VM?
- A: The IBM 1.4 VM accidentally removes certain entries of the environment variable LD_LIBRARY_PATH. This occurs in particular
for entries starting with /usr/lib. It will leave untouched entries such as /usr/../usr/lib.
Instructions for Red Hat Enterprise Linux 3 users:
- Q: Can I view Java applets in the SWT Browser?
- A: Browser support for applets varies by platform:
Windows: As of Eclipse/SWT 3.5, applets can be viewed in a Browser if all of the following conditions are met:
The application adds the JRE's plugin.jar, deploy.jar and javaws.jar jars to the JRE's boot classpath. For example, to launch eclipse:
eclipse -vmargs -Xbootclasspath/a:"C:\Program Files\Java\jre6\lib\plugin.jar;C:\Program Files\Java\jre6\lib\deploy.jar;C:\Program Files\Java\jre6\lib\javaws.jar"
Linux (Mozilla): Applets can be viewed with Mozilla-based Browsers as long as the Mozilla Java plug-in is found at runtime.
For info about adding directories to the Mozilla plug-in search path see
OS X (WebKit): Applets cannot be viewed with WebKit-based Browsers on OS X because the launching of a JRE to execute the applet collides with the
JRE that is running the application.
- Q: How do I hide the Browser's scrollbars?
- A: The only way to influence whether scrollbars are shown in a Browser or not is for the document it's showing to
specify a style such as
'overflow:auto'
or'overflow:hidden'
. There are two ways to do this:If you are providing the document being shown then its body tag can specify this style like
<body>
.Alternatively, this style can be changed in the DOM for any document that has been loaded. The easiest way
to do this is with a line like
<yourBrowser>.execute("document.getElementsByTagName('body')[0].style.overflow='auto'");
. - Q: How do I set a proxy for the Browser to use?
- A:
Windows: All Browser instances, regardless of native renderer, automatically use Windows' global proxy settings.
These settings can be changed at any time in the Windows Control Panel.
OS X: All Browser instances, regardless of native renderer, automatically use OS X's global proxy settings.
These settings can be changed at any time in the OS X System Preferences.
Linux/Solaris: Proxy information must be explicitly specified by setting values for java properties
network.proxy_host
andnetwork.proxy_port
(@since 3.4). These properties are checkedthe first time a Browser is created, and if set, will be used for all non-local HTTP, HTTPS and FTP requests in all Browser
instances. A user wishing to set these values should do so by passing
-D...
VM arguments to the JRE at startup. - Q: Can I specify which XULRunner installation gets used?
- A: Typically a Mozilla-based Browser uses XULRunner's lookup mechanism to find a registered XULRunner at runtime,
in which case a XULRunner location does not need to be specified. However if you wish to override this mechanism you
can set the value of java system property
org.eclipse.swt.browser.XULRunnerPath
to the full path of aspecific XULRunner to use. This property must be set before the first Browser instance is created.
The best opportunity for a user to set this property is by launching their application with a
-D
VM switch (eg.- add to the end of the eclipse.ini file:
-Dorg.eclipse.swt.browser.XULRunnerPath=...
).An alternate approach that an eclipse application may use is to provide a
XULRunnerInitializer
implementation that sets this property. This implementation will be invoked when the first Mozilla-based Browser
is about to be created. The steps to do this are:
Create a fragment with host plug-in
org.eclipse.swt
.In this fragment create class
org.eclipse.swt.browser.XULRunnerInitializer
.Implement a static initializer in this class that sets the
org.eclipse.swt.browser.XULRunnerPath
property.As an example, the class below will set the property to the win32 xulrunner plug-in if it is present.
package org.eclipse.swt.browser;
import java.io.*;
import java.net.*;
import org.eclipse.core.runtime.*;
import org.osgi.framework.Bundle;
public class XULRunnerInitializer {
static {
Bundle bundle = Platform.getBundle("org.mozilla.xulrunner.win32.win32.x86"); //$NON-NLS-1$
if (bundle != null) {
URL resourceUrl = bundle.getResource("xulrunner"); //$NON-NLS-1$
if (resourceUrl != null) {
try {
URL fileUrl = FileLocator.toFileURL(resourceUrl);
File file = new File(fileUrl.toURI());
System.setProperty("org.eclipse.swt.browser.XULRunnerPath",file.getAbsolutePath()); //$NON-NLS-1$
} catch (IOException e) {
// log the exception
} catch (URISyntaxException e) {
// log the exception
}
}
}
}
}
- Q: Can I specify which Mozilla profile gets used?
- A: (@since 4.4) A profile can be specified for use by all Mozilla-based Browser instances by setting Java property
org.eclipse.swt.browser.MOZ_PROFILE_PATH
to thepath of the profile before the first instance of a Mozilla-based Browser is created. The best opportunity for a user to set this property is by launching their application with a
-D
VM switch (eg.- add to the end of the eclipse.ini file:
-Dorg.eclipse.swt.browser.MOZ_PROFILE_PATH=...
). - Q: How does the Browser detect a native Mozilla browser to use?
- A: The first Mozilla-based Browser instance performs the steps below, in order, until a native browser is found. All subsequent Mozilla-based Browser instances will use this same detected browser.
If Java property
org.eclipse.swt.browser.XULRunnerPath
is defined then use it (see ).Attempt to detect an OS-registered XULRunner in the version range 1.8.1.2 <= version < 4.0 (in order to enable JavaXPCOM use). Note that only XULRunner installations that are compiled for the
same architecture as the running SWT will be considered.
Attempt to detect an OS-registered XULRunner with a version earlier than 1.8.1.2 (again, the architecture must match that of SWT).
(if running on Linux or Solaris, and the Browser's style is
SWT.NONE
) Attempt to use the native browser pointed at by OS environment variableMOZILLA_FIVE_HOME
, which may be any ofthe browsers listed . Note that if this environment variable is not set when eclipse is run then on linux the eclipse launcher will try to set it by checking various
potential installation locations.
At this point a native Mozilla browser could not be found, so an
SWTError
is thrown from the constructor, which should be caught and handled by the application. Subsequent attempts tocreate Mozilla-based Browsers will go through these detection steps again.
- Q: How can I determine which installed Mozilla browser is being used to render Browser content?
- A: The first Mozilla-based Browser instance performs a series of to detect a native browser to use. The SWT snippet below can be used to print the location of the
Mozilla browser that was found.
import org.eclipse.swt.SWT;
import org.eclipse.swt.browser.*;
import org.eclipse.swt.graphics.*;
import org.eclipse.swt.widgets.*;
public class DisplayMozillaVersion {
public static void main(String[] args) {
Device.DEBUG = true;
Display display = new Display();
Shell shell = new Shell(display);
System.out.println(">>>Snippet creating SWT.MOZILLA-style Browser");
try {
new Browser(shell, SWT.MOZILLA);
System.out.println(">>>succeeded");
} catch (Error e) {
System.out.println(">>>This failed with the following error:");
e.printStackTrace();
System.out.println("\n\nSnippet creating SWT.NONE-style Browser");
try {
new Browser(shell, SWT.NONE);
System.out.println(">>>succeeded");
} catch (Error e2) {
System.out.println(">>>This failed too, with the following error:");
e2.printStackTrace();
}
}
display.dispose();
}
}
- Q: How can my Mozilla-based Browser find my Mozilla plug-ins?
- A: As of eclipse 3.3 the default set of Mozilla plug-in paths that are searched can be augmented by defining
environment variable
MOZ_PLUGIN_PATH
. For example:export MOZ_PLUGIN_PATH=/usr/lib/browser-plugins
. - Q: How do I use JavaXPCOM with the Browser?
- A: First, ensure that you have all of the requirements listed in
.
Once these are in place then you can reference JavaXPCOM as follows:
If your application runs as an Eclipse plug-in:
download the XULRunner SDK for the XULRunner version that you will be embedding
add its lib/MozillaInterfaces.jar and (if present) lib/MozillaGlue.jar files to your plugin root
open your plug-in's META-INF/MANIFEST.MF file in the Plug-in Manifest editor
If your application runs as a stand-alone application:
download the XULRunner SDK for the XULRunner version that you will be embedding
add its lib/MozillaInterfaces.jar and (if present) lib/MozillaGlue.jar files to your application's java build path
You can use
Browser.getWebBrowser()
to access the JavaXPCOMnsIWebBrowser
that represents the Browser instance. For an example of using JavaXPCOM seeSnippet 267.
- Q: Why does the SWT_AWT bridge not work for me on OS X?
- A: This was an SWT-AWT incompatibility that existed prior to Eclipse 3.2 and Java 5 on Mac OS X 10.4.
This problem has since been fixed in SWT. On Mac OS X 10.4, you must install Java 1.5.0 Release 5 or later.
On Mac OS X 10.5 and later, no additional updates are needed. (In the past a separate download called
the "SWT Compatibility Library" was required. Starting with "Java for Mac OS X 10.4 Release 5", this library
is now a part of the JRE. It is no longer available as a separate download from Apple.)
For more information about this issue see
bug 67384.
- Q: Why does the SWT_AWT bridge not work for me on OS X, even after updating Java or the OS?
- A: Prior to Eclipse 3.6, both the Carbon and Cocoa versions of the SWT only supported embedding the SWT in an AWT Frame.
In Cocoa SWT 3.6 and later, embedding works in either direction. If you have the right environment, next,
make sure you are starting your application with the argument '-XstartOnFirstThread'. This is necessary even
if you will be using Swing or the AWT. Next, make sure your code is calling each toolkit on the correct thread. Code
that calls into the SWT must be running on the main thread, and code that calls the AWT or Swing must be called from
a thread other than the SWT thread, using either java.awt.EventQueue.invokeLater() or javax.swing.SwingUtilities.invokeLater().
NOTE: This is true on ALL PLATFORMS, not just Mac OS X, but your application is almost guaranteed to hang or
be very unstable if you don't follow this rule on the Mac.
- Q: Why does the SWT_AWT bridge not work for me on AIX or Solaris?
- A: The SWT_AWT bridge requires that AWT be using XToolkit, since this implements the XEmbed
protocol. However by default AWT on AIX and Solaris use MToolkit. This can be easily changed as
described in XToolkit on Solaris/Linux.
- Q: Why is the Print menu item disabled in Eclipse on GTK (Linux, UNIX)?
- A: GTK+ began supporting printing in version 2.10. To print in Eclipse, you need to have Eclipse version 3.3 or later,
and at least GTK+ 2.10.0. To determine what GTK+ version you are running, type: rpm -q gtk2.
Prior to Eclipse 3.3, printing was not implemented on GTK; however you can use the External Tools support in Eclipse
to print files using lpr or some other printing utility. See for the steps to set this up.
- Q: Why does Eclipse 3.3 freeze when I open an editor on GTK 2.10 and GTK 2.12 (Linux, UNIX)?
- A: There is a bug in some versions of GTK that causes certain print backends to hang.
If you do not want to upgrade your GTK to a fixed version, you can make use of the org.eclipse.swt.internal.gtk.disablePrinting
flag available in Eclipse 3.3.1 maintenance builds as well as 3.4 M1 and later. To use this, you must pass the flag to eclipse on startup:
./eclipse -vmargs -Dorg.eclipse.swt.internal.gtk.disablePrinting
- Q: Why is the Print menu item disabled in Eclipse on Motif?
- A: Printing on Motif requires that Xprint be installed on your machine. A good FAQ regarding Xprint can be found at
http://http://www.zjjv.com///docs/Xprint_FAQ.html.
- Q: Why do I get the error "org.eclipse.swt.SWTException: Invalid thread access"?
- A: In SWT, by definition the thread that creates the Display is a UI-thread. This thread is responsible for
reading and dispatching events from the operating system event queue, and invoking listeners in response to these events.
Listener code is executed in the UI-thread. This makes an SWT application generally quite responsive, behaving like most
other operating system programs. However, any long operation, when executed by a listener, will run in the UI-thread
and prevent it from reading and dispatching events, thus hanging the application.
If a listener has a large amount of work to perform, instead of performing that work in the UI-thread, it can
fork a separate thread so the UI-thread can continue dispatching events. If the other thread needs to execute code
that accesses an SWT object, such as changing the string in a label, there is a concurrency issue. At the very
least, some kind of synchronization is necessary to prevent the operating system or SWT from crashing, hanging or
behaving unpredictably.
SWT implements a single-threaded UI model often called apartment threading. In this model, only the UI-thread
can invoke UI operations. SWT strictly enforces this rule. If you try and access an SWT object from outside the
UI-thread, you get the exception "org.eclipse.swt.SWTException: Invalid thread access". Different operating systems
have different rules governing threads, UI components and synchronization. Some use a single-threaded UI model
like SWT. Others allow only one thread at a time in the window system library, controlling access through a
global lock. This type of multi-threaded UI model is often called free threading. Currently, in order to be
simple, efficient and portable, SWT is apartment threaded.
To allow background threads to perform operations on objects belonging to the UI-thread, the methods
syncExec(Runnable runnable) and asyncExec(Runnable runnable) of Display are used. These are the only
methods in SWT that can be called from any thread. They allow a runnable to be executed by the UI-thread,
either synchronously, causing the background thread to wait for the runnable to finish, or asynchronously
allowing the background thread to continue execution without waiting for the result. A runnable that is
executed using syncExec() most closely matches the equivalent direct call to the UI operation because a
Java method call always waits for the result before proceeding, just like syncExec().
The following code sets the text of a label from a background thread and waits for the operation to complete:
display.syncExec(
new Runnable() {
public void run(){
label.setText(text);
}
});
- Q: Why do I have to resize my shell to get my changed widgets to lay out again?
- A: See
- Q: Why do I get "SWTException: Unable to load graphics library" using GC?
- A: Support for advanced graphics operations such as path for curvers and
lines, alpha blending, antialiasing, patterns and transformations was
added to SWT 3.1. On Windows, GDI+
is required. On X Windows platforms (i.e. GTK and Motif),
Cairo 0.4.0 is
required. If your Windows platform does not have GDI+ by default then you can
download
a redistributable package from Microsoft.
- Q: Why doesn't mouse scrolling work on Linux/Motif?
- A: Mouse scrolling on Linux/Motif relies on the IMWheel driver. Here is how it works:
The X Server gets the wheel event.
Your /etc/X11/XF86Config must contain "ZAxisMap 4 5" (or the equivalent "Option"
line if you use XFree86 4.x) in the Mouse section. This maps the wheel to emulated
mouse buttons "4" and "5".
IMWheel has a global hook on the mouse, only looking for button4/5 events.
When it sees one, it looks in /etc/X11/imwheel which is a table of what to do for
which application. E.g., GTK-based applications support the idea of 5-button mice
natively, so the imwheel file says "do nothing (pass through) for gtk".
On the other hand, no known Motif-based app seems to know about these, so imwheel
eats the mouse event and emits an accelerator event for "PgUp" or whatever your
preference is. It has some clever pre-sets for xterm, netscape, and so on.
- Q: Why can't I move my mouse into certain controls using TWM on Linux/Motif?
- A: TWM by default is configured with focus-follows-mouse. It has been noticed that in this mode
it is not possible to enter any secondary window brought up by a widget (such as a ToolTip or a drop down
box on a Combo).
The two possible workarounds are:
Add NoTitleFocus to your $HOME/.twmrc file. By doing this you are instructing TWM not
to set keyboard focus to each window as it is entered.
has an example .twmrc file attachment.
Switch to another window manager.
- Q: Why don't modal dialogs stay on top of other windows on Solaris 10 using CDE and DTWM?
- A: The default setting of CDE is to allow modal dialogs to be hidden by other windows. To change this, you must:
- Q: Why do I get strange drawing behaviour when running 32 bit Eclipse on a 64 bit GTK platform?
- A: A 64 bit Linux OS comes configured by default with 64 bit libraries. If you wish to run the 32 bit version of Eclipse, you must ensure that you have
a 32 bit JRE as well as the 32 bit version of the GTK libraries. Red Hat bundles the 32 bit libraries in their installer under the "Compatibility Arch Support" package.
- Q: Why doesn't SWT.RIGHT_TO_LEFT work on some GTK versions (less than 2.8)?
- A: SWT relies on the Cairo graphics library to render strings and GTK started using Cairo in version 2.8.
- Q: Why doesn't my Shell have the trim decorations that I specified in its constructor?
- A: The native window system is responsible for creating the decorations for all windows, and has the right to not fully honor the set of requested decorations.
For this reason, styles that are passed to a Shell's constructor are considered to be hints. For example, on some window managers, creating
a shell with SWT.RESIZE, will also create a minimize and maximize button. This is a constraint that all native applications are subject to.
- Q: Why doesn't a widget send events when I change it programmatically?
- A: This is a design decision that is applied throughout SWT. Events are usually not sent in response to programmatic changes (as opposed to user actions)
in order to minimize notification of potentially unwanted events. As a result, patterns like the following are not needed:
ignoreNextSelectionEvent = true;
myTable.select(2);
ignoreNextSelectionEvent = false;
Since a programmatic change implies that the application is already aware of the change being made, it can trigger the appropriate action directly. If firing
an event is still desired (for instance, to preserve object de-coupling) then the application can create the event and send it to the widget's listeners
with
Widget.notifyListeners(int,Event)
.Note that some specific programmatically-triggered events are sent, typically in response to low-level
widget operations such as focus, move and resize changes.
- Q: Why doesn't my layout update when I create/dispose/move/resize a control?
- A: A layout is only performed automatically on a Composite's children when the Composite
is resized, including when it is initially shown. To make a Composite lay out its
children under any other circumstances, such as when children are created or disposed,
its layout() method must be called. For an example of this see SWT snippet
create and dispose children of a composite.
- Q: How do I programmatically scroll a Composite?
- A: This is done by using a ScrolledComposite instead of a Composite, and invoking
ScrolledComposite.setOrigin(...)
to scroll it. For an example of this see SWT snippetuse a ScrolledComposite to scroll a Tree vertically.
- Q: Why does Copy/Paste sometimes not work on Linux?
- A: There's a known Copy/Paste problem for people who run Klipper Clipboard applet which
causes Eclipse clipboard operations to fail. For more information about this issue see
Bug 153809
Bug 226540.
- Q: Can I use the TaskItem's menu without the launcher?
- A: The TaskItem's menu (also known as Jump List on Windows 7) was designed to be used in conjunction with
the eclipse launcher. That said, it is possible on Windows 7 to overwrite the default values for the items in the
jump list calling
setData()
on the respective menu item using the following keys:For more information about this issue see Bug 306039.
- Q: How do I produce a single jar file that contains all of the various SWT platform jars?
- A: Please see for a complete overview
of how to package the jars.
- Q: How do I enable the fade animation for expando buttons in Trees (Windows Vista and up) ?
- A: The fade in/fade out animation for expando buttons on Trees that can be seen in some applications, like Windows Explorer and older version
of Eclipse, has been disabled. See Bug 342282 for details.
The animation can be enabled by passing the -Dorg.eclipse.swt.internal.win32.enableFadeInOutExpandos argument to the JVM. For example:
eclipse -vmargs -Dorg.eclipse.swt.internal.win32.enableFadeInOutExpandos
will bring the animation back to Eclipse.
Alternatively, the flag
-Dorg.eclipse.swt.internal.win32.enableFadeInOutExpandos
can be added to the end of eclipse'seclipse.ini
for the same result. - Q: What are the standard keyboard shortcuts on Windows, Mac OS X, Linux?
- A: Since SWT uses native controls, standard keyboard shortcuts can be used in SWT applications.
Here is a useful Table of Keyboard Shortcuts.
Eclipse has additional keyboard shortcuts. For a list, type Ctrl + Shift + L.
On Mac OS X, the OS screen reader, VoiceOver, can also be used to navigate through controls using the keyboard.
Here is the VoiceOver User's Manual.
- Q: Can I use a screen reader with Eclipse?
- A: Yes. Eclipse works with JAWS and NVDA on Windows, VoiceOver on the Mac, and Orca on Linux.
Window-Eyes and Hal/SuperNova on Windows have not been tested recently, however they both worked the last time they were tested.
- Q: Why doesn't my old Windows screen reader work with Eclipse 3.6?
- A: JAWS version 8 and 9 and Window-Eyes version 6 no longer work well with Eclipse and other SWT applications.
Window-Eyes 6 will cause Eclipse to crash, and JAWS 8 and 9 can cause SWT applications to crash.
The reason is that Eclipse 3.6 added support for IAccessible2, and these older screen reader versions
contain a partial implementation of IAccessible2 that does not follow the current IAccessible2 specification.
The workaround is to launch eclipse or your SWT application using the
-Dorg.eclipse.swt.accessibility.UseIA2=false
VM argument. For more information about this issue see
Bug 313182.
- Q: How do I get JAWS to read Table column headers?
- A: JAWS does not read table column headers by default.
To get JAWS to read table headers, you need to do the following steps with JAWS running:
- Q: Where can I get more info on Accessibility in Eclipse/SWT?
- A: You can get more information on the Accessibility Features in Eclipse, and the Eclipse/SWT Accessibility API on the
Eclipse/SWT Accessibility wiki.