Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/320.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
获取Java ProgressMonitor的取消事件_Java_Multithreading_Swing_Swingworker_Progressmonitor - Fatal编程技术网

获取Java ProgressMonitor的取消事件

获取Java ProgressMonitor的取消事件,java,multithreading,swing,swingworker,progressmonitor,Java,Multithreading,Swing,Swingworker,Progressmonitor,我有一个ProgressMonitorpm和一个SwingWorkersw。我想在按下pm上的cancel-按钮时取消SwingWorker。我想这不应该太难,我读了一些关于SwingWorker和ProgressMonitor的教程,但我不能让它工作 final ProgressMonitor pm = new ProgressMonitor(frame, "checking", "...", 0, 100); final SwingWorker sw = new SwingWorker()

我有一个ProgressMonitor
pm
和一个SwingWorker
sw
。我想在按下
pm
上的
cancel
-按钮时取消SwingWorker。我想这不应该太难,我读了一些关于SwingWorker和ProgressMonitor的教程,但我不能让它工作

final ProgressMonitor pm = new ProgressMonitor(frame, "checking", "...", 0, 100);
final SwingWorker sw = new SwingWorker()
{
    protected Object doInBackground() throws Exception 
    {
        doSomethingAndUpdateProgress();
    }
};

sw.addPropertyChangeListener(new PropertyChangeListener()
{
    public void propertyChange(PropertyChangeEvent evt)
    {
        if(evt.getPropertyName().equals("progress"))
        {
            updateProgress();
        }
        if(pm.isCanceled())
        {
            cancelAction();
        }
        if(pm.isDone())
        {
            doneAction();
        }
    }
});

sw.execute();
进度更新工作正常,但是
pm.isCanceled()
永远不会
true
。我想我需要一个ProgressMonitor的propertyChangeListener,但我不知道如何在那里添加一个

我读了一些关于SwingWorker和ProgressMonitor的教程,但我不能让它工作

final ProgressMonitor pm = new ProgressMonitor(frame, "checking", "...", 0, 100);
final SwingWorker sw = new SwingWorker()
{
    protected Object doInBackground() throws Exception 
    {
        doSomethingAndUpdateProgress();
    }
};

sw.addPropertyChangeListener(new PropertyChangeListener()
{
    public void propertyChange(PropertyChangeEvent evt)
    {
        if(evt.getPropertyName().equals("progress"))
        {
            updateProgress();
        }
        if(pm.isCanceled())
        {
            cancelAction();
        }
        if(pm.isDone())
        {
            doneAction();
        }
    }
});

sw.execute();
取消总是调用InteruptedExeption

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.util.ArrayList;

public class SwingWorkerExample extends JFrame implements ActionListener {

    private static final long serialVersionUID = 1L;
    private final JButton startButton, stopButton;
    private JScrollPane scrollPane = new JScrollPane();
    private JList listBox = null;
    private DefaultListModel listModel = new DefaultListModel();
    private final JProgressBar progressBar;
    private mySwingWorker swingWorker;

    public SwingWorkerExample() {
        super("SwingWorkerExample");
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        getContentPane().setLayout(new GridLayout(2, 2));
        startButton = makeButton("Start");
        stopButton = makeButton("Stop");
        stopButton.setEnabled(false);
        progressBar = makeProgressBar(0, 99);
        listBox = new JList(listModel);
        scrollPane.setViewportView(listBox);
        getContentPane().add(scrollPane);
        //Display the window.
        pack();
        setVisible(true);
    }
//Class SwingWorker<T,V> T - the result type returned by this SwingWorker's doInBackground
//and get methods V - the type used for carrying out intermediate results by this SwingWorker's
//publish and process methods

    private class mySwingWorker extends javax.swing.SwingWorker<ArrayList<Integer>, Integer> {
//The first template argument, in this case, ArrayList<Integer>, is what s returned by doInBackground(),
//and by get(). The second template argument, in this case, Integer, is what is published with the
//publish method. It is also the data type which is stored by the java.util.List that is the parameter
//for the process method, which recieves the information published by the publish method.

        @Override
        protected ArrayList<Integer> doInBackground() {
//Returns items of the type given as the first template argument to the SwingWorker class.
            if (javax.swing.SwingUtilities.isEventDispatchThread()) {
                System.out.println("javax.swing.SwingUtilities.isEventDispatchThread() returned true.");
            }
            Integer tmpValue = new Integer(1);
            ArrayList<Integer> list = new ArrayList<Integer>();
            for (int i = 0; i < 100; i++) {
                for (int j = 0; j < 100; j++) { //find every 100th prime, just to make it slower
                    tmpValue = FindNextPrime(tmpValue.intValue());
//isCancelled() returns true if the cancel() method is invoked on this class. That is the proper way
//to stop this thread. See the actionPerformed method.
                    if (isCancelled()) {
                        System.out.println("SwingWorker - isCancelled");
                        return list;
                    }
                }
//Successive calls to publish are coalesced into a java.util.List, which is what is received by process,
//which in this case, isused to update the JProgressBar. Thus, the values passed to publish range from
//1 to 100.
                publish(new Integer(i));
                list.add(tmpValue);
            }
            return list;
        }//Note, always use java.util.List here, or it will use the wrong list.

        @Override
        protected void process(java.util.List<Integer> progressList) {
//This method is processing a java.util.List of items given as successive arguments to the publish method.
//Note that these calls are coalesced into a java.util.List. This list holds items of the type given as the
//second template parameter type to SwingWorker. Note that the get method below has nothing to do with the
//SwingWorker get method; it is the List's get method. This would be a good place to update a progress bar.
            if (!javax.swing.SwingUtilities.isEventDispatchThread()) {
                System.out.println("javax.swing.SwingUtilities.isEventDispatchThread() + returned false.");
            }
            Integer percentComplete = progressList.get(progressList.size() - 1);
            progressBar.setValue(percentComplete.intValue());
        }

        @Override
        protected void done() {
            System.out.println("doInBackground is complete");
            if (!javax.swing.SwingUtilities.isEventDispatchThread()) {
                System.out.println("javax.swing.SwingUtilities.isEventDispatchThread() + returned false.");
            }
            try {
//Here, the SwingWorker's get method returns an item of the same type as specified as the first type parameter
//given to the SwingWorker class.
                ArrayList<Integer> results = get();
                for (Integer i : results) {
                    listModel.addElement(i.toString());
                }
            } catch (Exception e) {
                System.out.println("Caught an exception: " + e);
            }
            startButton();
        }

        boolean IsPrime(int num) { //Checks whether a number is prime
            int i;
            for (i = 2; i <= num / 2; i++) {
                if (num % i == 0) {
                    return false;
                }
            }
            return true;
        }

        protected Integer FindNextPrime(int num) { //Returns next prime number from passed arg.
            do {
                if (num % 2 == 0) {
                    num++;
                } else {
                    num += 2;
                }
            } while (!IsPrime(num));
            return new Integer(num);
        }
    }

    private class TaskListener implements PropertyChangeListener {

        private String name;

        TaskListener(String name) {
            this.name = name;
        }

        @Override
        public void propertyChange(PropertyChangeEvent e) {
            System.out.println(name + ": "
                    + e.getOldValue() + " -> " + e.getNewValue());
        }
    }

    private JButton makeButton(String caption) {
        JButton b = new JButton(caption);
        b.setActionCommand(caption);
        b.addActionListener(this);
        getContentPane().add(b);
        return b;
    }

    private JProgressBar makeProgressBar(int min, int max) {
        JProgressBar progressBar1 = new JProgressBar();
        progressBar1.setMinimum(min);
        progressBar1.setMaximum(max);
        progressBar1.setStringPainted(true);
        progressBar1.setBorderPainted(true);
        getContentPane().add(progressBar1);
        return progressBar1;
    }

    private void startButton() {
        startButton.setEnabled(true);
        stopButton.setEnabled(false);
        System.out.println("SwingWorker - Done");
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        if ("Start" == null ? e.getActionCommand() == null : "Start".equals(e.getActionCommand())) {
            startButton.setEnabled(false);
            stopButton.setEnabled(true);
// Note that it creates a new instance of the SwingWorker-derived class. Never reuse an old one.
            (swingWorker = new mySwingWorker()).execute(); // new instance
            swingWorker.addPropertyChangeListener(new TaskListener("Task"));

        } else if ("Stop" == null ? e.getActionCommand() == null : "Stop".equals(e.getActionCommand())) {
            startButton.setEnabled(true);
            stopButton.setEnabled(false);
            swingWorker.cancel(true); // causes isCancelled to return true in doInBackground
            swingWorker = null;
        }
    }

    public static void main(String[] args) {
// Notice that it kicks it off on the event-dispatching thread, not the main thread.
        SwingUtilities.invokeLater(new Runnable() {

            @Override
            public void run() {
                SwingWorkerExample swingWorkerExample = new SwingWorkerExample();
            }
        });
    }
}
import javax.swing.*;
导入java.awt.*;
导入java.awt.event.*;
导入java.beans.PropertyChangeEvent;
导入java.beans.PropertyChangeListener;
导入java.util.ArrayList;
公共类SwingWorkerExample扩展JFrame实现ActionListener{
私有静态最终长serialVersionUID=1L;
专用最终按钮开始按钮、停止按钮;
私有JScrollPane scrollPane=新JScrollPane();
private JList listBox=null;
private DefaultListModel listModel=新的DefaultListModel();
私人最终JProgressBar progressBar;
私人mySwingWorker swingWorker;
公共SwingWorkerExample(){
超级(“SwingWorkerExample”);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
getContentPane().setLayout(新的GridLayout(2,2));
startButton=makeButton(“开始”);
stopButton=makeButton(“停止”);
stopButton.setEnabled(错误);
progressBar=makeProgressBar(0,99);
listBox=新的JList(listModel);
scrollPane.setViewportView(列表框);
getContentPane().add(滚动窗格);
//显示窗口。
包装();
setVisible(真);
}
//类SwingWorker T-此SwingWorker的doInBackground返回的结果类型
//并得到方法V——该SwingWorker的方法用于执行中间结果的类型
//发布和处理方法
私有类MyWingWorker扩展了javax.swing.SwingWorker{
//第一个模板参数(在本例中为ArrayList)是doInBackground()返回的参数,
//第二个模板参数,在本例中为Integer,是使用
//publish方法。它也是参数java.util.List存储的数据类型
//对于process方法,它接收由publish方法发布的信息。
@凌驾
受保护的ArrayList doInBackground(){
//将作为第一个模板参数给定的类型的项返回给SwingWorker类。
if(javax.swing.SwingUtilities.isEventDispatchThread()){
System.out.println(“javax.swing.SwingUtilities.isEventDispatchThread()返回true”);
}
整数tmpValue=新整数(1);
ArrayList=新建ArrayList();
对于(int i=0;i<100;i++){
对于(int j=0;j<100;j++){//查找每100个素数,只是为了使它变慢
tmpValue=FindNextPrime(tmpValue.intValue());
//如果在此类上调用cancel()方法,isCancelled()将返回true。这是正确的方法
//要停止此线程,请参阅actionPerformed方法。
如果(isCancelled()){
System.out.println(“SwingWorker-isCancelled”);
退货清单;
}
}
//对发布的连续调用合并到一个java.util.List中,这是进程接收到的内容,
//在本例中,它用于更新JProgressBar
//1比100。
发布(新整数(i));
列表。添加(tmpValue);
}
退货清单;
}//注意,请始终在此处使用java.util.List,否则它将使用错误的列表。
@凌驾
受保护的无效进程(java.util.List progressList){
//此方法正在处理java.util.List项,这些项作为publish方法的连续参数提供。
//请注意,这些调用合并到一个java.util.List中
//SwingWorker的第二个模板参数类型。请注意,下面的get方法与
//SwingWorker get方法;它是列表的get方法。这将是更新进度条的好地方。
如果(!javax.swing.SwingUtilities.isEventDispatchThread()){
System.out.println(“javax.swing.SwingUtilities.isEventDispatchThread()+返回false”);
}
整数percentComplete=progressList.get(progressList.size()-1);
progressBar.setValue(percentComplete.intValue());
}
@凌驾
受保护的void done(){
System.out.println(“doInBackground已完成”);
如果(!javax.swing.SwingUtilities.isEventDispatchThread()){
System.out.println(“javax.swing.SwingUtilities.isEventDispatchThread()+返回false”);
}
试一试{
//这里,SwingWorker的get方法返回与第一个类型参数指定的类型相同的项
//给SwingWorker类。
ArrayList results=get();
for(整数i:结果){
addElement(i.toString());
}
}捕获(例外e){
System.out.println(“捕获到异常:+e”);
}
开始按钮();
}
布尔值IsPrime(int num){//检查一个数是否为素数
int i;

对于(i=2;i在执行长时间运行的任务期间,您希望定期检查
ProgressMonitor
是否已被取消。您的工作是在取消任务有意义的地方进行检查,否则谁知道您可能会挂起哪些资源