使用 SWT 时我无法显示 Shell。当我作为单独的线程运行代码时,它可以工作。但是,我在 SWT 显示线程上需要它 - 在移动到 SWT 显示线程后,它无法显示。
这是我的代码:
public class TestSetup extends Canvas {
private Shell shell;
public void voiceInitialise() {
Display.getDefault().syncExec(new Runnable() {
public void run() {
initializeComponents();
runEventLoop();
}
});
}
public void initializeComponents() {
shell = SWT_AWT.new_Shell(new Display(), this);
}
public void runEventLoop() {
Thread curThread = Thread.currentThread();
curThread.setName(curThread.getName() + " SWT Dispatch");
Display display = Display.getDefault();
testSetup();
while (!shell.isDisposed()) {
if (!display.readAndDispatch()) {
display.sleep();
}
}
}
public void testSetup() {
shell.setText("Title");
GridLayout layout = new GridLayout(2, false);
shell.setSize(530, 320);
shell.setLayout(layout);
shell.open();
}
public static void main(String[] args) {
TestSetup t = new TestSetup();
t.voiceInitialise();
}
}
它只是给了我这个异常:“线程“main”org.eclipse.swt.SWTException中的异常:无效的线程访问”
如果有人知道如何解决请告诉我。
最佳答案
正如 GGrec 指出的那样,你的代码相当矫枉过正。
根据您的代码,我假设您正在尝试将 SWT 嵌入到 AWT 中,因此您的类应该如下所示:
import java.awt.BorderLayout;
import java.awt.Canvas;
import java.awt.Frame;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import org.eclipse.swt.SWT;
import org.eclipse.swt.awt.SWT_AWT;
import org.eclipse.swt.graphics.Color;
import org.eclipse.swt.graphics.RGB;
import org.eclipse.swt.layout.FillLayout;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Shell;
public class SWTEmbeddedExample {
public static void main(String[] args) {
//AWT frame comes here
Frame frame = new Frame("My AWT Application");
Canvas parentCanvas = new Canvas();
frame.add(parentCanvas, BorderLayout.CENTER);
frame.pack();
//SWT_AWT bridge
final Display display = Display.getDefault();
final Shell shell = SWT_AWT.new_Shell(display, parentCanvas);
shell.setLayout(new FillLayout(SWT.VERTICAL));
//SWT label with text and red background
Label label = new Label(shell, SWT.NONE);
label.setText("My embedded SWT label");
label.setBackground(new Color(display, new RGB(255, 0, 0)));
//AWT frame config goes here
frame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
e.getWindow().dispose();
//optionally also dispose display
}
});
frame.setSize(800, 600);
frame.setVisible(true);
//ReadAndDispatch display as long as frame is displayed
while (frame.isDisplayable()) {
if (!display.readAndDispatch()) {
display.sleep();
}
}
}
}
关于java - SWT 中未显示外壳,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20358314/