Create Toast Message in Java Swing


A toast message is an alert which disappears with time automatically. With JDK 7, we can create a toast message similar to an alert on android very easily. Following are the steps needed to make a toast message.

Make a rounded rectangle shaped frame. Add a component listener to frame and override the componentResized() to change the shape of the frame. This method recalculates the shape of the frame correctly whenever the window size is changed.

frame.addComponentListener(new ComponentAdapter() {
   @Override
   public void componentResized(ComponentEvent e) {
      frame.setShape(new  RoundRectangle2D.Double(0,0,frame.getWidth(),
      frame.getHeight(), 20, 20));
   }
});

During display, initially show the frame then hide it slowly by making the opacity towards 0.

for (double d = 1.0; d > 0.2; d -= 0.1) {
   Thread.sleep(100);
   setOpacity((float)d);
}

Example

See the example below of a toast message window.

import java.awt.Color;
import java.awt.GridBagLayout;
import java.awt.event.ComponentAdapter;
import java.awt.event.ComponentEvent;
import java.awt.geom.RoundRectangle2D;

import javax.swing.JFrame;
import javax.swing.JLabel;

public class Tester {
   public static void main(String[] args) {
      ToastMessage message = new ToastMessage("Welcome to TutorialsPoint.Com");
      message.display();
   }
}

class ToastMessage extends JFrame {
   public ToastMessage(final String message) {
      setUndecorated(true);
      setLayout(new GridBagLayout());
      setBackground(new Color(240,240,240,250));
      setLocationRelativeTo(null);
      setSize(300, 50);
      add(new JLabel(message));
       
      addComponentListener(new ComponentAdapter() {
         @Override
         public void componentResized(ComponentEvent e) {
            setShape(new  RoundRectangle2D.Double(0,0,getWidth(),
            getHeight(), 20, 20));                      
         }
      });        
   }

   public void display() {
      try {
         setOpacity(1);
         setVisible(true);
         Thread.sleep(2000);

         //hide the toast message in slow motion
         for (double d = 1.0; d > 0.2; d -= 0.1) {
            Thread.sleep(100);
            setOpacity((float)d);
         }

         // set the visibility to false
         setVisible(false);
      }catch (Exception e) {
         System.out.println(e.getMessage());
      }
   }
}

Output

karthikeya Boyini
karthikeya Boyini

I love programming (: That's all I know

Updated on: 19-Jun-2020

832 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements