Monday, May 14, 2012

SWT/JFace Examples

This example contains a lot of examples how to use SWT/JFace components with MigLayout. Not all SWT/JFace components are covered here.
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import net.miginfocom.swt.MigLayout;

import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.MultiStatus;
import org.eclipse.core.runtime.Status;
import org.eclipse.jface.action.Action;
import org.eclipse.jface.action.IAction;
import org.eclipse.jface.action.MenuManager;
import org.eclipse.jface.dialogs.Dialog;
import org.eclipse.jface.dialogs.ErrorDialog;
import org.eclipse.jface.dialogs.IDialogConstants;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.preference.ColorSelector;
import org.eclipse.jface.viewers.CellEditor;
import org.eclipse.jface.viewers.ColumnWeightData;
import org.eclipse.jface.viewers.ComboBoxCellEditor;
import org.eclipse.jface.viewers.ComboViewer;
import org.eclipse.jface.viewers.ICellModifier;
import org.eclipse.jface.viewers.ILabelProviderListener;
import org.eclipse.jface.viewers.IStructuredContentProvider;
import org.eclipse.jface.viewers.ITableLabelProvider;
import org.eclipse.jface.viewers.ITreeContentProvider;
import org.eclipse.jface.viewers.LabelProvider;
import org.eclipse.jface.viewers.ListViewer;
import org.eclipse.jface.viewers.TableLayout;
import org.eclipse.jface.viewers.TableViewer;
import org.eclipse.jface.viewers.TextCellEditor;
import org.eclipse.jface.viewers.TreeViewer;
import org.eclipse.jface.viewers.Viewer;
import org.eclipse.jface.window.ApplicationWindow;
import org.eclipse.jface.wizard.IWizardPage;
import org.eclipse.jface.wizard.Wizard;
import org.eclipse.jface.wizard.WizardDialog;
import org.eclipse.jface.wizard.WizardPage;
import org.eclipse.swt.SWT;
import org.eclipse.swt.dnd.DND;
import org.eclipse.swt.dnd.DropTarget;
import org.eclipse.swt.dnd.DropTargetAdapter;
import org.eclipse.swt.dnd.DropTargetEvent;
import org.eclipse.swt.dnd.FileTransfer;
import org.eclipse.swt.dnd.Transfer;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.SelectionListener;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.DirectoryDialog;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Group;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Menu;
import org.eclipse.swt.widgets.MessageBox;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.TabFolder;
import org.eclipse.swt.widgets.TabItem;
import org.eclipse.swt.widgets.Table;
import org.eclipse.swt.widgets.TableColumn;
import org.eclipse.swt.widgets.TableItem;
import org.eclipse.swt.widgets.Text;

public class SWTApp extends ApplicationWindow {
    public SWTApp() {
        super(null);
        addStatusLine();
    }

    @Override
    protected Control createContents(Composite parent) {
        getStatusLineManager().setMessage("Welcome to SWTApp");

        TabFolder tabFolder = new TabFolder(parent, SWT.NONE);
        TabItem tabItem = new TabItem(tabFolder, SWT.NONE);
        tabItem.setText("Tab 1");
        tabItem.setControl(new MyComposite1(tabFolder));

        tabItem = new TabItem(tabFolder, SWT.NONE);
        tabItem.setText("Tab 2");
        tabItem.setControl(new MyComposite2(tabFolder));

        tabItem = new TabItem(tabFolder, SWT.NONE);
        tabItem.setText("Tab 3");
        tabItem.setControl(new MyComposite3(tabFolder));

        tabItem = new TabItem(tabFolder, SWT.NONE);
        tabItem.setText("Tab 4");
        tabItem.setControl(new MyComposite4(tabFolder));
        
        tabItem = new TabItem(tabFolder, SWT.NONE);
        tabItem.setText("Tab 5");
        tabItem.setControl(new MyComposite5(tabFolder));
        
        getShell().setText("SWTApp");
        getShell().setSize(900, 700);

        return parent;
    };

    static class MyComposite1 extends Composite {
        public MyComposite1(Composite parent) {
            super(parent, SWT.NONE);
            setLayout(new MigLayout("", "[grow][grow]", "[grow, fill]"));

            Group g1 = new Group(this, SWT.SHADOW_ETCHED_IN);
            g1.setLayout(new MigLayout("", "[grow, fill]", "[][grow, fill]"));
            g1.setLayoutData("grow");

            Composite1 c1 = new Composite1(g1);
            c1.setLayoutData("grow, wrap");

            Composite2 c2 = new Composite2(g1);
            c2.setLayoutData("grow");

            Group g2 = new Group(this, SWT.SHADOW_ETCHED_IN);
            g2.setLayout(new MigLayout("", "[grow, fill]", "[grow, fill]"));
            g2.setLayoutData("grow");

            Composite c3 = new Composite3(g2);
            c3.setLayoutData("grow");
        }
    }

    static class Composite1 extends Composite {
        public Composite1(Composite parent) {
            super(parent, SWT.NONE);
            setLayout(new MigLayout("", "[grow, fill][]", "[grow, fill]"));

            Composite c1 = new Composite(this, SWT.NONE);
            c1.setLayout(new MigLayout("", "[][grow]", ""));
            Label field1Label = new Label(c1, SWT.NONE);
            field1Label.setText("Field 1");
            Text field1Text = new Text(c1, SWT.BORDER);
            field1Text.setLayoutData("grow, wrap");

            Label field2Label = new Label(c1, SWT.NONE);
            field2Label.setText("Field 2");
            Text field2Text = new Text(c1, SWT.BORDER);
            field2Text.setLayoutData("grow, wrap");

            Label field3Label = new Label(c1, SWT.NONE);
            field3Label.setText("Field 3");
            Text field3Text = new Text(c1, SWT.BORDER);
            field3Text.setLayoutData("grow, wrap");

            Label field4Label = new Label(c1, SWT.NONE);
            field4Label.setText("Field 4");
            Text field4Text = new Text(c1, SWT.BORDER);
            field4Text.setLayoutData("grow");

            Composite c2 = new Composite(this, SWT.NONE);
            c2.setLayout(new MigLayout("", "", "[grow]"));
            Button startButton = new Button(c2, SWT.NONE);
            startButton.setText("START");
            startButton.setBackground(getDisplay().getSystemColor(SWT.COLOR_GREEN));
            startButton.setLayoutData("grow, wrap");

            Button stopButton = new Button(c2, SWT.NONE);
            stopButton.setText("STOP");
            stopButton.setBackground(getDisplay().getSystemColor(SWT.COLOR_RED));
            stopButton.setLayoutData("grow, wrap");

            Button advancedButton = new Button(c2, SWT.NONE);
            advancedButton.setText("ADVANCED");
            advancedButton.setLayoutData("grow, wrap");

            ColorSelector cs = new ColorSelector(c2);
            Button colorSelectorButton = cs.getButton();
            colorSelectorButton.setText("COLOR");
            colorSelectorButton.setLayoutData("grow");
        }
    }

    static class Composite2 extends Composite {
        public Composite2(Composite parent) {
            super(parent, SWT.NONE);
            setLayout(new MigLayout("", "[grow]", "[grow]"));

            Text statusText = new Text(this, SWT.MULTI | SWT.BORDER);
            statusText.setEditable(false);
            statusText.setLayoutData("grow");
        }
    }

    static class Composite3 extends Composite {
        public Composite3(Composite parent) {
            super(parent, SWT.NONE);
            setLayout(new MigLayout("", "[grow]", "[grow][grow]"));

            Button b1 = new Button(this, SWT.NONE);
            b1.setText("Button 1");
            b1.setLayoutData("grow, wrap");

            Button b2 = new Button(this, SWT.NONE);
            b2.setText("Button 2");
            b2.setLayoutData("grow");
        }
    }

    static class MyComposite2 extends Composite {
        public MyComposite2(Composite parent) {
            super(parent, SWT.NONE);
            setLayout(new MigLayout("", "[grow, fill]", "[grow, fill][]"));

            Composite c1 = new Composite(this, SWT.BORDER);
            c1.setLayout(new MigLayout("", "[grow][grow][grow][grow]", "[grow]"));
            c1.setLayoutData("wrap");

            int[] styles = { SWT.SINGLE, SWT.MULTI };
            for (int style = 0; style < styles.length; style++) {
                ListViewer lv = createListViewer(c1, styles[style]);
                lv.getList().setLayoutData("grow");
            }

            int[] selectionStyle = { SWT.SINGLE, SWT.MULTI };
            int[] checkStyle = { SWT.NONE, SWT.CHECK };

            for (int selection = 0; selection < selectionStyle.length; selection++) {
                for (int check = 0; check < checkStyle.length; check++) {
                    int style = selectionStyle[selection] | checkStyle[check];
                    TreeViewer tv = createTreeViewer(c1, style);
                    tv.getTree().setLayoutData("grow");
                }
            }

            Composite c2 = new Composite(this, SWT.BORDER);
            c2.setLayout(new MigLayout("", "[grow]", ""));
            ComboViewer cv = createComboViewer(c2);
            cv.getCombo().setLayoutData("grow");
        }

        private ComboViewer createComboViewer(Composite parent) {
            ComboViewer viewer = new ComboViewer(parent, SWT.NONE);

            viewer.setLabelProvider(new LabelProvider() {
                @Override
                public String getText(Object element) {
                    return ((ListItem) element).name;
                }
            });

            viewer.setContentProvider(new IStructuredContentProvider() {
                @SuppressWarnings("unchecked")
                @Override
                public Object[] getElements(Object inputElement) {
                    return ((List<ListItem>) inputElement).toArray();
                }

                @Override
                public void dispose() {
                }

                @Override
                public void inputChanged(Viewer viewer, Object oldInput, Object newInput) {
                }
            });

            List<ListItem> input = new ArrayList<ListItem>();
            for (int i = 0; i < 20; i++) {
                input.add(new ListItem("Item " + i, i));
            }
            viewer.setInput(input);

            return viewer;
        }

        private ListViewer createListViewer(Composite parent, int style) {
            ListViewer viewer = new ListViewer(parent, style);

            viewer.setLabelProvider(new LabelProvider() {
                @Override
                public String getText(Object element) {
                    return ((ListItem) element).name;
                }
            });

            viewer.setContentProvider(new IStructuredContentProvider() {
                @SuppressWarnings("unchecked")
                @Override
                public Object[] getElements(Object inputElement) {
                    return ((List<ListItem>) inputElement).toArray();
                }

                @Override
                public void dispose() {
                }

                @Override
                public void inputChanged(Viewer viewer, Object oldInput, Object newInput) {
                }
            });

            List<ListItem> input = new ArrayList<ListItem>();
            for (int i = 0; i < 20; i++) {
                input.add(new ListItem("Item " + i, i));
            }
            viewer.setInput(input);

            return viewer;
        }

        private TreeViewer createTreeViewer(Composite parent, int style) {
            TreeViewer viewer = new TreeViewer(parent, style);

            viewer.setContentProvider(new ITreeContentProvider() {
                public Object[] getChildren(Object parentElement) {
                    return ((TreeNode) parentElement).getChildren().toArray();
                }

                public Object getParent(Object element) {
                    return ((TreeNode) element).getParent();
                }

                public boolean hasChildren(Object element) {
                    return ((TreeNode) element).getChildren().size() > 0;
                }

                public Object[] getElements(Object inputElement) {
                    return ((TreeNode) inputElement).getChildren().toArray();
                }

                public void dispose() {
                }

                public void inputChanged(Viewer viewer, Object oldInput, Object newInput) {
                }
            });

            viewer.setInput(getRootNode());

            return viewer;
        }

        private TreeNode getRootNode() {
            TreeNode root = new TreeNode("root");
            root.addChild(new TreeNode("child 1").addChild(new TreeNode("subchild 1")));
            root.addChild(new TreeNode("child 2").addChild(new TreeNode("subchild 2")
                .addChild(new TreeNode("grandchild 1"))));

            return root;
        }
    }

    static class ListItem {
        public String name;
        public int value;

        public ListItem(String n, int v) {
            name = n;
            value = v;
        }
    }

    static class TreeNode {
        private String name;
        private List<TreeNode> children = new ArrayList<TreeNode>();
        private TreeNode parent;

        public TreeNode(String n) {
            name = n;
        }

        protected Object getParent() {
            return parent;
        }

        public TreeNode addChild(TreeNode child) {
            children.add(child);
            child.parent = this;
            return this;
        }

        public List<TreeNode> getChildren() {
            return children;
        }

        public String toString() {
            return name;
        }
    }

    static class MyComposite3 extends Composite {
        public MyComposite3(Composite parent) {
            super(parent, SWT.NONE);
            setLayout(new MigLayout("", "[grow]", "[grow]"));

            Table table = createTable();
            table.setLayoutData("grow");
        }

        private Table createTable() {
            final String[] VALUE_SET = new String[] {"xxx", "yyy", "zzz"};
            final String NAME_PROPERTY = "name";
            final String VALUE_PROPERTY = "value";

            Table table = new Table(this, SWT.FULL_SELECTION);

            final TableViewer viewer = new TableViewer(table);
            TableLayout layout = new TableLayout();
            layout.addColumnData(new ColumnWeightData(50, 75, true));
            layout.addColumnData(new ColumnWeightData(50, 75, true));
            table.setLayout(layout);

            TableColumn column = new TableColumn(table, SWT.CENTER);
            column.setText("Name");
            column = new TableColumn(table, SWT.NONE);
            column.setText("Value");
            table.setHeaderVisible(true);

            viewer.setLabelProvider(new ITableLabelProvider() {
                @Override
                public void removeListener(ILabelProviderListener lpl) {
                }

                @Override
                public boolean isLabelProperty(Object element, String property) {
                    return false;
                }

                @Override
                public void dispose() {
                }

                @Override
                public void addListener(ILabelProviderListener lpl) {
                }

                @Override
                public String getColumnText(Object element, int columnIndex) {
                    switch (columnIndex) {
                    case 0:
                        return ((EditableTableItem) element).name;
                    case 1:
                        Number index = ((EditableTableItem) element).value;
                        return VALUE_SET[index.intValue()];
                    default:
                        return "Invalid column: " + columnIndex;
                    }
                }

                @Override
                public Image getColumnImage(Object element, int columnIndex) {
                    return null;
                }
            });

            viewer.setContentProvider(new IStructuredContentProvider() {
                @Override
                public void inputChanged(Viewer viewer, Object oldInput, Object newInput) {
                }

                @Override
                public void dispose() {
                }

                @Override
                public Object[] getElements(Object inputElement) {
                    return (Object[]) inputElement;
                }
            });

            viewer.setCellModifier(new ICellModifier() {
                @Override
                public void modify(Object element, String property, Object value) {
                    TableItem tableItem = (TableItem) element;
                    EditableTableItem data = (EditableTableItem) tableItem.getData();
                    if (NAME_PROPERTY.equals(property)) {
                        data.name = value.toString();
                    } else {
                        data.value = (Integer) value;
                    }

                    viewer.refresh(data);
                }

                @Override
                public Object getValue(Object element, String property) {
                    if (NAME_PROPERTY.equals(property)) {
                        return ((EditableTableItem) element).name;
                    } else {
                        return ((EditableTableItem) element).value;
                    }
                }

                @Override
                public boolean canModify(Object element, String property) {
                    return true;
                }
            });

            viewer.setCellEditors(new CellEditor[] {
                new TextCellEditor(table),
                new ComboBoxCellEditor(table, VALUE_SET)
            });

            viewer.setInput(new Object[] {
               new EditableTableItem("Item 1", 0),
               new EditableTableItem("Item 2", 1)
            });

            viewer.setColumnProperties(new String[] {NAME_PROPERTY, VALUE_PROPERTY});

            createMenu(table, viewer);

            return table;
        }

        private void createMenu(Table table, TableViewer viewer) {
            MenuManager popupMenu = new MenuManager();
            IAction newRowAction = new NewRowAction(viewer);
            popupMenu.add(newRowAction);
            Menu menu = popupMenu.createContextMenu(table);
            table.setMenu(menu);
        }
    }

    static class EditableTableItem {
        public String name;
        public Integer value;

        public EditableTableItem(String name, Integer value) {
            this.name = name;
            this.value = value;
        }
    }

    static class NewRowAction extends Action {
        private TableViewer viewer;

        public NewRowAction(TableViewer viewer) {
            super("Insert New Row");
            this.viewer = viewer;
        }

        @Override
        public void run() {
            EditableTableItem newItem = new EditableTableItem(
                "new row", new Integer(2));
            viewer.add(newItem);
        }
    }

    static class MyComposite4 extends Composite {
        public MyComposite4(Composite parent) {
            super(parent, SWT.NONE);
            setLayout(new MigLayout());

            createPasswordDialogButton();
            createMessageDialogButton();
            createMessageBoxButton();
            createErrorDialogButton();
            createWizardDialogButton();
        }

        private Button createPasswordDialogButton() {
            Button dialogButton = new Button(this, SWT.PUSH);
            dialogButton.setText("Password Dialog...");
            dialogButton.addSelectionListener(new SelectionListener() {
                @Override
                public void widgetSelected(SelectionEvent e) {
                    UserNamePasswordDialog d = new UserNamePasswordDialog(getShell());
                    d.open();
                }

                @Override
                public void widgetDefaultSelected(SelectionEvent e) {
                }
            });

            return dialogButton;
        }

        private Button createMessageDialogButton() {
            Button dialogButton = new Button(this, SWT.PUSH);
            dialogButton.setText("Message Dialog...");
            dialogButton.addSelectionListener(new SelectionListener() {
                @Override
                public void widgetSelected(SelectionEvent e) {
                    MessageDialog dialog = new MessageDialog(getShell(),
                        "Greeting Dialog",
                        null, "Hello! How are you today?",
                        MessageDialog.QUESTION,
                        new String[] { "Good", "Been better", "Excited about SWT!" },
                        0);
                    dialog.open();
                }

                @Override
                public void widgetDefaultSelected(SelectionEvent e) {
                }
            });

            return dialogButton;
        }

        private Button createMessageBoxButton() {
            Button dialogButton = new Button(this, SWT.PUSH);
            dialogButton.setText("Message Box...");
            dialogButton.addSelectionListener(new SelectionListener() {
                @Override
                public void widgetSelected(SelectionEvent e) {
                    MessageBox dialog = new MessageBox(getShell(),
                        SWT.OK | SWT.CANCEL);
                    dialog.setMessage("Do you wish to continue?");
                    dialog.open();
                }

                @Override
                public void widgetDefaultSelected(SelectionEvent e) {
                }
            });

            return dialogButton;
        }

        private Button createErrorDialogButton() {
            Button dialogButton = new Button(this, SWT.PUSH);
            dialogButton.setText("Error Dialog...");
            dialogButton.addSelectionListener(new SelectionListener() {
                @Override
                public void widgetSelected(SelectionEvent e) {
                    ErrorDialog errorDialog = new ErrorDialog(getShell(),
                        "Test Error Dialog",
                        "This is a test error dialog",
                        createStatus(),
                        IStatus.ERROR | IStatus.INFO);
                    errorDialog.open();
                }

                @Override
                public void widgetDefaultSelected(SelectionEvent e) {
                }
            });

            return dialogButton;
        }

        private IStatus createStatus() {
            final String dummyPlugin = "some plugin";
            IStatus[] statuses = new IStatus[2];
            statuses[0] = new Status(IStatus.ERROR, dummyPlugin, IStatus.OK,
                "Oh no!  An error occurred!", new Exception());

            statuses[1] = new Status(IStatus.INFO, dummyPlugin, IStatus.OK, "More errors!?!?",
                new Exception());

            MultiStatus multiStatus = new MultiStatus(dummyPlugin, IStatus.OK, statuses,
                "Several errors have occurred.", new Exception());

            return multiStatus;
        }
        
        private Button createWizardDialogButton() {
            Button dialogButton = new Button(this, SWT.PUSH);
            dialogButton.setText("Wizard Dialog...");
            dialogButton.addSelectionListener(new SelectionListener() {
                @Override
                public void widgetSelected(SelectionEvent e) {
                   WizardDialog dialog = new WizardDialog(getShell(),
                       new ProjectWizard());
                   dialog.open();
                }

                @Override
                public void widgetDefaultSelected(SelectionEvent e) {
                }
            });

            return dialogButton;
        }
    }

    static class UserNamePasswordDialog extends Dialog {
        private static final int RESET_ID = IDialogConstants.NO_TO_ALL_ID + 1;
        private Text userNameText;
        private Text passwordText;

        public UserNamePasswordDialog(Shell parentShell) {
            super(parentShell);
        }

        @Override
        protected void configureShell(Shell newShell) {
            super.configureShell(newShell);
            newShell.setText("Username/Password Dialog");
        }
        
        @Override
        protected Control createDialogArea(Composite parent) {
            Composite composite = (Composite) super.createDialogArea(parent);
            composite.setLayout(new MigLayout("", "[][grow]", ""));

            Label userNameLabel = new Label(composite, SWT.NONE);
            userNameLabel.setText("Username: " );
            userNameText = new Text(composite, SWT.SINGLE | SWT.BORDER);
            userNameText.setLayoutData("grow, wrap");

            Label passwordLabel = new Label(composite, SWT.NONE);
            passwordLabel.setText("Password: ");
            passwordText = new Text(composite, SWT.SINGLE | SWT.PASSWORD | SWT.BORDER);
            passwordText.setLayoutData("grow");

            return composite;
        }

        @Override
        protected void createButtonsForButtonBar(Composite parent) {
            super.createButtonsForButtonBar(parent);
            createButton(parent, RESET_ID, "Reset All", false);
        }

        @Override
        protected void buttonPressed(int buttonId) {
            if (buttonId == RESET_ID) {
                userNameText.setText("");
                passwordText.setText("");
            } else {
                super.buttonPressed(buttonId);
            }
        }
    }

    static class DirectoryPage extends WizardPage {
        public static final String PAGE_NAME = "Directory";
        private Button button;

        public DirectoryPage() {
            super(PAGE_NAME, "Directory Page", null);
        }

        @Override
        public void createControl(Composite parent) {
            Composite topLevel = new Composite(parent, SWT.NONE);
            topLevel.setLayout(new MigLayout());

            button = new Button(topLevel, SWT.CHECK);
            button.setText("Use default directory?");

            setControl(topLevel);
            setPageComplete(true);
        }

        public boolean useDefaultDirectory() {
            return button.getSelection();
        }
    }
    
    static class ChooseDirectoryPage extends WizardPage {
        public static final String PAGE_NAME = "Choose Directory";
        private Text text;

        public ChooseDirectoryPage() {
            super(PAGE_NAME, "Choose Directory Page", null);
        }

        @Override
        public void createControl(Composite parent) {
            Composite topLevel = new Composite(parent, SWT.NONE);
            topLevel.setLayout(new MigLayout("", "[][grow][]", ""));

            Label l = new Label(topLevel, SWT.CENTER);
            l.setText("Enter the directory to use:");

            text = new Text(topLevel, SWT.SINGLE | SWT.BORDER);
            text.setEditable(false);
            text.setLayoutData("grow");
            
            Button b = new Button(topLevel, SWT.PUSH);
            b.setText("Choose Directory");
            b.addSelectionListener(new SelectionListener() {
                @Override
                public void widgetSelected(SelectionEvent e) {
                    DirectoryDialog dialog = new DirectoryDialog(getShell());
                    String directory = dialog.open();
                    text.setText(directory);
                }
                
                @Override
                public void widgetDefaultSelected(SelectionEvent e) {
                }
            });

            setControl(topLevel);
            setPageComplete(true);
        }

        public String getDirectory() {
            return text.getText();
        }
    }
    
    static class SummaryPage extends WizardPage {
        public static final String PAGE_NAME = "Summary";
        private Label textLabel;
        private Composite topLevel;

        public SummaryPage() {
            super(PAGE_NAME, "Summary Page", null);
        }

        @Override
        public void createControl(Composite parent) {
            topLevel = new Composite(parent, SWT.NONE);
            topLevel.setLayout(new MigLayout());

            textLabel = new Label(topLevel, SWT.CENTER);
            textLabel.setText("");
            textLabel.setLayoutData("grow");
            
            setControl(topLevel);
            setPageComplete(true);
        }

        public void updateText(String newText) {
            textLabel.setText(newText);
            topLevel.pack();
        }
    }
    
    static class ProjectWizard extends Wizard {
        public void addPages() {
            addPage(new DirectoryPage());
            addPage(new ChooseDirectoryPage());
            addPage(new SummaryPage());
        }

        @Override
        public boolean performFinish() {
            DirectoryPage dirPage = getDirectoryPage();
            if (dirPage.useDefaultDirectory()) {
                System.out.println("Using default directory");
            } else {
                ChooseDirectoryPage choosePage = getChoosePage();
                System.out.println("Using directory: " + choosePage.getDirectory());
            }
            return true;
        }

        private ChooseDirectoryPage getChoosePage() {
            return (ChooseDirectoryPage) getPage(ChooseDirectoryPage.PAGE_NAME);
        }

        private DirectoryPage getDirectoryPage() {
            return (DirectoryPage) getPage(DirectoryPage.PAGE_NAME);
        }

        @Override
        public boolean performCancel() {
            System.out.println("Perform Cancel called");
            return true;
        }

        @Override
        public IWizardPage getNextPage(IWizardPage page) {
            if (page instanceof DirectoryPage) {
                DirectoryPage dirPage = (DirectoryPage) page;
                if (dirPage.useDefaultDirectory()) {
                    SummaryPage summaryPage = (SummaryPage) getPage(SummaryPage.PAGE_NAME);
                    summaryPage.updateText("Using default directory");
                    return summaryPage;
                }
            }

            IWizardPage nextPage = super.getNextPage(page);
            if (nextPage instanceof SummaryPage) {
                SummaryPage summary = (SummaryPage) nextPage;
                DirectoryPage dirPage = getDirectoryPage();
                summary.updateText(dirPage.useDefaultDirectory() ? "Using default directory"
                    : "Using directory: " + getChoosePage().getDirectory());
            }
            return nextPage;
        }
    }
    
    static class MyComposite5 extends Composite {
        public MyComposite5(Composite parent) {
            super(parent, SWT.NONE);
            setLayout(new MigLayout("", "[grow, fill]", "[grow, fill]"));
            
            Text text = createTextArea();
            text.setLayoutData("grow");
        }
        
        private Text createTextArea() {
            Text text = new Text(this, SWT.MULTI | SWT.BORDER);
            
            DropTarget target = new DropTarget(text,
                DND.DROP_MOVE | DND.DROP_COPY | DND.DROP_DEFAULT);
            target.setTransfer(new Transfer[] { FileTransfer.getInstance() });
            target.addDropListener(new DropTargetAdapter() {
                @Override
                public void drop(DropTargetEvent event) {
                    DropTarget target = (DropTarget) event.widget;
                    Text t = (Text) target.getControl();
                    String[] fileList = (String[]) event.data;
                    t.setText(read(fileList[0]));
                } 
            });
            
            return text;
        }
        
        private String read(String path) {
            String text = "";
            BufferedReader br = null;
            try {
                File file = new File(path);
                br = new BufferedReader(new FileReader(file));
                
                String line = "";
                while ((line = br.readLine()) != null) {
                    text += line + System.getProperty("line.separator");
                }
                int lastIndex = text.length() - 
                    System.getProperty("line.separator").length();
                text = text.substring(0, lastIndex);
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                if (br != null) {
                    try {
                        br.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
            return text;
        }
    }
    
    public static void show() {
        SWTApp app = new SWTApp();
        app.setBlockOnOpen(true);
        app.open();
        Display.getCurrent().dispose();
    }
}

No comments:

Post a Comment