gpt4 book ai didi

java - 同步j进度条

转载 作者:行者123 更新时间:2023-12-02 04:44:07 25 4
gpt4 key购买 nike

   public class frame11 extends javax.swing.JFrame implements ActionListener,
PropertyChangeListener {


public String[] columnNames = { "Path",
"File Name",
"Size"};
public Object[][] data ;
int isJPEG (String s) throws IOException
{ int c=0;//not jpeg

if ( (s.endsWith(".JPG")) || (s.endsWith(".JPEG"))||(s.endsWith(".jpeg"))||(s.endsWith(".jpg")))
{

c=1;//is jpeg

}
return c;
}

}


private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed

setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
JFileChooser fch = new JFileChooser("C:\\");
jProgressBar1.setValue(0);
jProgressBar1.setStringPainted(true);
jTextField1.setText(null);
jTextField2.setText(null);
jTextField4.setText(null);
jLabel7.setText(null);
data = new Object[15][3];
jTable2.setModel(new DefaultTableModel(data, columnNames));
fch.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
int ret = fch.showOpenDialog(null);
int apr=0;
if (ret==JFileChooser.APPROVE_OPTION)
{ apr=1;
jTextField1.setText(fch.getSelectedFile().toString());
setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
}
else jTextField1.setText("Nothing clicked!!!");
if (apr==1) {
jLabel7.setText("Wait Please, While searching ...");
task = new Task();
task.addPropertyChangeListener(this);
task.execute();
EventQueue.invokeLater(new Runnable() { // Added

@Override
public void run() {
File f = fch.getSelectedFile();
String s= f.getAbsolutePath();
int cnt;
int st=0;
Path myfile = Paths.get(s);
if(f.isDirectory()&& Files.isReadable(myfile)){
try {
st=st+CheckFiles(f);
cnt=count(f);
String ss=Integer.toString(cnt);
jTextField2.setText(ss);
jTextField4.setText(Integer.toString(st));
} catch (IOException ex) {
Logger.getLogger(frame1.class.getName()).log(Level.SEVERE, null, ex);
}
}
jLabel7.setText("Scanning Finished. Thanks for waiting ");
}

});

}

}//GEN-LAST:event_jButton1ActionPerformed
private Task task;
@Override
public void propertyChange(PropertyChangeEvent evt) {
if ("progress".equals(evt.getPropertyName())) {
int progress = (Integer) evt.getNewValue();
jProgressBar1.setValue(progress);
System.out.println("Property changed");
}
}

//@Override
public void actionPerformed(ActionEvent e) {

}

class Task extends SwingWorker<Void, Void> {
@Override
public Void doInBackground() {
Random random = new Random();
int progress = 0;
setProgress(0);
while (progress < 100) {
try {
Thread.sleep(random.nextInt(100));
} catch (InterruptedException ignore) {}
progress += random.nextInt(10);
setProgress(Math.min(progress, 100));
}
return null;
}

/*
* Executed in event dispatching thread
*/
@Override
public void done() {
Toolkit.getDefaultToolkit().beep();
setCursor(null);
}
}

我需要您的帮助,我正在尝试扫描我的电脑以查找 JPEG 图像以对其进行计数。我有两个问题,第一是我使用的是jtable,但直到程序结束才添加结果,并且进度条不同步,有时它在程序之前结束,有时在程序结束之后。请帮我解决这两个问题,谢谢。

最佳答案

您使用 SwingWorker 来创建后台线程——很好——但是您直接从该后台线程进行 Swing 调用——不好:

jProgressBar1.setValue(n);

而是从 SwingWorker 中调用 setProgress(...),并向工作线程添加一个 PropertyChangeListener,用于监听工作线程的“进度”绑定(bind)属性的更改。

例如:

<小时/>

例如 mcve显示了将 JProgressBar 与 SwingWorker 一起使用的示例:

import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.util.Random;
import java.util.concurrent.ExecutionException;
import javax.swing.*;

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

public TestProgress2() {
progressBar.setStringPainted(true);
add(progressBar);
add(new JButton(startBackgroundTaskAction));
}

public void setActionEnabled(boolean enabled) {
startBackgroundTaskAction.setEnabled(enabled);
}

private class StartBackgroundTaskAction extends AbstractAction {
public StartBackgroundTaskAction() {
super("Start Background Task");
putValue(MNEMONIC_KEY, KeyEvent.VK_S);
}

@Override
public void actionPerformed(ActionEvent e) {
progressBar.setString(null);
progressBar.setValue(0);
setActionEnabled(false);
MyTask myTask = new MyTask();
myTask.addPropertyChangeListener(new MyTaskListener());
myTask.execute();
}
}

private class MyTaskListener implements PropertyChangeListener {
@Override
public void propertyChange(PropertyChangeEvent pcEvt) {
MyTask myTask = (MyTask) pcEvt.getSource();
if ("progress".equals(pcEvt.getPropertyName())) {
int progress = myTask.getProgress();
progressBar.setValue(progress);
}
if (pcEvt.getNewValue() == SwingWorker.StateValue.DONE) {
setActionEnabled(true);
progressBar.setString("Done");
try {
myTask.get();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
}
}
}

private class MyTask extends SwingWorker<Void, Void> {
@Override
protected Void doInBackground() throws Exception {
Random random = new Random();
int progress = 0;
setProgress(0);
while (progress < 100) {
try {
Thread.sleep(random.nextInt(1000));
} catch (InterruptedException ignore) {}
progress += random.nextInt(10);
setProgress(Math.min(progress, 100));
}
return null;
}
}

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

JFrame frame = new JFrame("TestProgress2");
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.getContentPane().add(mainPanel);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}

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

关于java - 同步j进度条,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29831505/

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