Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/multithreading/4.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 用于更新jlabel的多个线程_Java_Multithreading_Swing_Jlabel - Fatal编程技术网

Java 用于更新jlabel的多个线程

Java 用于更新jlabel的多个线程,java,multithreading,swing,jlabel,Java,Multithreading,Swing,Jlabel,下面的代码是一个简单的JFrame,带有一个按钮和两个JLabel,该代码的目标是通过调用新线程来更新“”编号JLabel,而不是在EDT中尝试这样做 我的问题是,每次按下按钮时,run方法都会调用一个新线程,但是,它不会取消旧线程。因此,如果您按下按钮,几秒钟后再次按下按钮,您将有两个线程更新JLabel,这看起来很糟糕 问题陈述:每次按下按钮时,计数器必须从0开始,并且必须取消更新计数器的旧线程 import java.awt.Font; import java.awt.GridBagCon

下面的代码是一个简单的
JFrame
,带有一个按钮和两个
JLabel
,该代码的目标是通过调用新线程来更新“”编号
JLabel
,而不是在EDT中尝试这样做

我的问题是,每次按下按钮时,run方法都会调用一个新线程,但是,它不会取消旧线程。因此,如果您按下按钮,几秒钟后再次按下按钮,您将有两个线程更新
JLabel
,这看起来很糟糕

问题陈述:每次按下按钮时,计数器必须从0开始,并且必须取消更新计数器的旧线程

import java.awt.Font;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.List;
import java.util.concurrent.ExecutionException;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.SwingUtilities;
import javax.swing.SwingWorker;

public class MainFrame extends JFrame {

private JLabel countLabel1 = new JLabel("0");
private JLabel statusLabel = new JLabel("Task not completed.");
private JButton startButton = new JButton("Start");

public MainFrame(String title) {
    super(title);

    setLayout(new GridBagLayout());

    countLabel1.setFont(new Font("serif", Font.BOLD, 28));

    GridBagConstraints gc = new GridBagConstraints();

    gc.fill = GridBagConstraints.NONE;

    gc.gridx = 0;
    gc.gridy = 0;
    gc.weightx = 1;
    gc.weighty = 1;
    add(countLabel1, gc);

    gc.gridx = 0;
    gc.gridy = 1;
    gc.weightx = 1;
    gc.weighty = 1;
    add(statusLabel, gc);

    gc.gridx = 0;
    gc.gridy = 2;
    gc.weightx = 1;
    gc.weighty = 1;
    add(startButton, gc);

    startButton.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent arg0) {
            start();
        }
    });

    setSize(200, 400);
    setDefaultCloseOperation(EXIT_ON_CLOSE);
    setVisible(true);
}


private void start() 
{
    Thread worker = new Thread() 
    {
        public void run() 
        {

            // Simulate doing something useful.
            for(int i=0; i<=10; i++) {

                final int count = i;

                SwingUtilities.invokeLater(new Runnable() 
                {
                    public void run() 
                    {
                        countLabel1.setText(Integer.toString(count));
                    }
                });

                try 
                {
                    Thread.sleep(1000);
                } catch (InterruptedException e) 
                {

                }
            }

            SwingUtilities.invokeLater(new Runnable() {
                public void run() 
                {
                    statusLabel.setText("Completed.");
                }
            });

        }
    };

    worker.start();
}

public static void main(String[] args) {
    SwingUtilities.invokeLater(new Runnable() {

        @Override
        public void run() {
            new MainFrame("SwingWorker Demo");
        }
    });
 }
   }
导入java.awt.Font;
导入java.awt.GridBagConstraints;
导入java.awt.GridBagLayout;
导入java.awt.event.ActionEvent;
导入java.awt.event.ActionListener;
导入java.util.List;
导入java.util.concurrent.ExecutionException;
导入javax.swing.JButton;
导入javax.swing.JFrame;
导入javax.swing.JLabel;
导入javax.swing.SwingUtilities;
导入javax.swing.SwingWorker;
公共类大型机扩展JFrame{
私有JLabel countLabel1=新JLabel(“0”);
私有JLabel statusLabel=新JLabel(“任务未完成”);
私有JButton startButton=新JButton(“开始”);
公共主机(字符串标题){
超级(标题);
setLayout(新的GridBagLayout());
countLabel1.setFont(新字体(“衬线”,Font.BOLD,28));
GridBagConstraints gc=新的GridBagConstraints();
gc.fill=GridBagConstraints.NONE;
gc.gridx=0;
gc.gridy=0;
gc.weightx=1;
gc.weighty=1;
添加(countLabel1,gc);
gc.gridx=0;
gc.gridy=1;
gc.weightx=1;
gc.weighty=1;
添加(状态标签,gc);
gc.gridx=0;
gc.gridy=2;
gc.weightx=1;
gc.weighty=1;
添加(启动按钮,gc);
addActionListener(新ActionListener()){
已执行的公共无效操作(操作事件arg0){
start();
}
});
设置大小(200400);
setDefaultCloseOperation(关闭时退出);
setVisible(真);
}
私有void start()
{
线程工作线程=新线程()
{
公开募捐
{
//模拟做一些有用的事情。

对于(int i=0;i请检查此版本的代码。主要的新功能是实现
Runnable
Updater
类。请参见此处的用法。另请参见
private void start()
中的更改。另请参见
Updater
类中的
enabled
标志

import java.awt.Font;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.SwingUtilities;

public class MainFrame extends JFrame {

    public static final long serialVersionUID = 380931874973423432L;
    private Updater currentUpdater = null;
    private Thread currentWorker = null;
    private int cnt = 0;

    private JLabel countLabel1 = new JLabel("0");
    private JLabel statusLabel = new JLabel("Initialized.");
    private JButton startButton = new JButton("Start");

    public MainFrame(String title) {
        super(title);

        setLayout(new GridBagLayout());

        countLabel1.setFont(new Font("serif", Font.BOLD, 28));

        GridBagConstraints gc = new GridBagConstraints();

        gc.fill = GridBagConstraints.NONE;

        gc.gridx = 0;
        gc.gridy = 0;
        gc.weightx = 1;
        gc.weighty = 1;
        add(countLabel1, gc);

        gc.gridx = 0;
        gc.gridy = 1;
        gc.weightx = 1;
        gc.weighty = 1;
        add(statusLabel, gc);

        gc.gridx = 0;
        gc.gridy = 2;
        gc.weightx = 1;
        gc.weighty = 1;
        add(startButton, gc);

        startButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent arg0) {
                start();
            }
        });

        setSize(400, 400);
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        setVisible(true);
    }

    private void start() {

        cnt++;

        Thread cw = this.currentWorker;
        if (currentUpdater != null) {
            currentUpdater.setEnabled(false);
        }

        Updater newUpdater = new Updater(this, cnt);
        Thread newWorker = new Thread(newUpdater);

        try{
            if (cw!=null) 
                cw.join();
        }catch(InterruptedException ex){
            ex.printStackTrace();
        }

        this.currentUpdater = newUpdater;
        this.currentWorker = newWorker;

        newWorker.start();
    }

    public JLabel getCountLabel1() {
        return countLabel1;
    }

    public void setCountLabel1(JLabel countLabel1) {
        this.countLabel1 = countLabel1;
    }

    public JLabel getStatusLabel() {
        return statusLabel;
    }

    public void setStatusLabel(JLabel statusLabel) {
        this.statusLabel = statusLabel;
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {

            @Override
            public void run() {
                new MainFrame("SwingWorker Demo");
            }
        });
    }
}

class Updater implements Runnable {

    private int id = 0;
    private MainFrame frame = null;
    private volatile boolean enabled = false;

    public Updater(MainFrame f, int id) {
        this.frame = f;
        this.id = id;
    }

    public void run() {
        enabled = true;

        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                frame.getStatusLabel().setText("Task not completed. Task ID: " + id);
                System.out.println("Task not completed. Task ID: " + id);
            }
        });

        // Simulate doing something useful.
        for (int i = 0; i <= 10; i++) {

            if (!enabled)
                break;

            final int count = i;

            SwingUtilities.invokeLater(new Runnable() {
                public void run() {
                    frame.getCountLabel1().setText(Integer.toString(count));
                }
            });

            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                frame.getStatusLabel().setText("Task completed. Task ID: " + id);
                System.out.println("Task completed. Task ID: " + id);
            }
        });

    }

    public boolean isEnabled() {
        return enabled;
    }

    public void setEnabled(boolean enabled) {
        this.enabled = enabled;
    }

}
导入java.awt.Font;
导入java.awt.GridBagConstraints;
导入java.awt.GridBagLayout;
导入java.awt.event.ActionEvent;
导入java.awt.event.ActionListener;
导入javax.swing.JButton;
导入javax.swing.JFrame;
导入javax.swing.JLabel;
导入javax.swing.SwingUtilities;
公共类大型机扩展JFrame{
公共静态最终长serialVersionUID=380931874973423432L;
私有更新程序currentUpdater=null;
私有线程currentWorker=null;
私有int cnt=0;
私有JLabel countLabel1=新JLabel(“0”);
私有JLabel statusLabel=新JLabel(“已初始化”);
私有JButton startButton=新JButton(“开始”);
公共主机(字符串标题){
超级(标题);
setLayout(新的GridBagLayout());
countLabel1.setFont(新字体(“衬线”,Font.BOLD,28));
GridBagConstraints gc=新的GridBagConstraints();
gc.fill=GridBagConstraints.NONE;
gc.gridx=0;
gc.gridy=0;
gc.weightx=1;
gc.weighty=1;
添加(countLabel1,gc);
gc.gridx=0;
gc.gridy=1;
gc.weightx=1;
gc.weighty=1;
添加(状态标签,gc);
gc.gridx=0;
gc.gridy=2;
gc.weightx=1;
gc.weighty=1;
添加(启动按钮,gc);
addActionListener(新ActionListener()){
已执行的公共无效操作(操作事件arg0){
start();
}
});
设置大小(400400);
setDefaultCloseOperation(关闭时退出);
setVisible(真);
}
私有void start(){
cnt++;
线程cw=此.currentWorker;
if(currentUpdater!=null){
currentUpdater.setEnabled(false);
}
Updater newUpdater=新的更新程序(这个,cnt);
线程newWorker=新线程(newUpdater);
试一试{
如果(cw!=null)
cw.join();
}捕获(中断异常例外){
例如printStackTrace();
}
this.currentUpdater=newUpdater;
this.currentWorker=newWorker;
newWorker.start();
}
公共JLabel getCountLabel1(){
返回计数1;
}
公共无效setCountLabel1(JLabel countLabel1){
this.countLabel1=countLabel1;
}
公共JLabel getStatusLabel(){
返回状态标签;
}
公共无效设置状态标签(JLabel statusLabel){
this.statusLabel=状态标签;
}
公共静态void main(字符串[]args){
SwingUtilities.invokeLater(新的Runnable(){
@凌驾
公开募捐{
新的大型机(“SwingWorker演示”);
}
});
}
}
类更新程序实现可运行{
私有int id=0;
私有主机帧=null;
私有易失性布尔启用=false;
公共更新程序(大型机f,int-id){
这个框架=f;
this.id=id;
}
公开募捐{
启用=真;
SwingUtilities.invokeLater(新的Runnable(){
公开募捐{
frame.getStatusLabel().setText(“任务未完成。任务ID:+ID”);
System.out.println(“任务未完成。任务ID:+ID”);
}
});
//模拟做一些有用的事情。

对于(inti=0;i检查此版本的代码。主要的新功能是
更新程序
import java.awt.Font;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.SwingUtilities;

public class MainFrame extends JFrame {

    private JLabel countLabel1 = new JLabel("0");
    private JLabel statusLabel = new JLabel("Task not completed.");
    private JButton startButton = new JButton("Start");

    private MyThread myThread;

    public MainFrame(String title) {
        super(title);

        setLayout(new GridBagLayout());

        countLabel1.setFont(new Font("serif", Font.BOLD, 28));

        GridBagConstraints gc = new GridBagConstraints();

        gc.fill = GridBagConstraints.NONE;

        gc.gridx = 0;
        gc.gridy = 0;
        gc.weightx = 1;
        gc.weighty = 1;
        add(countLabel1, gc);

        gc.gridx = 0;
        gc.gridy = 1;
        gc.weightx = 1;
        gc.weighty = 1;
        add(statusLabel, gc);

        gc.gridx = 0;
        gc.gridy = 2;
        gc.weightx = 1;
        gc.weighty = 1;
        add(startButton, gc);

        startButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent arg0) {
                start();
            }
        });

        setSize(200, 400);
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        setVisible(true);
    }

    private void start() {
        if (myThread != null) {
            myThread.setRunning(false);
        }
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                statusLabel.setText("Task not completed.");
            }
        });
        myThread = new MyThread(countLabel1, statusLabel);
        Thread thread = new Thread(myThread);
        thread.start();
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {

            @Override
            public void run() {
                new MainFrame("SwingWorker Demo");
            }
        });
    }
}

class MyThread implements Runnable {

    public MyThread(JLabel countLabel1, JLabel statusLabel) {
        this.countLabel1 = countLabel1;
        this.statusLabel = statusLabel;
    }

    private boolean running = true;
    private JLabel countLabel1, statusLabel;

    public void run() {

        // Simulate doing something useful.
        for (int i = 0; i <= 10; i++) {

            if (running) {
                final int count = i;

                SwingUtilities.invokeLater(new Runnable() {
                    public void run() {
                        if (running) {
                            countLabel1.setText(Integer.toString(count));

                            if (count == 10) {
                                SwingUtilities.invokeLater(new Runnable() {
                                    public void run() {
                                        statusLabel.setText("Completed.");
                                    }
                                });
                            }
                        }
                    }
                });
            } else {
                break;
            }

            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {

            }
        }

    }

    public boolean isRunning() {
        return running;
    }

    public void setRunning(boolean running) {
        this.running = running;
    }

}