简体   繁体   中英

Java SWT Update Text control

I've written much java code since 1996, but never tried SWT. I though I'd pick something really simple to start with, but I became stuck quite early on, even with the several SWT/Jface/RCP books before me which do not help me with my problem.

I am trying to make a command line application run in an SWT window. It does not need any kind of input from the user, it just needs to show sysout. The application rarely generates more than 30 lines of sysout.

public class TestGui implements Runnable {

private Display display;
private Shell shell;
private Text text;

public void run() {
    display = new Display();
    shell = new Shell(display, SWT.DIALOG_TRIM);
    shell.setText("SWT Test");
    shell.setSize(new Point(800, 400));
    shell.setLayout(new FillLayout());
    text = new Text(shell, SWT.MULTI | SWT.V_SCROLL | SWT.READ_ONLY);
    shell.open();
    while (!shell.isDisposed()) {
        if (!display.readAndDispatch())
            display.sleep();
    }
}

void addMessage(String s) {
    text.append(s);
    text.append("\n");
}

void close() {
    display.dispose();
}

public static void main(String[] args) {
    TestGui pr = new TestGui();
    pr.run();
    pr.addMessage("add some text");
    pr.close();
}
 }

I run this and I see the window with the cursor blinking reassuringly, but nothing else appears in it. I do not seem able to make the call to the addMessage() method run until I close the window, and of course by then the Shell is disposed, so I get an exception.

I'm sure I have missed a key step...

Thanks

chris

The problem is that the while loop in your run method waits until the display is actually disposed , so this way the run method can only finish after the display is disposed.

I'm not an expert with SWT, but try moving the while loop into your main method, or move the call(s) to addMessage into your run method. Whatever way you do it, you have to add the messages before waiting for the frame to be disposed.

The problem in the original example I posted was that the code to add the messages never got executed, as noted by the replies. So I spun off a separate thread and called the messages from there. I am still working on it, and will post a refresh when I have time to get it all working correctly.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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