简体   繁体   English

如何同步两个swt按钮的事件?

[英]How to synchronize events of two swt buttons?

I have two SWT buttons, button("Start") & button("Stop"). 我有两个SWT按钮,即button(“ Start”)和button(“ Stop”)。 When I press on "Start", I call a method: printFiles(inputPath, printer) //scans "inputPath" directory for pdfs and sends them to the printer "printer" 当我按“开始”时,我调用一个方法:printFiles(inputPath,printer)//扫描“ inputPath”目录中的pdf,并将它们发送到打印机“ printer”

I want printFiles(inputPath, printer) to run always, untill I press the button("Stop"). 我希望printFiles(inputPath,printer)始终运行,直到我按下按钮(“ Stop”)为止。 So, that was my first thoughts how to do it. 所以,那是我的第一个想法。

//button("Start")
btnStart.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent arg0) {
    keepPrinting=true;
    while(keepPrinting){
        printFiles(inputPath, printer);
    }
}
});

//button("Stop")
btnStop.addSelectionListener(new SelectionAdapter() {
        @Override
        public void widgetSelected(SelectionEvent arg0) {
            keepPrinting=false;
        }
});

But, there is an obvious problem. 但是,有一个明显的问题。 When I press on button("Start"), it never gets back from the while(true) loop. 当我按下按钮(“开始”)时,它永远不会从while(true)循环中返回。 As a result, the whole window (shell) stops responding. 结果,整个窗口(外壳)停止响应。

Do you have any idea how to put an endless loop inside button's press Listener? 您是否知道如何在按钮的按下侦听器内放置一个无限循环?

My instict says I have to use concurrency, to synchronize these two buttons somehow. 我的分析师说,我必须使用并发,以某种方式同步这两个按钮。 If that's correct, could you give some hints how to implemnt that? 如果是正确的话,您能给一些暗示如何暗示的提示吗?

Many thanks! 非常感谢!

You shouldn't execute lengthy tasks on the GUI thread. 您不应该在GUI线程上执行冗长的任务。 Instead, start a new thread to do the work. 而是,启动一个新线程来完成工作。 In this simple case, you don't need complicated synchronization mechanisms, just replace 在这种简单情况下,您不需要复杂的同步机制,只需替换

while(keepPrinting){
    printFiles(inputPath, printer);
}

with

new Thread() {
    @Override
    public void run() {
        while (keepPrinting) {
            printFiles(inputPath, printer);
        }
    }               
}.start();

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

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