简体   繁体   English

如何释放按下的Java按钮

[英]How to release a pressed java button

I have java method that executes a very long model. 我有执行非常长的模型的java方法。 It takes about 20 minutes. 大约需要20分钟。 When I press the button, the button remains pressed until the model is finished. 当我按下按钮时,按钮保持按下状态,直到模型完成。 I need to create a button that when is pressed, it stop the model execution So far I have 2 buttons: Stop and Start. 我需要创建一个按钮,当按下该按钮时,它将停止模型执行。到目前为止,我有2个按钮:“停止”和“启动”。 My problem is that when I press the start button, all the buttons from the GUI are freeze and they cannot be pressed until the model finishes 我的问题是,当我按下开始按钮时,GUI中的所有按钮都被冻结,并且在模型完成之前无法按下它们

How can I create a stop button? 如何创建停止按钮?

Thank you, 谢谢,

Ionut 约努茨

You should use a SwingWorker . 您应该使用SwingWorker They are specifically designed for performing long running tasks off of the EDT while still being able to update the GUI with progress reports. 它们是专门为在EDT之外执行长时间运行的任务而设计的 ,同时仍然能够使用进度报告来更新GUI。

It is best to start a Thread once the button is clicked. 最好在单击按钮后启动一个线程。 You could make a stop button that stops the thread if it has not finished yet. 您可以创建一个停止按钮,以在线程尚未完成时将其停止。 For this you will have to keep track of the Thread though (for example in a static variable). 为此,您将必须跟踪线程(例如,在静态变量中)。

A quick guide to threading: http://www.tutorialspoint.com/java/java_multithreading.htm 线程快速指南: http : //www.tutorialspoint.com/java/java_multithreading.htm

Please take a look at this as well: How to properly stop the Thread in Java? 请同时看一下: 如何正确停止Java中的线程? .

如果您正在执行20分钟的任务以响应按钮单击,则您可能应该在后台线程中执行该任务。

You have to use multi-threading. 您必须使用多线程。 A basic example- 一个基本的例子

public class ThreadTest {

    private int getSum(int x, int y){
        return x + y;
    }

    public static void main(String args[]) {

        ThreadTest tTest = new ThreadTest();        
        System.out.println(tTest.getSum(2, 5));
        // Start the thread
        new LongProcess().start();        
        // Since the thread sleeps for two seconds
        // You will see 5 + 5 = 10 before Done! gets printed out
        System.out.println(tTest.getSum(5, 5));

    }
}

class LongProcess extends Thread {

    public LongProcess(){
        System.out.println("Thread started.."); 
    }

    public void run() {
        try{                   
            Thread.sleep(2000);
            System.out.println("Done!");        
        } catch(InterruptedException iEx){
            System.out.println(iEx.toString());        
        }
    }
}

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

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