Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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. 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. Also tried to call myDir.layout(), myDir.refresh() and myDir.getParent().layout(). The label doesn't refresh.

How to refresh the label text?

like image 933
John Avatar asked Feb 10 '23 00:02

John


1 Answers

Calling layout() on the parent seems to work just fine here:

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:

  • SWT label size is not correctly updated
  • Java RCP - Not able to dynamically set text to SWT label control
like image 73
Baz Avatar answered Feb 11 '23 14:02

Baz