我正在努力寻找一种方法来正确填充需要一些时间的SWT GUI元素(即:我不希望它挂起APP)。目前我正在这样做,但我觉得必须有更好的方法。
我必须这样做的原因是:
原谅任何代码错误 - 我正在从现有项目中复制和粘贴。
public class Gui {
protected Shell shell;
private Display display;
private SomeController someController;
private Label statusLabel;
public void createControllers(){
someController = new someController(this);
}
public void open() {
this.display = Display.getDefault();
createContents();
shell.open();
shell.layout();
while (!shell.isDisposed()) {
if (!display.readAndDispatch()) {
display.sleep();
}
}
}
protected void createContents() {
// Create a bunch of stuff
statusLabel = new Label(shell, SWT.NONE);
fd_tabFolder.bottom = new FormAttachment(statusLabel, -6);
Button btnStart = new Button(composite_1, SWT.NONE);
btnStart.addSelectionListener(new SelectionListener() {
public void widgetDefaultSelected(SelectionEvent arg0) {
}
public void widgetSelected(SelectionEvent arg0) {
someController.setStatus("some status");
}
});
}
private Label getStatusLabel(){
return(statusLabel);
}
public Display getDisplay(){
return(display);
}
}
public class SomeController {
private Gui gui;
private Label statusLabel;
public SomeController(Gui gui)
this.gui = gui;
this.statusLabel = gui.getStatusLabel();
}
public void setStatus(String status){
Thread t = new Thread(new SetStatus(status));
t.start();
}
private void setStatusToGui(String status){
gui.getDisplay().asyncExec(new SetStatusRunnable(status));
}
public class SetStatus implements Runnable{
private String status;
public SetStatus(String status){
this.status = status;
}
public void run() {
setStatusToGui(status);
}
}
public class SetStatusRunnable implements Runnable{
private String status;
public SetStatusRunnable(String status){
this.status = status;
}
public void run() {
statusLabel.setText(status);
}
}
}