我正在开发一个风险管理系统,部分功能是向每个分配了纠正措施的成员发送电子邮件。因此,作为在发送电子邮件时让用户保持更新的一种措施,我决定使用进度监视器和 swing worker,因为 GUI 在电子邮件发送过程中冻结。我不确定如何实现这一点,但我知道的是我需要创建一个处理电子邮件发送的任务、一个用于监控电子邮件发送过程的属性更改列表和一个用于启动电子邮件发送的操作列表。以下是我编写的类和方法,但我不知道如何将它们组合在一起以实现我的既定目标。
private void jButton4ActionPerformed(java.awt.event.ActionEvent evt) {
setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
progressMonitor = new ProgressMonitor(NewJFrame.this, "Sending an email", " ", 0, 100);
progressMonitor.setProgress(0);
task = new Task();
task.addPropertyChangeListener(this);
task.execute();
}
@Override
public void propertyChange(PropertyChangeEvent evt) {
if("progress".equals(evt.getPropertyName())){
int progress = (Integer) evt.getNewValue();
progressMonitor.setProgress(progress);
String message = String.format("Sending message ..%d%%...\n", progress );
jTextArea1.append(message);
//progressMonitor.setNote(task.getMessage());
if(progressMonitor.isCanceled() || task.isDone()){
progressMonitor.close();
Toolkit.getDefaultToolkit().beep();
if(progressMonitor.isCanceled()){
task.cancel(true);
}else{
jTextArea1.append("Message Send");
}
}
}
}
class Task extends SwingWorker<Void, Void>{
@Override
protected Void doInBackground() throws Exception {
int progress = 0;
setProgress(0);
try{
Thread.sleep(1000);
progress += 5;
progress++;
setProgress(progress);
Properties props = new Properties();
props.put("mail.smtp.host", "mail.test.biz");
props.put("mail.smtp.port", "587");
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.auth", "true");
Session session = Session.getDefaultInstance(props,
new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication(){
return new PasswordAuthentication("herbert@conceptium.biz", "Kaylad1*#");
}
});
try {
Message msg = new MimeMessage(session);
msg.setFrom(new InternetAddress("herbert@conceptium.biz"));
msg.addRecipients(Message.RecipientType.CC, InternetAddress.parse("herbertd@test.com,herbert@test.biz"));
msg.setSubject("This is a test");
msg.setText("This is a test a message");
Transport.send(msg);
JOptionPane.showMessageDialog(NewJFrame.this, "Email succesfull sent...!" );
}
catch(MessagingException | HeadlessException e){
//progressMonitor.isCanceled();
JOptionPane.showMessageDialog(NewJFrame.this, e.getMessage() +". "+ "Please check your internet connection");
}
}catch(InterruptedException | HeadlessException e){
JOptionPane.showMessageDialog(NewJFrame.this, e.getMessage());
}
return null;
}
@Override
public void done(){
setCursor(null);
//jTextArea1.append("Done!\n");
progressMonitor.setProgress(100);
}
}
我已经对电子邮件地址进行了硬编码,但它假设是从基地开始的。为简单起见,我删除了该方法,只添加了足够的代码来表达我的观点。一些帮助将不胜感激。