Display message automatically using Java Swing


 

Display message automatically using Java Swing

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

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) {}
}
}
}

Ads