Java - SWT - Hello World tutorial

Hello World!
It seems to me that I already seen this expression somewhere.

Well, let's go?

First thing to know is that we need two SWT widgets to make a window appear:

  • Display
  • Shell

Then a loop while to tell the program to continue displaying the window until someone close it.
Now, the code.

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

public class Helloworld {
    public static void main(String[] args) {
        Display display = new Display();
        Shell shell = new Shell(display);
       
        shell.setSize(300, 300);
        shell.setText("Hello World");
        shell.open();
       
        while(!shell.isDisposed())
            if (!display.readAndDispatch())
                display.sleep();
        display.dispose();
    }
}

Right click on the HelloWorld class and run it as a Java Application.
The window is coming and displays the title Hello World.

Really easy, isn't it? surprise

Comments

Comment: 

Thank you for the tutorial. It does sound relatively simple. But when I followed exactly the same instructions which do not differ from Eclipse tutorial - I've got "Error" for the window title. No compilation errors either. I am running Java 9.0.4 and Eclipse Oxygen.2 release 4.7.2.
What could be the problem?

Add new comment

Plain text

  • No HTML tags allowed.
  • Lines and paragraphs break automatically.