Reputation: 177
I'm studying java from "The Complete Reference" by Herbert Schidlt. In the book, it is advised that if any part of you GUI needs to do something which might take longer on an event generation, then we should implement that thing as a new Thread.
So, I made a GUI to send mails to my inbox, which works fine but it takes 2-3 seconds to send the mail, and hence the Send button also takes time to return to its normal state(it remains pressed until listener responds back, as In Listener, I have implemented the code to send mail).
In order to avoid this, I am trying to run a thread on this "Send" Button, such that when Button is pressed, a mouseEvent will be generated, & on that mouseEvent, I want to run the thread so that Listener responds back immediately and mail is send through a thread instead.
How do I implement this scheme ? I tried implementing new Runnable as an inner class in the MouseEvent, but I cant figure out on how do i call the start method !
the code is large, so I will put only the "Send Button" code of it here.
sendButton.addMouseListener(new MouseAdapter(){
public void mouseClicked(MouseEvent me){
String id=emailIdField.getText();
String subject=subjectField.getText();
String body=mailBodyArea.getText();
String user= "[email protected]";
String pass="password";
String host="smtp.gmail.com";
sendEmail= new SendEmail(); // class which actually sends the mail. defined in other file.
sendEmail.sendMail( id, user, subject ,body ,host, user, pass );
}
});
I want to run the code inside this MouseClicked function as a new Thread. What I have tried so far is,
sendButton.addMouseListener(new MouseAdapter(){
public void mouseClicked(MouseEvent me){
new Runnable(){
public void run(){
String id=emailIdField.getText();
String subject=subjectField.getText();
String body=mailBodyArea.getText();
System.out.println(id);
System.out.println(subject);
System.out.println(body);
String user= "[email protected]";
String pass="impe(*&amit";
String host="smtp.gmail.com";
sendEmail= new SendEmail();
sendEmail.sendMail( id, user, subject ,body ,host, user, pass );
}
};
});
But now I dont know as how do I call the start method to this thread ? Please advise.
Upvotes: 2
Views: 4119
Reputation: 1738
Inside mouseCliked function add:
new Thread() {
public void run() {
String id=emailIdField.getText();
String subject=subjectField.getText();
String body=mailBodyArea.getText();
System.out.println(id);
System.out.println(subject);
System.out.println(body);
String user= "[email protected]";
String pass="impe(*&amit";
String host="smtp.gmail.com";
sendEmail= new SendEmail();
sendEmail.sendMail( id, user, subject ,body ,host, user, pass );
}
}.start();
Upvotes: 1