java - JProgressBar 无法正常工作

标签 java swing thread-sleep jprogressbar invokelater

所以我设置的 JProgressBar 无法按我想要的方式工作。所以每当我运行该程序时,它就会立即从 0 变为 100。我尝试使用 ProgressMonitor、一个任务,并尝试使用 SwingWorker 但我尝试的任何方法都不起作用。

这是我的程序:

int max = 10;
for (int i = 0; i <= max; i++) {
        final int progress = (int)Math.round(
            100.0 * ((double)i / (double)max)
        );

        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException ex) {
                    Logger.getLogger(BandListGenerator.class.getName()).log(Level.SEVERE, null, ex);
                }
                jProgressBar2.setValue(progress);
            }
        });
    }

@MadProgrammer 这是我尝试制作一个 Swing Worker 并将每个名称写入文档并更新进度栏。程序进行到大约 86% 时就停止了,永远不会创建完成的文档。该程序创建一个空白文档。下面是两个方法首先是我制作的SwingWorker对象:

public class GreenWorker extends SwingWorker<Object, Object> {
    @Override
    protected Object doInBackground() throws Exception {
        int max = greenList.size();
        XWPFParagraph tmpParagraph;
        XWPFRun tmpRun;
        FileInputStream file = 
                new FileInputStream(location + "GreenBandList.docx");
        gDocument = new XWPFDocument(OPCPackage.open(file));
        for (int i = 0; i < max; i++) {
            tmpParagraph = gDocument.getParagraphs().get(0);
            tmpRun = tmpParagraph.createRun();
            if (greenList.get(i).length() == 1) {
                    tmpRun.setBold(true);
                    tmpRun.setText(greenList.get(i));
                    tmpRun.setBold(false);
            } else {
                    tmpRun.setText(greenList.get(i));//Write the names to the Word Doc
            }
            int progress = Math.round(((float) i / max) * 100f);
            setProgress(progress);
        }
        return null;
  }        
}

这是启动它并具有我的属性更改事件的按钮的代码。

private void GenerateGreenList() throws IOException, InterruptedException {
    //Need to fix the bug that removes the Letter Header in Yellow Band list
    //********************************************************************\\

    //Delete the old list and make a new one
    File templateFile = new File(location + "\\backup\\GreenTemplate.docx");
    FileUtils.deleteQuietly(new File(location + "GreenBandList.docx"));
    FileUtils.copyFile(templateFile, new File(location + 
            "GreenBandList.docx"));
    //Get the New Entries
    String[] entries = jTextPane3.getText().split("\n");
    for (String s : entries) {
        if (s != null) {
            greenList.add(s);
        }
    }
    //Resort the list
    Collections.sort(greenList);
    //Write the names to the document
    GreenWorker worker = new GreenWorker();
    worker.addPropertyChangeListener(new PropertyChangeListener() {
        @Override
        public void propertyChange(PropertyChangeEvent evt) {
            if ("progress".equals(evt.getPropertyName())) {
                jProgressBar2.setValue((Integer) evt.getNewValue());
            }
        }
    });
    worker.execute();
    if (worker.isDone()) {
        try {
            gDocument.write(new FileOutputStream(new File(location + "GreenBandList.docx")));
            ////////////////////////////////////////////////////////////
        } catch (IOException ex) {
            Logger.getLogger(BandListGenerator.class.getName()).log(Level.SEVERE, null, ex);
        }
        JOptionPane.showMessageDialog(null, "Green Band List Created!");
        jProgressBar2.setValue(0);
    }
}

我使用了您其他帖子中的属性更改监听器,但我不太明白您写的那个的作用或一般情况是什么?

最佳答案

Swing 是一个单线程环境,也就是说,有一个线程负责处理系统内发生的所有事件,包括重绘事件。如果任何事情因任何原因阻塞该线程,它将阻止 Swing 处理任何新事件,包括重绘事件...

所以这一切......

EventQueue.invokeLater(new Runnable() {
    @Override
    public void run() {
        try {
            Thread.sleep(1000);
        } catch (InterruptedException ex) {
            Logger.getLogger(BandListGenerator.class.getName()).log(Level.SEVERE, null, ex);        }
        jProgressBar2.setValue(progress);
    }
});

不断暂停事件调度线程,阻止它实际执行任何更新(或至少随机间隔它们)...

您的外循环也可能是在 EDT 上下文中运行的,这意味着在它存在之前,事件队列中的任何内容都不会被处理。您所有的重绘请求都将合并为一个绘画请求,瞧,进度条即时填充...

你真的应该使用 SwingWorker - 我知道你说过你尝试过一个,但你没有显示任何关于你在这方面的尝试的代码,所以很难知道为什么它没有'然而,不起作用...

如果我们之前没有说过几次,请原谅我:P

关于java - JProgressBar 无法正常工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22031086/

相关文章:

java - cvFlip() 闪烁或返回 null

java - java中的反射或内省(introspection)有多昂贵

java - SpringLayout 适用于 Windows 7 但不适用于 NetBSD?

Java : How to get button position after self click-action

java - 在 android 中使用 webservice 响应对象

java - 从文本文件获取输入时不比较大小

java - 如何在 Java 中将私有(private) Swing 组件变成公共(public) Swing 组件?

c++ - 停止长 sleep 线程

c - 让所有的 child 从另一个 child 线程 sleep

java - 多线程中的死锁示例