我见过这个,但它不适用于我的代码。这是我独特的课程:
public static void main(String[] args) {
try {
Main window = new Main();
window.open();
} catch (Exception e) {
e.printStackTrace();
}
}
public void open() {
Display display = Display.getDefault();
createContents();
shell.open();
shell.layout();
while (!shell.isDisposed()) {
if (!display.readAndDispatch()) {
display.sleep();
}
}
}
protected void createContents() {
shell = new Shell(SWT.CLOSE | SWT.MIN | SWT.TITLE | SWT.ON_TOP);
shell.setSize(301, 212);
shell.setText("MyShell");
// ...Other contents...
btn = new Button(shell, SWT.NONE);
btn.setBounds(114, 151, 76, 25);
btn.setText("BUTTON!");
btn.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
doSomething();
}
});
}
该方法doSomething()
是另一个方法的调用者,如下所示:
private void doSomething()
{
Thread th = new Thread() {
public void run() {
threadMethod();
}
};
th.start();
}
当我点击我的按钮时,一个“无效的线程访问”从 Thread-0 引发,它指向threadMethod()
(wich不访问UI 小部件) 的第一条指令。我试图用我的按钮监听器包围
Display.getDefault().asyncExec(new Runnable() {
public void run() {
// ...
}
});
但它也不起作用。我需要该doSomething()
方法,因为它在创建线程之前会检查一些代码。这是线程方法()
private void threadMethod()
{
String[] listItems = list.getItems();
String fileName;
Path source, target;
File folder = new File(dir + File.separator);
if (!folder.exists()) {
folder.mkdir();
}
try
{
for(int i = 0; i < list.getItemCount(); i++)
{
// do something with non UI widgets
}
list.removeAll();
}
catch(IOException | InterruptedException e)
{
//print error
}
}
为什么我有无效的线程访问?谢谢!