简体   繁体   English

如何显示进度条? Java多线程

[英]How to display progress bar? multithreading java

I'm a beginner in java so sorry if I'm asking a stupid question , but how do I make a new thread in my gui class that would create a progress bar. 我是Java的初学者,所以很抱歉如果我问一个愚蠢的问题,但是如何在gui类中创建一个新线程来创建进度条。 I have a class named progress and made a new thread in my gui class using the constructor that I have created. 我有一个名为progress的类,并使用创建的构造函数在gui类中创建了一个新线程。 But for some reason, I am getting a strange error: 但是由于某种原因,我遇到了一个奇怪的错误:

"constructor progress in class NewJFrame.progress cannot be applied to given types;
  required: no arguments
  found: JProgressBar
  reason: actual and formal argument lists differ in length   

NewJframe.java NewJframe.java

 private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {                                         
        // TODO add your handling code here:
           if (jRadioButton1.isSelected()){   

          App m = new App();


      Thread t1 = new Thread(new progress(jProgressBar1));
      m.sendPingRequest2("104.160.142.3",jTextPane1,jTextPane2,jTextField1);


} 
    }    

progress.java progress.java

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 *
 * @author User
 */


import javax.swing.JProgressBar;
public class progress implements Runnable {


      private static int DELAY = 500;


  JProgressBar progressBar;



  public  progress (JProgressBar bar) {
    progressBar = bar;
  }


  public void run() {
    int minimum = progressBar.getMinimum();
    int maximum = progressBar.getMaximum();
    for (int i = minimum; i < maximum; i++) {
      try {
        int value = progressBar.getValue();
        progressBar.setValue(value + 1);

        Thread.sleep(DELAY);
      } catch (InterruptedException ignoredException) {
      }
    }
  }
}

This: 这个:

Thread t1= new progress ( jProgressBar1);

Should be: 应该:

Thread t1 = new Thread(new progress(jProgressBar1));

since your progress class implements Runnable and does not extend Thread. 因为您的进度类实现了Runnable并且不扩展Thread。

Also your error message is strange: 另外,您的错误消息很奇怪:

constructor progress in class NewJFrame.progress cannot be applied to given types 类NewJFrame.progress中的构造函数进度不能应用于给定类型

suggesting that the problem resides within the constructor of the NewJFrame.progress class, a class that looks to be nested within the NewJFrame class. 建议问题出在NewJFrame.progress类的构造函数中,该类看起来嵌套在NewJFrame类中。 If this is so, get rid of the nested class and only deal with the free-standing progress (re-name it "Progress" please) class. 如果是这样,请摆脱嵌套类,而仅处理独立进度(请重命名为“ Progress”)类。


But having said that, your code has potential problems as you're changing the state of the JProgressBar, a Swing component, directly from within a background thread, and this is not Swing thread-safe. 话虽如此,当您直接从后台线程内部更改JProgressBar(Swing组件)的状态时,您的代码可能会出现问题,这不是Swing线程安全的。 Much better to use a SwingWorker and link it to the JProgressBar's state as per the JProgressBar standard tutorial (check the link please). 根据JProgressBar标准教程,最好使用SwingWorker并将其链接到JProgressBar的状态(请检查链接)。

For example: 例如:

import java.awt.event.KeyEvent;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;

import javax.swing.*;

@SuppressWarnings("serial")
public class ProgressFun extends JPanel {
    private JProgressBar progressBar = new JProgressBar(0, 100);

    public ProgressFun() {
        progressBar.setStringPainted(true);
        final JButton startProgress = new JButton("Start Progress");
        startProgress.setMnemonic(KeyEvent.VK_S);
        startProgress.addActionListener(l -> {
            startProgress.setEnabled(false);
            progressBar.setValue(0);
            final MyWorker myWorker = new MyWorker();
            myWorker.execute();

            myWorker.addPropertyChangeListener(pcEvent -> {
                if (pcEvent.getPropertyName().equals("progress")) {
                    int value = (int) pcEvent.getNewValue();
                    progressBar.setValue(value);
                } else if (pcEvent.getNewValue() == SwingWorker.StateValue.DONE) {
                    startProgress.setEnabled(true);
                    try {
                        myWorker.get();
                    } catch (InterruptedException | ExecutionException e) {
                        e.printStackTrace();
                    }
                }
            });
        });

        add(progressBar);
        add(startProgress);
    }

    private static void createAndShowGui() {
        ProgressFun mainPanel = new ProgressFun();

        JFrame frame = new JFrame("Progress Fun");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.getContentPane().add(mainPanel);
        frame.pack();
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> createAndShowGui());
    }
}

class MyWorker extends SwingWorker<Void, Integer> {

    @Override
    protected Void doInBackground() throws Exception {
        int progress = 0;
        setProgress(progress);
        while (progress < 100) {
            progress += (int)(5 * Math.random());
            progress = Math.min(progress, 100);
            TimeUnit.MILLISECONDS.sleep((int) (500 * Math.random()));
            setProgress(progress);
        }
        return null;
    }
}

As an aside, you will want to learn and use Java naming conventions . 顺便说一句,您将要学习和使用Java命名约定 Variable names should all begin with a lower letter while class names with an upper case letter. 变量名都应以小写字母开头,而类名应以大写字母开头。 Learning this and following this will allow us to better understand your code, and would allow you to better understand the code of others. 学习并遵循此规则将使我们能够更好地理解您的代码,并使您能够更好地理解其他人的代码。

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

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