在来这里之前,我已经在网上搜索并阅读了几十个谈论这个的话题,但我无法解决我的问题。
我想显示上传的进度。在下面的代码中,一切正常,除了我的 JFrame 没有更新。我正在使用我在另一个主题上找到的技术,但它似乎不起作用。我认为如果您查看我的代码会更简单(我删除了与问题无关的说明)。
/*
* Correct imports have been done
*/
class GUI extends JFrame {
public JPanel pan;
public GUI(JPanel panel) {
super("Uploading...");
setLayout(new BoxLayout(this, BoxLayout.Y_AXIS));
setPreferredSize(new Dimension(600, 500));
setMinimumSize(new Dimension(600, 500));
setMaximumSize(new Dimension(600, 500));
setDefaultCloseOperation(this.DO_NOTHING_ON_CLOSE);
setLocationRelativeTo(null);
pan = panel;
pan.setLayout(new BoxLayout(pan, BoxLayout.Y_AXIS));
setContentPane(pan);
setVisible(true);
}
}
public class GUIUpload {
private static GUI ui;
public static void main(String args[]) {
JPanel main = new JPanel();
ui = new GUI(main); // create and display GUI
uploadLoop(args, main); // start the upload loop
/*
* After upload is finished
*/
JButton jb = new JButton("Ok");
jb.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
ui.setVisible(false);
}
});
ui.getContentPane().add(jb);
ui.getContentPane().repaint();
}
private static void uploadLoop(String[] paths, JPanel monitor) {
/*
* Upload starts here
*/
long transfered;
long size;
InputStream inputStream;
FTPClient ftpClient = new FTPClient();
try {
ftpClient.connect("xxxxxx", 21);
boolean success = ftpClient.login("xxxxxx", "xxxxxx");
/*
* Sending
*/
for (int i = 0; i < 4; i++){
if (paths[i] != null){
File localFile = new File(paths[i]);
String remoteFile = "/public_html/papers/" + i + ".pdf";
JLabel label = new JLabel("Uploading...");
ui.getContentPane().add(label);
ui.repaint();
inputStream = new FileInputStream(localFile);
// Monitoring misc
size = localFile.length();
transfered = 0;
int percentage = 0;
// Progress bar
JProgressBar pgb = new JProgressBar();
pgb.setValue(0);
ui.getContentPane().add(pgb);
ui.repaint();
// Upload routine
OutputStream outputStream = ftpClient.storeFileStream(remoteFile);;
byte[] bytesIn = new byte[4096];
int read = 0;
while ((read = inputStream.read(bytesIn)) != -1) {
outputStream.write(bytesIn, 0, read);
transfered += read;
percentage = (int)(transfered * 100.0 / size + 0.5);
System.out.println(percentage);
pgb.setValue(percentage);
ui.repaint();
}
inputStream.close();
outputStream.close();
boolean completed = ftpClient.completePendingCommand();
/*
* End of upload
*/
}
}
} // end try
catch (Exception e){
// Do nothing}
} // end catch
} // end upload method
}
百分比工作正常。文件传输工作正常。GUI 框架仅在我在 GUIUpload 类的主要方法中重新绘制后更新。重新绘制时,我可以看到所有标签和进度条都已正确添加和更新(进度条显示最大值。
所以..我一直在寻找如何做到这一点已经有一段时间了,我尝试过使用线程,我尝试了很多东西,但都没有奏效(或者我在尝试它们时做错了)。
非常感谢任何能够帮助我的人。
最好的祝福。