Java SWT y acceso a subprocesos no válido
He vistoesta pero no funciona para mi código. Esta es mi clase única:
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();
}
});
}
El métododoSomething()
es una persona que llama para otro método, como este:
private void doSomething()
{
Thread th = new Thread() {
public void run() {
threadMethod();
}
};
th.start();
}
Cuando hago clic en mi botón, aparece un "Acceso de subproceso no válido" desde Thread-0, y apunta a la primera instrucción dethreadMethod()
(cualesno accede a los widgets de la interfaz de usuario). He intentado rodear a mi oyente de botones con
Display.getDefault().asyncExec(new Runnable() {
public void run() {
// ...
}
});
pero tampoco funciona. Necesito eldoSomething()
Método porque comprueba algún código antes de crear el hilo. Esto es threadMethod ()
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
}
}
¿Por qué tengo acceso al hilo no válido? ¡Gracias!