如何刷新SWT标签?

时间:2015-09-18 09:52:48

标签: java user-interface label swt

我构建了一个FileDialog,在用户选择其中的文件后,应使用文件名更新标签。这就是我所拥有的:

Button buttonSelectFile;
fileFilterPath = "C:/";
Label myDir;

fileSelectionLabel = new Label(container, SWT.None | SWT.WRAP);
fileSelectionLabel.setText("Path to file");

buttonSelectFile = new Button(container, SWT.PUSH);
buttonSelectFile.setText("Select file");
buttonSelectFile.addListener(SWT.Selection, new Listener() {
    @Override
    public void handleEvent(Event event) {
        Shell shell = new Shell();
        FileDialog fileDialog = new FileDialog(shell, SWT.MULTI);
        fileDialog.setFilterPath(fileFilterPath);
        fileDialog.setFilterExtensions(new String[] { "*.exe" });
        fileDialog.setFilterNames(new String[] { "exe-files" });

        String files = fileDialog.open();
        if (files != null) {
            fileFilterPath = fileDialog.getFilterPath();
            selectedFile = fileDialog.getFileName();
            StringBuffer sb = new StringBuffer(
                    "Selected file under directory "
                            + fileDialog.getFilterPath() + "\n");
            sb.append(selectedFile);
        }
    }
});

myDir = new Label(container, SWT.None);
new Label(container, SWT.None).setText("");

我尝试在myDir.setText(fileFilterPath)方法中调用handleEvent()。还尝试拨打myDir.layout()myDir.refresh()myDir.getParent().layout()。标签不刷新。

如何刷新标签文字?

1 个答案:

答案 0 :(得分:6)

在父母身上调用layout()似乎在这里工作得很好:

public static void main(String[] args)
{
    final Display display = new Display();
    final Shell shell = new Shell(display);
    shell.setText("StackOverflow");
    shell.setLayout(new GridLayout(2, false));

    final Label label = new Label(shell, SWT.NONE);

    Button button = new Button(shell, SWT.PUSH);
    button.setText("Click me!");
    button.addListener(SWT.Selection, new Listener()
    {
        @Override
        public void handleEvent(Event event)
        {
            label.setText(label.getText() + " test");
            label.getParent().layout();
        }
    });

    shell.pack();
    shell.setSize(400, 300);
    shell.open();
    while (!shell.isDisposed())
    {
        if (!display.readAndDispatch())
            display.sleep();
    }
    display.dispose();
}

这也是推荐的解决方案: