0

当我使用 Swing 时,我能够做这样的事情..

java.awt.EventQueue.invokeLater(new Runnable() { 
public void run() { 
gui = new GUI();
gui.setVisible(true); 
}
}

现在我正在使用 SWT,我正在尝试使用相同的方式创建一个 GUI。要么 gui 不会出现,要么 gui 将冻结。我试图从另一个类中调用它,因为我正在将它开发为整个应用程序的模块。

这就是我到目前为止所尝试的方式..

gui = new GUI();
gui.open();

我也试过上面的括号,但我没有运气。

这是gui类

package org.eclipse.swt.snippets;

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

public class GUI {

protected Shell shell;

/**
 * Launch the application.
 * @param args
 */
public static void main(String[] args) {
    try {
        GUI window = new GUI();
        window.open();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

/**
 * Open the window.
 */
public void open() {
    Display display = Display.getDefault();
    createContents();
    shell.open();
    shell.layout();
    while (!shell.isDisposed()) {
        if (!display.readAndDispatch()) {
            display.sleep();
        }
    }
}

/**
 * Create contents of the window.
 */
protected void createContents() {
    shell = new Shell();
    shell.setSize(450, 300);
    shell.setText("SWT Application");

}

}

我曾尝试编辑 gui 类以形成构造函数,但仍然没有运气

4

1 回答 1

0

I'm pretty sure the problem is coming from shell = new Shell(). As far as I remember, the Display has to passed to the Shell constructor so it knows where to attach.

I would change it to something like this and try it:

/**
 * Open the window.
 */
public void open() {
    Display display = Display.getDefault();
    createContents(display);
    shell.open();
    shell.layout();
    while (!shell.isDisposed()) {
        if (!display.readAndDispatch()) {
            display.sleep();
        }
    }
}

/**
 * Create contents of the window.
 */
protected void createContents(Display display) {
    shell = new Shell(display);
    shell.setSize(450, 300);
    shell.setText("SWT Application");

I don't have Eclipse or SWT on this machine, though, so I can't test it and am going off memory of how the SWT hierarchy works.

于 2012-05-02T20:50:05.323 回答