event

Determine click count example

With this tutorial we are going to see how can you determine the number of clicks that a user performed over an object in a Java Desktop application. This is very useful when you want the user to have rich interaction with your application using his mouse. You can also add extra functionality according to how many clicks the user did with the mouse.

In short all you have to do in order to detect double or triple clicks is:

  • Create a class that extends MouseAdapter
  • Override mouseClicked method in order to further customize the handling of that specific event. Now every time the user clicks a mouse button this method will be executed.
  • Use MouseEvent.getClickCount() to get the calculated click count

Let’s take a look a the code:

package com.javacodegeeks.snippets.desktop;

import java.awt.BorderLayout;
import java.awt.Button;
import java.awt.Component;
import java.awt.Frame;
import java.awt.TextArea;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;

public class ClickCounter {

  public static void main(String[] args) {

    // Create frame with specific title
    Frame frame = new Frame("Example Frame");

    // Create a component to add to the frame; in this case a text area with sample text
    final TextArea textArea = new TextArea("Click button to handle mouse clicks...");

    // Create a component to add to the frame; in this case a button
    Component button = new Button("Click Me!!");

    // Add a mouse listener to determine click counts
    button.addMouseListener(new MouseAdapter() {

  public void mouseClicked(MouseEvent evt) {

    if (evt.getClickCount() == 3) {

textArea.setText("Triple click");

    } else if (evt.getClickCount() == 2) {

textArea.setText("Double click");

    }

  }
    });

    // Add the components to the frame; by default, the frame has a border layout
    frame.add(textArea, BorderLayout.NORTH);
    frame.add(button, BorderLayout.SOUTH);

    // Show the frame
    int width = 300;
    int height = 300;
    frame.setSize(width, height);
    frame.setVisible(true);

  }

}

 
This was an example on how to determine click count in Java Desktop Application.

Byron Kiourtzoglou

Byron is a master software engineer working in the IT and Telecom domains. He is an applications developer in a wide variety of applications/services. He is currently acting as the team leader and technical architect for a proprietary service creation and integration platform for both the IT and Telecom industries in addition to a in-house big data real-time analytics solution. He is always fascinated by SOA, middleware services and mobile development. Byron is co-founder and Executive Editor at Java Code Geeks.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Back to top button