User Tools

Site Tools


blog:needed_more_readable_swt_snippets

Differences

This shows you the differences between two versions of the page.

Link to this comparison view

Both sides previous revision Previous revision
blog:needed_more_readable_swt_snippets [2008/05/06 13:23]
djo Discussion status changed
blog:needed_more_readable_swt_snippets [2014/10/17 22:08] (current)
Line 1: Line 1:
 +====== Needed More Readable SWT Snippets ======
 +
 +When creating small examples to illustrate a single SWT programming technique, the SWT team has been utilizing what they call //​snippets,//​ or minimal SWT applications. These are great if you need to see at a glance everything related to the particular application in question.
 +
 +However, suppose you are trying to illustrate a technique for working with, for example, the Label widget. In this case, all the housekeeping chores of creating the SWT Display, running the SWT event loop, and disposing of everything afterward just get in the way of communicating the technique you are trying to illustrate.
 +
 +In other words, in order to illustrate SWT label usage, you'd really like to write something like the following:
 +
 +<code java>
 +public class Hello extends Snippet {
 +    public void setupUI(Shell parent) {
 +        parent.setLayout(new FillLayout());​
 +        new Label(parent,​ SWT.NULL).setText("​Hello,​ world"​);​
 +    }
 +
 +    public static void main(String[] args) {
 +        new Hello();
 +    }
 +}
 +</​code>​
 +
 +I realized I had an itch; I just had to scratch it. Here's the result:
 +
 +<code java>
 +public class Snippet {
 +
 +    public Snippet() {
 +        Display display = new Display();
 +        shell = new Shell(display);​
 +
 +        setupUI(shell);​
 +
 +        shell.setSize(getDefaultSize());​
 +        shell.open();​
 +        while (!shell.isDisposed()) {
 +            if (!display.readAndDispatch())
 +                display.sleep();​
 +        }
 +        display.dispose();​
 +
 +        afterClose();​
 +    }
 +
 +    private Shell shell;
 +
 +    // Returns the application shell
 +    protected Shell getShell() {
 +        return shell;
 +    }
 +
 +    // Override this method to set up your UI
 +    public void setupUI(Shell parent) {
 +    }
 +
 +    // Override this method to do something after the Shell closes
 +    // (print results, debug info, etc.).
 +    public void afterClose() {
 +    }
 +
 +    // Override this method to set a new default Shell size
 +    protected Point getDefaultSize() {
 +        return new Point(800, 600);
 +    }
 +}
 +</​code>​
 +
 +Feel free to use this code however you like, subject to the license terms at the bottom of this page.
 +
 +~~LINKBACK~~
 +~~DISCUSSION:​closed~~