简体   繁体   English

如何刷新SWT标签?

[英]How to refresh SWT label?

I built an FileDialog and after the user selects the file in it a label should be updated with the file name. 我建立了一个FileDialog ,在用户选择其中的文件后,应使用文件名更新标签。 This is what I have: 这就是我所拥有的:

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("");

I tried calling myDir.setText(fileFilterPath) inside the handleEvent() method. 我尝试在handleEvent()方法内调用myDir.setText(fileFilterPath) Also tried to call myDir.layout() , myDir.refresh() and myDir.getParent().layout() . 还尝试调用myDir.layout()myDir.refresh()myDir.getParent().layout() The label doesn't refresh. 标签不会刷新。

How to refresh the label text? 如何刷新标签文字?

Calling layout() on the parent seems to work just fine here: 在父级上调用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();
}

It's also the recommended solution here: 这里也是推荐的解决方案:

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM