Share on Google+Share on Google+

Display message automatically using Java Swing

Advertisement
In this section, you will learn how to display message automatically after regular interval of time.

Display message automatically using Java Swing

Here we are going to display message automatically after regular interval of time. For this, we have allowed the user to specify  the no of seconds and the message. The method Thread.sleep(time)  pauses the execution for the specified number of milliseconds and prevent the message to be displayed. After every 5 seconds, it will display the specified message automatically.

Here is the code

import javax.swing.*;

public class DisplayMessageAutomatically{
public static void main(String args[]){
try {
UIManager.setLookAndFeel(
UIManager. getSystemLookAndFeelClassName () );
}
catch Exception e ) {}
int time = 0;
while(true) {
try{
time = Integer.parseIntJOptionPane.showInputDialog "Enter time in second" ));
break;
catch (NumberFormatException e){
JOptionPane.showMessageDialognull, "Invalid" );
}
}
time *=1000;
String str = JOptionPane.showInputDialog"Enter your message" );
if (str == nullreturn;
while(true){
try {
Thread.sleep(time);
JOptionPane.showMessageDialognull,str,"Alert", JOptionPane.ERROR_MESSAGE);
catch (Exception e) {}
}
}
}

Advertisements

Posted on: October 22, 2009 If you enjoyed this post then why not add us on Google+? Add us to your Circles

Share this Tutorial Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.