将JProgressBar与Java Mail一起使用(知道transport.send()之后的进度)

我有这个发送电子邮件的程序。我想知道我是否可以使用progress bar来改善用户界面。 我想要的是进度条应该在遇到语句transport.send()之后相应地进展。有一种方法我可以知道进度。 知道的是,当用户按下send启动一个发送send的新线程。点击发送后的响应很差,因为用户不知道他的动作是否被收听。 (虽然它正在被听!)在半分钟的间隙后,他得到了一个JOptionPane ,是的,消息已被发送。你会同意每个人都渴望知道他的行为是否正在被处理。

有什么办法我可以使用进度条。 即我怎么知道我的电子邮件程序的进度如果我不能使用JProgressBar ,我可以使用的另一种方法告诉用户他的命令正在处理,他不用担心。

顺便说一下,这是负责发送电子邮件的部分。

 try { message.setFrom( new InternetAddress(from)); message.setRecipients(MimeMessage.RecipientType.TO , InternetAddress.parse(to) ); message.setSubject(subject); message.setText(emailMessage); attachment.setDataHandler( new DataHandler( fds ) ); attachment.setFileName( fileName ); messagePart.setText( emailMessage ); Multipart gmailMP = new MimeMultipart(); gmailMP.addBodyPart(attachment); gmailMP.addBodyPart( messagePart ); message.setContent( gmailMP ); Transport transport = session.getTransport("smtp"); transport.send(message); // LINE THAT SENDS EMAIL transport.close(); JOptionPane.showMessageDialog(new JFrame() , "Message sent!"); } catch(Exception exc) { JOptionPane.showMessageDialog( new JFrame() , exc ); } 

在注释行之后,执行接下来的两个语句需要一些时间。在我希望用户知道他的动作正在被处理之间

我怎样才能做到这一点 ?

如果我理解您的问题,您希望了解有关电子邮件发送过程的最新信息。 在这种情况下,您可以以进度条的forms向用户显示此信息。

据我所知,你这里没有“明确”的解决方案。 尽管javax.mail.Transport具有方法addTransportListener(TransportListener l)但接口TransportListener不会报告已完成工作的百分比。 坦率地说,我不确定这是可能的。 您可以做的是在流程开始和结束时回电。 您可以为程序添加一个逻辑,该逻辑“倾斜”发送电子邮件通常需要多长时间,然后尝试使用计时器任务“模仿”进度。 例如,通常需要30秒才会每1秒为进度条添加3%。 然后停止,除非电子邮件发送完成。 如果发送完成,请立即跳转到100%。 你的程序可以倾斜并自我更新,如果网络变得更快,它将估计时间为20秒而不是30等。

我不认为存在更好的解决方案。 不要担心:世界上大多数流程条都基于某种估计,启发式等。

我很欣赏@ AlexR的方法。

这就是我实现它的方式。 就用户对了解按钮响应的满意度而言,它几乎是完美的。 (但有时连接速度太慢可能会导致问题)

 boolean status = false; // global variable // add the following statement just before the statement transport.send() startProgressThread(); // start a separate thread for progress bar transport.send(); // progress bar started just before this statement is encountered // the execution of the following statement will take some time,by the time JProgressBar is working status = false; // as this statement is encountered while loop starts and jprogress bar stops. public void startProgressThread() { // start the thread and from here call the function showProgress() } public showProgress() { status = true; int i = 0; while( status ) { i++; jProgressBar.setValue(i); try { Thread.sleep(90); } catch(Exception exc) { System.out.println(exc); } } if( status != true ) { jprogressBar.setValue( jProgressBar.getMaximum() ); } }