Character counter in JavaScript

This is about creating a character counter for textarea and limit it accordingly. You may have seen this kinda stuff in some messaging site mostly in sites which provides SMS facilities. They limit us to enter only specified number of characters in text area. Also in some sites there are limitation on characters in comments. So this article will help you in building a similar thing which will look like below picture:

Character counter for text area in JavaScript

Step 1 create a text area for entering text and an input text box which will hold remaining character count.

     Character Remaining:
     <INPUT  disabled size="3" value="140" name="txtLen" id="txtLen">
     <TEXTAREA id="textArea" name="textArea" rows="7" value="" cols="50"></TEXTAREA>

Step 2 Add key events on text area to monitor character count in it:

<TEXTAREA id="textArea" onKeyDown="countChars()" onKeyUp="countChars()" name="textArea" rows="7" value="" cols="50"></TEXTAREA>

Step 3 Create JavaScript function to calculate length of text entered in text area and change input box’s value accordingly and if length goes beyond limit then substring text up to length limit:

function countChars() {
     var l = "140";
     var str = document.getElementById("textArea").value;
     var len = str.length;
     if(len <= l) {
     } else {
          document.getElementById("textArea").value=str.substr(0, 140);

Step 4 Apply some CSS to it:

   FONT-WEIGHT: bold;
   BACKGROUND: #000000;
   MARGIN-LEFT: 0px;
   PADDING-TOP: 5px;
   FONT-WEIGHT: bold;
   FONT-SIZE: 12px;
   COLOR: #000;
   FONT-FAMILY: Tahoma;
   FONT-WEIGHT: bolder;

And its done. Hope this helps you.

Create tab view in java script

With the combination of div tag, style:display attribute of div tag and java script one can make a simple tab view which look something like as follow:

Following is the js code for that:

function tabChange(i) {
      for ( var j = 1; j <= 3; j++) {
           if (i == j) {
                document.getElementById("Page" + j).style.display = "block";
                document.getElementById("Tab" + j).className = "tabSelect";
           } else {
                document.getElementById("Page" + j).style.display = "none";
                document.getElementById("Tab" + j).className = "tab";

The html code:-

       <a id="Tab1" href="javascript:tabChange(1)">Tab 1</a><a id="Tab2" href="javascript:tabChange(2)">Tab 2</a><a id="Tab3" href="javascript:tabChange(3)">Tab 3</a>
<div id="Page1" class="box">
     First tab content.
<div id="Page2" style="display: none;">
     Second tab content.
<div id="Page3" style="display: none;">
     Third tab content.

And the css used in this example:

.tab {
    width: 105px;
    padding: 5px;
    color: #065fba;
    background: #f4f5f8;
    border: #e2e2e2 1px solid;
.tab:hover {
    background: #065fba;
    color: #f4f5f8;
.tabSelect {
    width: 800px;
    padding: 5px;
    background: #065fba;
    color: #f4f5f8;
    border: #e2e2e2 1px solid;
.box {
    width: 600px;
    padding: 5px;
    background: #ffffff;
    border: #065fba 2px solid;
a {
    color: #000000;
    text-decoration: none;

Create a scheduler task in 5 simple steps – java

Most people don’t know how to run some specific task at specific time in java. For example send daily email at 11:59 or do a daily wind up job or weakly database clean up job, etc. So here you will find how to schedule task in java in 5 simple steps.

Before starting first you need to download quartz jar. You can download it from here.

Step-1 Make a class that implements Job interface from quartz jar and implement it’s execute method. In this method define your task that will be executed on time interval.

public class ScheduleTaskHelper  implements Job  {
      public void execute(JobExecutionContext arg0) throws JobExecutionException {
           // define your task here.

Step-2 Create another class which will create and start scheduler for this task.

public class ScheduleTask{
       public ScheduleTask()throws Exception{

Step-3 To start scheduler task we first need to define a SchedulerFactory and a Scheduler. Following code will do that:

SchedulerFactory sf=new StdSchedulerFactory();
Scheduler sched=sf.getScheduler();

Step-4 Start that scheduler which is done by calling start method of Scheduler as follows:


Step-5 Create a Job of our task, a cron trigger to tell on which time interval it will run and schedule that job in the scheduler.

JobDetail jd=new JobDetail("myjob",  Scheduler.DEFAULT_GROUP,ScheduleTaskHelper.class);
CronTrigger tr=new CronTrigger("myCronTrigger", Scheduler.DEFAULT_GROUP,"0 59 23 ? * *");
sched.scheduleJob(jd, tr);

Note: – Here the string “0 59 23 ? * *” is used to define scheduler time that is on which time our scheduled task will run. Here this string will schedule task that will run daily in 11:59 pm. To know how to write appropriate cron trigger string refer to this.

Make JFrame transparent

How to create a slider for JFrame transparency and make JFrame transparent accordingly?

First create a frame that has a slider in it which will be used to set transparency amount.

import javax.swing.JFrame;
import javax.swing.JSlider;

public class TransparentFrame extends JFrame {
     public TransparentFrame() {
         setTitle("Transparent Frame");
         JSlider slider = new JSlider(JSlider.HORIZONTAL);
     public static void main(String[] args) {
         new TransparentFrame();

Output of this will be:

Now add a change listener to slider so we can monitor it.

slider.addChangeListener(new ChangeListener() {
       public void stateChanged(ChangeEvent e) {

Now we will write our transparency logic in this method but before we do that first let’s see how to make a JFrame transparent.

To make a JFrame transparent java has a built in utility class that is AWTUtilities. By using methods provided in this class we can make our JFrame transparent. Following is the code for that:

       AWTUtilities.setWindowOpacity(window, floatOpacity);


                  Window – Your frame/window object.

                  floatOpactity – between 0 to 1.  1 for no opacity and 0 for fully transparent.

So now we know that we have to add this logic to slider change event and give sliders value as floatOpacity value. So for that change stateChanged() method with following:

public void stateChanged(ChangeEvent e) {
      JSlider slider = (JSlider) e.getSource();
            AWTUtilities.setWindowOpacity(TransparentFrame.this, slider.getValue());

Think it’s done. No we still have to make sure that opacity value doesn’t go beyond its limit that is 0.0f to 1.0f. So for that we have to limit our slider to these values. As slider don’t supports point values we will take values in multiple of 10 and then divide them by 100 to get desired value. For this we will change JSlider declaration and stateChanged like follow:

JSlider slider = new JSlider(JSlider.HORIZONTAL, 10, 100, 100);

Change following line in stateChanged method:

AWTUtilities.setWindowOpacity(TransparentFrame.this, slider.getValue()/100f);

So now when we run this program we see a frame with a slider in it which is set to end. And when we change slider the frame accordingly change its transparency.



To use AWTUtilities class in eclipse you need to change preference setting or you may have error for accessing restricted classes. To change settings do as follows:

  1. Right click on your project. Select properties.
  2. Select Java compiler and expand it.
  3. Select Errors/Warnings.
  4. Enable project specific settings.
  5. In Deprecated and Restricted API you will find Forbidden References (access rules.) Change it to Warning or Ignore.

Also take a look take: Transparent JFrame using JNA

Create new message notification pop up in Java.

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


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.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.
frame.add(headingLabel, constraints);
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));
frame.add(cloesButton, constraints);
constraints.gridx = 0;
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);

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(…); :


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") {
        public void actionPerformed(final ActionEvent e) {

 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(){
      public void run() {
           try {
                  Thread.sleep(5000); // time after which pop up will be disappeared.
           } catch (InterruptedException e) {

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:


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.

%d bloggers like this: