gpt4 book ai didi

java - 返回值和 JProgressbar

转载 作者:行者123 更新时间:2023-11-29 05:15:58 25 4
gpt4 key购买 nike

我在为 JProgressBar 设置一个值时遇到问题,该值是从类型返回方法内部获得的。我知道我必须执行多线程,但我对这个主题真的很陌生,真的不知道如何实现它。

我尝试用代码简要解释一下我的困境:

这是我的数据返回方法,用于计算字符串中的行数(例如,来自 JTextArea 或其他)。

    public static int countLines(String s) {
int count = 0;

String[] words = s.split("\n");

for(String i: words) {
count++;
}
return count;
}

我想要添加的是此方法中的一个方法,它将我在 JFrame 中创建的 JProgressBar 设置为值 count。例如。 setProgress(计数);

这可能吗?因为我尝试了几种方法来做到这一点,无论如何,进度条只会在返回值发出后更新。

我必须在自己的线程中运行此方法还是仅在进度设置方法中运行?还是两者兼而有之?

干杯!

最佳答案

Do I have to run this method in an own Thread or just the progress setting method? or both?

这两个任务应该在不同的线程中运行:业务逻辑(在本例中是单词计数)必须在后台线程中执行,而进度条更新必须在 Swing 线程中运行,也称为 Event Dispatch Thread (EDT) .

IMO 实现此目的的最佳方法是使用 SwingWorker :

  • 将所有计数逻辑移至 doInBackground() 实现。
  • PropertyChangeListener 附加到 swing worker 以监听 progress 属性并更新此监听器中的进度条。
  • 使用setProgress()doInBackground 中设置工作人员的进度并触发属性更改事件通知您的监听器。

SO里面有很多例子,看看就知道了标签。另外,考虑这个片段:

SwingWorker<Void, Void> worker = new SwingWorker<Void, Void>() {

// Following code is performed in a background thread

@Override
protected Void doInBackground() throws Exception {

String[] words = string.split(System.lineSeparator());
int totalWords = words.length;

for (int count = 0; count < totalWords; count++) {
int progress = (count + 1) * 100 / totalWords;
setProgress(progress);
}
return null;
}
};

worker.addPropertyChangeListener(new PropertyChangeListener() {

// Following code is performed in the EDT, as all event handling code is.
// Progress bar update must be done here, NOT within doInBackground()

@Override
public void propertyChange(PropertyChangeEvent evt) {
if ("progress".equals(evt.getPropertyName())) {
Integer progress = (Integer)evt.getNewValue();
progressBar.setValue(progress);
}
}
});

关于java - 返回值和 JProgressbar,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26527717/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com