Create new message notification pop up in Java.

This article is about “How to create new message notification pop up in java?

Example:-

Pop up example

This image is taken from internet.

First create JFrame to work as pop up. Add some JLabels in it to contain information and assign them at proper location to look like a notification message.  A sample code is given below:

String message = "You got a new notification message. Isn't it awesome to have such a notification message.";
String header = "This is header of notification message";
JFrame frame = new JFrame();
frame.setSize(300,125);
frame.setLayout(new GridBagLayout());
GridBagConstraints constraints = new GridBagConstraints();
constraints.gridx = 0;
constraints.gridy = 0;
constraints.weightx = 1.0f;
constraints.weighty = 1.0f;
constraints.insets = new Insets(5, 5, 5, 5);
constraints.fill = GridBagConstraints.BOTH;
JLabel headingLabel = new JLabel(header);
headingLabel .setIcon(headingIcon); // --- use image icon you want to be as heading image.
headingLabel.setOpaque(false);
frame.add(headingLabel, constraints);
constraints.gridx++;
constraints.weightx = 0f;
constraints.weighty = 0f;
constraints.fill = GridBagConstraints.NONE;
constraints.anchor = GridBagConstraints.NORTH;
JButton cloesButton = new JButton("X");
cloesButton.setMargin(new Insets(1, 4, 1, 4));
cloesButton.setFocusable(false);
frame.add(cloesButton, constraints);
constraints.gridx = 0;
constraints.gridy++;
constraints.weightx = 1.0f;
constraints.weighty = 1.0f;
constraints.insets = new Insets(5, 5, 5, 5);
constraints.fill = GridBagConstraints.BOTH;
JLabel messageLabel = new JLabel("<HtMl>"+message);
frame.add(messageLabel, constraints);
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frame.setVisible(true);

Output of this will be:

First look of pop up.

Here I have created a JFrame and add two labels; first is headingLabel which is header label and second is messageLabel which will contains message information; and a close button. I have used GridBagLayout but you can use any of your choice.

Now to make this frame look like a popup we have to remove the title bar and border from this frame. For this add following line after frame.setSize(…); :

frame.setUndecorated(true);

Now the output will be:

Second look of pop up.

Note that now our frame cannot be closed as it do not have title bar close button. So to make our close button to work as frame closing button change its declaration as follows:

JButton cloesButton = new JButton(new AbstractAction("x") {
        @Override
        public void actionPerformed(final ActionEvent e) {
               frame.dispose();
        }
});

 After adding it you will get error as “Cannot refer to a non-final variable frame inside an inner class defined in a different method”.  To get rid of this error you can adopt one of following solution:

  1. Make your frame variable as final.
  2. Make your frame variable a global variable in class.
  3. Make your class extends JFrame and remove frame variable at all.

Now when you run your program it will look like same as in figure 2 but now you will be able to close your frame by clicking on closeButton.

You will notice that your frame appears at the top of screen so change to its location bottom right corner of the screen add following lines after creating frame:

Dimension scrSize = Toolkit.getDefaultToolkit().getScreenSize();// size of the screen
Insets toolHeight = Toolkit.getDefaultToolkit().getScreenInsets(frame.getGraphicsConfiguration());// height of the task bar
frame.setLocation(scrSize.width - frame.getWidth(), scrSize.height - toolHeight.bottom - frame.getHeight());

Now when you run it will look like this:

Third look of pop up.

Now to make it to disappear after predefined time add following lines at the end:

new Thread(){
      @Override
      public void run() {
           try {
                  Thread.sleep(5000); // time after which pop up will be disappeared.
                  frame.dispose();
           } catch (InterruptedException e) {
                  e.printStackTrace();
           }
      };
}.start();

Up to this you have successfully created a notification pop up that will appear at bottom-right corner of screen and disappear after some time if close button is not clicked.

So as a final touch you can design it as you want by applying look and feel or by applying different colours in frame.

Also you can make it appear on top of all windows by adding:

frame.setAlwaysOnTop(true);

Some things to notice in above code blocks:

                  1.      <HtMl> tag in messageLabel. It is to make word wrap in label. But make sure you text in message does not exceed some specific amount of length. You can adjust this and height of pop up as per your need.

                   2.      “headingIcon” is not declared in code. It is the image icon you want to use instead of devil icon in screen shot as a heading title icon. A sample declaration will look like:

                       ImageIcon headingIcon = new ImageIcon(“image_url”);

                    3.      Currently a new window for our pop up is shown in task bar so if you want that no window is shown for pop up in task bar change JFrame to JDialog.

                   4.      In above code default timeout before the pop up will be disappear is taken as 5 seconds you can update it as per your need by editing following line in code:

                        Thread.sleep(5000); // time after which pop up will be disappeared.

                    5.      To make close button look like default title bar’s close button “x” is taken in his text. You can write it close if you want to.

 

Hope this helps you. Thanks and Regards.

About these ads

About harryjoy
A passionate self-taught software developer. Currently working as Software Engineer in an IT company located in INDIA.

19 Responses to Create new message notification pop up in Java.

  1. Pingback: JavaPins

  2. karthik says:

    hey…this really helped…thanks..
    One problem
    When i made it disappear,then the notification disappear…but with in that time if one more notification comes,then it come and disappear,but the previous notification does not disappear.
    It gets stuck…Please help…

    • harryjoy says:

      Hi karthik,

      Some more information is required to help you:
      How you make it disappear? Do you use same code or modified it to fit your needs?
      Does it get closed after clicking on closeButton?

      Also make sure that you are calling dispose method of correct popup frame and you are not mixing frame variables of all opened popup frames.

  3. karthik says:

    Thanks for your reply.
    Now it is working fine.I made frame as instance variable and made modification in the same frame when new notification comes.

  4. zakaria says:

    thank you for this tutorial, i really appreciate it and we hope to see more tutorials about java

  5. Lily says:

    Thanks for the tutorial! It’s really helpful! What if there is 2 pop ups at the same time? How can I display the 2nd pop up on top of the first one? Thanks!

    • harryjoy says:

      Hi Lily,

      In your situation what you can do is maintain a list of popups. Whenever you need to display a popup add it in this list. Now whenever new popup comes check this list’s size and if its greater than one then update popup’s location based on list’s size. Instead of list you can also simply use a integer counter as you just need to know currently shown popup count.

      In this line you can change the location:

      frame.setLocation(scrSize.width - frame.getWidth(), scrSize.height - toolHeight.bottom - frame.getHeight());
      

      instead of this you can have:

      frame.setLocation(scrSize.width - frame.getWidth(), scrSize.height - toolHeight.bottom - (frame.getHeight() * (n+1)));
      

      Here ‘n’ is the number of popup opened before this popup. Let me know if any further explanation is required. :)

      • Lily says:

        Thanks for the reply Harsh, it’s popping up now! :) However, the cloesButton and sleep after 5 secs only works on one frame. What can I do to enable then on the other frames too? Thanks again! :)

        • harryjoy says:

          Hi Lily,

          If you have separate instance of all popup then it should work. Make sure you are not mixing up frame variables of popup. Don’t take only 1 frame variable to handle all popup. You should have different var for all. For this maintaining list of popup will be better option.

  6. Nubi says:

    So… Many… Errors…

    Do you have to import anything? sorry for my neeeewbnes.

    • harryjoy says:

      Hi ,

      Yes there are multiple imports. Which kind of errors are you getting? Let me know the errors and I will try to solve them for you.

      Thanks & regards,
      Harsh Raval.

  7. Sourour says:

    Thank you very much

  8. Douglas says:

    How can I do to not display the icon in the Windows Taskbar?

  9. Pingback: Java JFrame creating close button | BlogoSfera

  10. Victoria Alexandra says:

    Hi! How do I create arrow keys to click and see the prev or next messages on the pop-up?

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.

Join 53 other followers

%d bloggers like this: