Tuesday, April 1, 2008

[Java] Introducing GUI with Swing and SWT

These days I'm having a look at JAVA GUIs, playing with different 2D libraries: AWT, JFC/Swing, SWT and JFace.
Actually AWT is the base library for 2D issues and lacks of several common controls (see figure, taken from here).

To fulfill those lacks, the JRE comes with the Java Foundation Classes (JFC) / Swing libraries, with all kind of controls, allowing the creation of complex GUIs.
If anyway you are looking for something quick to implement, you should use the SWT (Standard Widget Toolkit) library, based upon Swing and AWT, created by IBM as the graphic constituent for Eclipse Framework (actually over SWT lies JFace, a graphic library created to support common programming features, not treated in this post).
In Swing controls are disposed automatically by the garbage collector, while in SWT you have manually to dispose them, like in the current example in which a simple window with a lable is created:

import java.awt.GridLayout;
import javax.swing.JFrame;
import javax.swing.JLabel;

public class SwingHelloWorld extends JFrame {

public static void main(String args[]) {
new SwingHelloWorld();
SwingHelloWorld() {
JLabel jlbHelloWorld = new JLabel("Just a label");
setTitle("Example Frame");
setLayout(new GridLayout());
this.setSize(300, 100);


import org.eclipse.swt.SWT;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Shell;

public class SWTHelloWorld {
public static void main(String[] args) {
Display display = new Display();
final Shell shell = new Shell(display);
shell.setText("Example Frame");
shell.setLayout(new GridLayout());

/* controls code goes here */
Label label1 = new Label(shell, SWT.BORDER);
label1.setText("Just a label");


As seen in Swing the main class is inherited straight from the JFrame Swing class, while in the SWT version there is the Display object that is a repository of display OS-dependent features and a Shell which is the actual window: you can have several shells for one display. Moreover in the SWT code there is a while loop, which waits for the disposal of the shell (done by the close button [X]) and in that case the main class disposes the Display instance (actually the disposal of all objects is done automatically by the container's dispose event, i.e. by the disposal of the shell).

Another difference between the two libraries is the graphical look:


It is clear that SWT library depends on the OS look (thanks to the Display object), while Swing uses typical JAVA interface.

If you are planning to learn basics of JAVA GUIs, try first with Swing and than switch to SWT, so you'll gain a wide view of those technologies and learn for each application the one which suites your needs.

Hope JohnnyIdol learned something... he just got served.

Stay tuned!

1 comment:

Elsa said...

se ti va passa dal mio blog a leggere una storia di Sardegna