我正在开发一个风险管理系统,部分功能是向每个被分配纠正措施的成员发送电子邮件。因此,作为在发送电子邮件时保持用户更新的措施,我决定使用进度监视器和摇摆工作人员,因为GUI在电子邮件发送过程中冻结。我不确定如何实现这一点,但我知道的是,我将需要创建一个处理电子邮件发送的任务,一个属性changelister来监控电子邮件发送过程和一个actiondlister来启动电子邮件发送。以下是我编写的类和方法,但我不知道如何将它们组合在一起以实现我的设定目标。
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);
}
}
我已经硬编码了电子邮件地址,但它假设从基地圆顶。为简单起见,我已经删除了该方法,并且只提供足够的代码来解决我的观点。一些帮助将不胜感激。