我正在尝试向 Swing 中的某些方法处理添加进度条。我想在方法开始时同时开始进度并在方法结束时结束。我在网上找到了使用 SwingWorker
并分配任务的示例。但是,就我而言,我想在单击按钮时执行相同的操作。它附加到 btnTest.addActionListener(this);
并在 actionPeformed
下面实现。我尝试了多种方法来同时运行两个线程,但没有一个按预期工作,即并行。要么进度条挂起,直到释放按钮,然后进度条开始。谁能建议一种方法来解决这个问题?
public void actionPerformed(ActionEvent e) {
if (e.getSource() == btnTest) {
>>>
1. Add progress BAR thread 1
2. call the method for with progress bar should start thread 2
3. start both thread simultaneously
4. End progress BAR
>>>
}
}
最佳答案
看看 SwingWorker
我将向您展示使用它的基础知识,然后让您使用进度条来实现它。
SwingWorker<Void, Integer> randomWorker = new SwingWorker<Void, Integer>()
{
@Override
protected Void doInBackground() throws Exceptio
{
for (int i = 0; i <= 5; i++)
{
//Generate a bunch of numbers
int x = 50 * i;
//Pause in between
Thread.sleep(100);
//Store them in the 'chunks' list
publish(x);
}
return null;
}
@Override
protected void process(List<Integer> chunks)
{
for(int num : chunks)
{
//Get the numbers in the 'chunks' list
//To use wherever/however you want
label.setText(String.valueOf(num));
}
}
@Override
protected void done()
{
//Something to do when everything is done
label.setText("Finished");
}
};
然后在actionPerformed()
中调用Swing Worker的execute方法
@Override
public void actionPerformed(ActionEvent e)
{
randomWorker.execute();
}
关于java - 在操作内同时运行线程为进度条执行,仅显示方法的流程执行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35907784/