Distinguish between a single click and a double click in Java - java

I search the forum and see this codes:
public void mouseClicked(MouseEvent e) {
if (e.getClickCount() == 2) {
System.out.println(" and it's a double click!");
wasDoubleClick = true;
} else {
Integer timerinterval = (Integer) Toolkit.getDefaultToolkit().getDesktopProperty(
"awt.multiClickInterval");
timer = new Timer(timerinterval.intValue(), new ActionListener() {
public void actionPerformed(ActionEvent evt) {
if (wasDoubleClick) {
wasDoubleClick = false; // reset flag
} else {
System.out.println(" and it's a simple click!");
}
}
});
timer.setRepeats(false);
timer.start();
}
}
but the code runs incorrectly(Sometime it prints out " and it's a single click!" 2 times . It should print out " and it's a double click!"). Can anybody show me why? or can you give me some better ways to do this?
Thank you!

Sometime it prints out " and it's a single click!" 2 times . It should print out " and it's a double click!").
That is normal. A double click only happens if you click twice within the specified time interval. So sometimes if you don't click fast enough you will get two single clicks in a row.
Integer timerinterval = (Integer) Toolkit.getDefaultToolkit().getDesktopProperty("awt.multiClickInterval");
The above line of code determines how fast the double click must be.
For what its worth here is some code I have used to do the same thing. Don't know if its any better or worse than the code you have:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
public class ClickListener extends MouseAdapter implements ActionListener
{
private final static int clickInterval = (Integer)Toolkit.getDefaultToolkit().
getDesktopProperty("awt.multiClickInterval");
MouseEvent lastEvent;
Timer timer;
public ClickListener()
{
this(clickInterval);
}
public ClickListener(int delay)
{
timer = new Timer( delay, this);
}
public void mouseClicked (MouseEvent e)
{
if (e.getClickCount() > 2) return;
lastEvent = e;
if (timer.isRunning())
{
timer.stop();
doubleClick( lastEvent );
}
else
{
timer.restart();
}
}
public void actionPerformed(ActionEvent e)
{
timer.stop();
singleClick( lastEvent );
}
public void singleClick(MouseEvent e) {}
public void doubleClick(MouseEvent e) {}
public static void main(String[] args)
{
JFrame frame = new JFrame( "Double Click Test" );
frame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
frame.addMouseListener( new ClickListener()
{
public void singleClick(MouseEvent e)
{
System.out.println("single");
}
public void doubleClick(MouseEvent e)
{
System.out.println("double");
}
});
frame.setSize(200, 200);
frame.setVisible(true);
}
}

public void mouseClicked(MouseEvent evt) {
if (evt.getButton()==MouseEvent.BUTTON1){
leftClick = true; clickCount = 0;
if(evt.getClickCount() == 2) doubleClick=true;
Integer timerinterval = (Integer)Toolkit.getDefaultToolkit().getDesktopProperty("awt.multiClickInterval");
timer = new Timer(timerinterval, new ActionListener() {
public void actionPerformed(ActionEvent evt) {
if(doubleClick){
System.out.println("double click.");
sb = new StringBuffer();
sb.append("Double Click");
clickCount++;
if(clickCount == 2){
clickCount=0;
doubleClick = false;
}
} else {
sb = new StringBuffer();
sb.append("Left Mouse");
System.out.println("single click.");
}
}
});
timer.setRepeats(false);
timer.start();
if(evt.getID()==MouseEvent.MOUSE_RELEASED) timer.stop();
}

Related

Mouse event goes through the component

I have added a simple program to illustrate.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class SimpleInternalFrame extends Frame
{
private static final long serialVersionUID = 1L;
static JLayeredPane desktop;
JInternalFrame internalFrame;
public SimpleInternalFrame()
{
super("Internal Frame Demo");
setSize(500, 400);
Panel p = new Panel();
add(p, BorderLayout.SOUTH);
addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent e)
{
System.exit(0);
}
});
desktop = new JDesktopPane();
desktop.setOpaque(true);
add(desktop, BorderLayout.CENTER);
}
public static void main(String args[])
{
SimpleInternalFrame sif = new SimpleInternalFrame();
sif.setVisible(true);
final JInternalFrame internalFrame = new JInternalFrame("Internal Frame 1", true, true, true, true);
internalFrame.setBounds(50, 50, 300, 200);
desktop.add(internalFrame, new Integer(1));
JTextField tf = new JTextField();
tf.addMouseListener(new MouseAdapter()
{
public void mouseClicked(MouseEvent evt)
{
System.out.println("Text Field " + evt.getClickCount());
}
});
internalFrame.add(tf);
internalFrame.setVisible(true);
final JInternalFrame internalFrame2 = new JInternalFrame("Internal Frame 1", true, true, true, true);
internalFrame2.setBounds(50, 50, 200, 100);
desktop.add(internalFrame2, new Integer(1));
JButton jb = new JButton("click me");
jb.addMouseListener(new MouseAdapter()
{
public void mouseClicked(MouseEvent evt)
{
if (evt.getClickCount() == 1)
{
System.out.println("Button " + evt.getClickCount());
internalFrame2.setVisible(false);
}
}
});
internalFrame2.add(jb);
internalFrame2.setVisible(true);
}
}
When running the code it will open a two internal frames.One has button.One has text field.Button will close the first Internal frame for single click.
Double click the button.It will show click count 2 as in text field.
This is the problem we have currently in the project.Thing is second frame dose not has text field in actual project.It has click-able item that work in double click event.
This is the problem we have currently.Please help.
tf.addMouseListener(new MouseAdapter() {
int cc;
public void mouseClicked(MouseEvent evt) {
int ccount = evt.getClickCount();
if(ccount == 1 || ccount == cc+1) {
cc = ccount;
System.out.println("Text Field " + evt.getClickCount());
}
}
});
This will work more than once.
Another possibility is to use components with overriden processMouseEvent():
public class SimpleInternalFrame extends Frame {
...
private MouseEvent lastMouseEvent;
public boolean checkEvent(MouseEvent e) {
if(lastMouseEvent != null) {
if(lastMouseEvent.getSource() != e.getSource()) {
if(e.getClickCount() != 1) {
return false;
}
}
}
lastMouseEvent = e;
return true;
}
class MTextField extends JTextField {
protected void processMouseEvent(MouseEvent e) {
if (checkEvent(e)) {
super.processMouseEvent(e);
}
}
}
class MButton extends JButton {
protected void processMouseEvent(MouseEvent e) {
if (checkEvent(e)) {
super.processMouseEvent(e);
}
}
}
public JTextField createText() {
return new MTextField();
}
public MButton createButton() {
return new MButton();
}
} //end of SimpleInternalFrame
create components:
final JTextField tf = sif.createText();
tf.addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent evt) {
System.out.println("Text Field " + evt.getClickCount());
}
});
JButton jb = sif.createButton();
jb.setText("click me");
jb.addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent evt) {
if (evt.getClickCount() == 1) {
internalFrame2.setVisible(false);
}
}
});
You can use a static boolean called myTurn initialized to false and then in the textfield mouseClicked:
tf.addMouseListener(new MouseAdapter()
{
public void mouseClicked(MouseEvent evt)
{
if (evt.getClickCount() >= 2 && !myTurn) {
myTurn = true;
evt.consume();
} else {
myTurn = true; //Initial one click on me
System.out.println("Text Field " + evt.getClickCount());
evt.consume();
}
}
});
This solves your problem in this basic case, but I don't know if it will in your application. The problem is that if you click the TextField before the Button, you can experience the same problem. However, if that isn't possible, this will solve it.
While searching on internet and reading some documents i was able get a solution.
int timerinterval = (int) Toolkit.getDefaultToolkit().
getDesktopProperty("awt.multiClickInterval");
final Timer timer = new Timer(timerinterval, new ActionListener()
{
public void actionPerformed(ActionEvent acEvt)
{
internalFrame2.setVisible(false);
}
});
jb.addMouseListener(new MouseAdapter()
{
public void mouseClicked(final MouseEvent evt)
{
System.out.println("Button " + evt.getClickCount());
timer.setRepeats(false);
timer.start();
if (evt.getClickCount() > 1)
{
timer.restart();
}
}
});
One draw back of this solution is if user do a single click he need to wait
timerinterval unnecessarily.Any one has better solution please post.

Can you make a JToolBar undetachable?

I would like to make my JToolBar impossible to detach from its container but still let the user drag it to one of the container's sides.
I know about
public void setFloatable( boolean b )
but this won't allow the user to move the JToolBar at all.
Is there any way of doing this without overwriting ToolBarUI?
Also, is there an option to highlight its new position before dropping it?
It's not the most elegant solution, but it works.
public class Example extends JFrame {
BasicToolBarUI ui;
Example() {
JToolBar tb = new JToolBar();
tb.add(new JButton("AAAAA"));
tb.setBackground(Color.GREEN);
ui = (BasicToolBarUI) tb.getUI();
getContentPane().addContainerListener(new Listener());
getContentPane().add(tb, BorderLayout.PAGE_START);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setSize(300, 300);
setLocationRelativeTo(null);
setVisible(true);
}
class Listener implements ContainerListener {
#Override
public void componentAdded(ContainerEvent e) {}
#Override
public void componentRemoved(ContainerEvent e) {
if (ui.isFloating()) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
ui.setFloating(false, null);
}
});
}
}
}
public static void main(String[] args) {
new Example();
}
}
Explanation:
Whenever the toolbar is moving to a floating state, it is instructed not do so. The only problem is that you have to wait for the EDT to finish the process for creating the floating window, and only then can you tell it not to float. The result is that you actually see the window created and then hidden.
Note:
I think that overriding the UI for the toolbar is a better solution, though it's possible that with a more intricate approach doing something similar to what I did will also work well.
works for me quite correctly on WinOS, old code from SunForum
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class CaptiveToolBar {
private Robot robot;
private JDialog dialog;
private JFrame frame;
public static void main(String[] args) {
//JFrame.setDefaultLookAndFeelDecorated(true);
//JDialog.setDefaultLookAndFeelDecorated(true);
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
new CaptiveToolBar().makeUI();
}
});
}
public void makeUI() {
try {
robot = new Robot();
} catch (AWTException ex) {
ex.printStackTrace();
}
final JToolBar toolBar = new JToolBar();
for (int i = 0; i < 3; i++) {
toolBar.add(new JButton("" + i));
}
frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(400, 400);
frame.setLocationRelativeTo(null);
frame.add(toolBar, BorderLayout.NORTH);
final ComponentListener dialogListener = new ComponentAdapter() {
#Override
public void componentMoved(ComponentEvent e) {
dialog = (JDialog) e.getSource();
setLocations(false);
}
};
toolBar.addHierarchyListener(new HierarchyListener() {
#Override
public void hierarchyChanged(HierarchyEvent e) {
Window window = SwingUtilities.getWindowAncestor(toolBar);
if (window instanceof JDialog) {
boolean listenerAdded = false;
for (ComponentListener listener : window.getComponentListeners()) {
if (listener == dialogListener) {
listenerAdded = true;
break;
}
}
if (!listenerAdded) {
window.addComponentListener(dialogListener);
}
}
}
});
frame.addComponentListener(new ComponentAdapter() {
#Override
public void componentMoved(ComponentEvent e) {
if (dialog != null && dialog.isShowing()) {
setLocations(true);
}
}
});
frame.setVisible(true);
}
private void setLocations(boolean moveDialog) {
int dialogX = dialog.getX();
int dialogY = dialog.getY();
int dialogW = dialog.getWidth();
int dialogH = dialog.getHeight();
int frameX = frame.getX();
int frameY = frame.getY();
int frameW = frame.getWidth();
int frameH = frame.getHeight();
boolean needToMove = false;
if (dialogX < frameX) {
dialogX = frameX;
needToMove = true;
}
if (dialogY < frameY) {
dialogY = frameY;
needToMove = true;
}
if (dialogX + dialogW > frameX + frameW) {
dialogX = frameX + frameW - dialogW;
needToMove = true;
}
if (dialogY + dialogH > frameY + frameH) {
dialogY = frameY + frameH - dialogH;
needToMove = true;
}
if (needToMove) {
if (!moveDialog && robot != null) {
robot.mouseRelease(InputEvent.BUTTON1_MASK);
}
dialog.setLocation(dialogX, dialogY);
}
}
}

Detect double click in mouseReleased method

I need to use mouseReleased method instead of mouseClicked so i need to find a way to Intercept double click. this is the code:
public void mouseReleased(MouseEvent e)
{
if (e.getClickCount() == 2)
System.out.println ("Double CLICK mouseReleased");
else
{
row= clientTable.rowAtPoint(e.getPoint());
col= clientTable.columnAtPoint(e.getPoint());
clientTable.sel(row, col);
}
}
The problem is that when I double-click I have also a single click event. Can anyone know ho to fix that? Thanks
1. Use the method getClickCount() method of ClassMouseEvent
2. This will help you to get the Type of the click.. Single , Double, Triple, etc..
See here for more details:
http://docs.oracle.com/javase/6/docs/api/java/awt/event/MouseEvent.html
public void mouseClicked(MouseEvent evt) {
if (evt.getButton()==MouseEvent.BUTTON1){
leftClick = true; clickCount = 0;
if(evt.getClickCount() == 2) doubleClick=true;
Integer timerinterval = (Integer)Toolkit.getDefaultToolkit().getDesktopProperty("awt.multiClickInterval");
timer = new Timer(timerinterval, new ActionListener() {
public void actionPerformed(ActionEvent evt) {
if(doubleClick){
System.out.println("double click.");
sb = new StringBuffer();
sb.append("Double Click");
clickCount++;
if(clickCount == 2){
rfbProto.capture();
clickCount=0;
doubleClick = false;
}
} else {
sb = new StringBuffer();
sb.append("Left Mouse");
System.out.println("single click.");
rfbProto.capture();
}
}
});
timer.setRepeats(false);
timer.start();
if(evt.getID()==MouseEvent.MOUSE_RELEASED) timer.stop();
}
}
there is no simpel fix to not have a single click when you double click
i wrote this once but it has a downside, your single click gets abit sluggish
example usage:
JLabel label = new JLabel("test");
label.addMouseListener(new SingleClickInhibitorMouseListener(some other mouselistener));
public class SingleClickInhibitorMouseListener implements MouseListener
{
public static final Integer CLICK_TRESHOLD = (Integer) Toolkit.getDefaultToolkit().getDesktopProperty("awt.multiClickInterval");
private Collection<MouseListener> mouseListeners = new ArrayList<MouseListener>();
public SingleClickInhibitorMouseListener( MouseListener listener )
{
mouseListeners.add(listener);
}
public void addMouseListener( MouseListener listener )
{
mouseListeners.add(listener);
}
public void removeMouseListener( MouseListener listener )
{
mouseListeners.remove(listener);
}
public void removeAllListeners()
{
mouseListeners.clear();
}
public void mouseSingleClick( MouseEvent e )
{
for (MouseListener mouseListener : mouseListeners)
{
mouseListener.mouseClicked(e);
}
}
public void mouseDoubleClick( MouseEvent e )
{
for (MouseListener mouseListener : mouseListeners)
{
mouseListener.mouseClicked(e);
}
}
public boolean hasDoubleClick = false;
public void mouseClicked( final MouseEvent me )
{
if ( me.getClickCount() == 1 )
{
new Thread(new Runnable()
{
public void run()
{
try
{
Thread.sleep(CLICK_TRESHOLD);
SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
if ( hasDoubleClick )
hasDoubleClick = false;
else
mouseSingleClick(me);
}
});
}
catch (InterruptedException e)
{
mouseSingleClick(me);
hasDoubleClick = false;
}
}
}).start();
}
else
{
if ( me.getClickCount() == 2 )
hasDoubleClick = true;
mouseDoubleClick(me);
}
}
public void mousePressed( MouseEvent e )
{
for (MouseListener mouseListener : mouseListeners)
{
mouseListener.mousePressed(e);
}
}
public void mouseReleased( MouseEvent e )
{
for (MouseListener mouseListener : mouseListeners)
{
mouseListener.mouseReleased(e);
}
}
public void mouseEntered( MouseEvent e )
{
for (MouseListener mouseListener : mouseListeners)
{
mouseListener.mouseEntered(e);
}
}
public void mouseExited( MouseEvent e )
{
for (MouseListener mouseListener : mouseListeners)
{
mouseListener.mouseExited(e);
}
}
}

Generate a double click mouse event in Java Swing

I am trying to generate a double click mouse event on the EDT as follows:
SwingUtilities.invokeLater(new Runnable() {
public void run() {
component.dispatchEvent(new MouseEvent(
component,
MouseEvent.MOUSE_CLICKED,
System.currentTimeMillis(),
InputEvent.BUTTON1_MASK,
x, y,
2, // click count
false
));
}
});
This does not seem to dispatch a double click event, even though I am setting the click count to 2.
Any suggestions or examples?
Considering:
final JButton clickTwiceButton = new JButton();
final JButton fireEventButton = new JButton();
Listeners:
clickTwiceButton.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
if (evt.getClickCount() == 2) {
JOptionPane.showMessageDialog(null, "Double clicked!");
}
}
});
fireEventButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
// Invoking later for no reason, just to simulate your code
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
clickTwiceButton.dispatchEvent(new MouseEvent(
fireEventButton,
MouseEvent.MOUSE_CLICKED,
1,
MouseEvent.BUTTON1,
0, 0,
2,
false
));
}
});
}
});
When I click fireEventButton the MouseEvent gets correctly dispatched to clickTwiceButton, and the dialog appears as expected.
So, as #Andrew pointed out, the problem seems to be that either you are firing the event to the wrong component or that something is not right with the registered MouseListener / MouseAdapter code.
Use component.getMouseListeners() to check for your component Listeners and debug the code that handles its events.
The method is very simple. You should get the time of the first click and the time of the second click, then you can do a condition in between.
Method code as below:
private boolean state=false;
private long first_pressed;
JButton btnAdd = new JButton("add");
btnAdd.addMouseListener(new MouseAdapter() {
#Override
public void mousePressed(MouseEvent e) {
if(state==false) {
first_pressed=e.getWhen();
state=true;
}
if(first_pressed!=e.getWhen())
{
JOptionPane.showConfirmDialog(null,"doubel click","Click",JOptionPane.YES_NO_OPTION);
state=false;
}
}
});
public class TestMouseListener implements MouseListener {
private boolean leftClick;
private int clickCount;
private boolean doubleClick;
private boolean tripleClick;
public void mouseClicked(MouseEvent evt) {
if (evt.getButton()==MouseEvent.BUTTON1){
leftClick = true; clickCount = 0;
if(evt.getClickCount() == 2) doubleClick=true;
if(evt.getClickCount() == 3){
doubleClick = false;
tripleClick = true;
}
Integer timerinterval = (Integer)Toolkit.getDefaultToolkit().getDesktopProperty("awt.multiClickInterval");
Timer timer = new Timer(timerinterval, new ActionListener() {
public void actionPerformed(ActionEvent evt) {
if(doubleClick){
System.out.println("double click.");
clickCount++;
if(clickCount == 2){
doubleClick(); //your doubleClick method
clickCount=0;
doubleClick = false;
leftClick = false;
}
}else if (tripleClick) {
System.out.println("Triple Click.");
clickCount++;
if(clickCount == 3) {
tripleClick(); //your tripleClick method
clickCount=0;
tripleClick = false;
leftClick = false;
}
} else if(leftClick) {
System.out.println("single click.");
leftClick = false;
}
}
});
timer.setRepeats(false);
timer.start();
if(evt.getID()==MouseEvent.MOUSE_RELEASED) timer.stop();
}
}
public static void main(String[] argv) throws Exception {
JTextField component = new JTextField();
component.addMouseListener(new TestMouseListener());
JFrame f = new JFrame();
f.add(component);
f.setSize(300, 300);
f.setVisible(true);
component.addMouseListener(new TestMouseListener());
}
}

Java MouseEvent, check if pressed down

I have a class that implements MouseListener (JPanel). When I click on the panel something happens. What I want is some kind of while-loop that loops as long as left mousebutton is pressed down.
#Override
public void mousePressed(MouseEvent e) {
while(e.isPressedDownD) { // <--
//DO SOMETHING
}
}
This obviously doesn't work, but I hope you understand what I'm trying to achieve.
The whole class for those that are interested:
package control;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import model.GridModel;
import view.GUIView;
public class MapListener implements MouseListener{
private GridModel model;
private GUIView view;
private int posX;
private int posY;
public MapListener(GridModel model, GUIView view) {
this.model = model;
this.view = view;
}
#Override
public void mouseClicked(MouseEvent e) {
posX = e.getX();
posY = e.getY();
model.setMouseAtX(posX);
model.setMouseAtY(posY);
view.paintTile();
System.out.println("X: " + posX + " Y: " + posY);
}
#Override
public void mouseEntered(MouseEvent e) {
}
#Override
public void mouseExited(MouseEvent arg0) {
}
#Override
public void mousePressed(MouseEvent e) {
while(e.getModifiers() == MouseEvent.MOUSE_PRESSED) { //Obviously doesn't work
//DO SOMETHING
}
}
#Override
public void mouseReleased(MouseEvent arg0) {
}
}
As pointed out by other answers, the place to do your work is not in the mouse event listener methods.
Also there is no explicit "mouse pressed" notion in MouseEvent, so you must track that yourself. I have provided an example of how to do this. Also note the MouseEvent.BUTTON1 references, as this is just to track the state of the left mouse button.
This is where you must start to learn about concurrency. For that reason, I've added in a synchronized method as you need to be aware that funny things happen when multiple threads access properties at the same time, and synchronized is a mechanism for keeping this sane. Consider it further reading beyond the scope of this example.
Untested, but this should work:
volatile private boolean mouseDown = false;
public void mousePressed(MouseEvent e) {
if (e.getButton() == MouseEvent.BUTTON1) {
mouseDown = true;
initThread();
}
}
public void mouseReleased(MouseEvent e) {
if (e.getButton() == MouseEvent.BUTTON1) {
mouseDown = false;
}
}
volatile private boolean isRunning = false;
private synchronized boolean checkAndMark() {
if (isRunning) return false;
isRunning = true;
return true;
}
private void initThread() {
if (checkAndMark()) {
new Thread() {
public void run() {
do {
//do something
} while (mouseDown);
isRunning = false;
}
}.start();
}
}
Why do so many of these answers wrongly assert that there is no explicit "mouse pressed" notion in MouseEvent?
Although the other commenters are correct that the OP should not be doing all that stuff in an event handler, there are other situations in which querying the button state in a mouse listener is useful. In those cases, you actually CAN determine the button down state. For example:
#Override
public void mouseExited(MouseEvent event) // Or any other mouse event handler...
{
int buttonsDownMask = MouseEvent.BUTTON1_DOWN_MASK
| MouseEvent.BUTTON2_DOWN_MASK
| MouseEvent.BUTTON3_DOWN_MASK; // Or whichever buttons you care about...
if ( (event.getModifiersEx() & buttonsDownMask) != 0 )
System.out.println("Hey! Some button is pressed!");
}
Notice in particular the use of the MouseEvent.getModifiersEx() method, along with MouseEvent.BUTTON1_DOWN_MASK and friends.
You could create a new Thread containing your while loop.
You start that Thread when the mouse button is pressed. You stop it when the mouse button is released.
You shouldn't be doing that in an event handler as no more events will be processed until the event handler exits.
What you want to achieve can be done with a separate worker thread. Create the thread from the mousePressed listener, do whatever you want to do in the thread (this should contain the while loop) and make the thread exit when the mouse is released (your mouseReleased listener should notify the thread).
for example
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class ClickListener extends MouseAdapter implements ActionListener {
private final static int clickInterval = (Integer) Toolkit.getDefaultToolkit().getDesktopProperty("awt.multiClickInterval");
private MouseEvent lastEvent;
private Timer timer;
public ClickListener() {
this(clickInterval);
}
public ClickListener(int delay) {
timer = new Timer(delay, this);
}
#Override
public void mouseClicked(MouseEvent e) {
/*if (e.getClickCount() > 2) {
return;
}
lastEvent = e;
if (timer.isRunning()) {
timer.stop();
doubleClick(lastEvent);
} else {
timer.restart();
}*/
if (timer.isRunning() && !e.isConsumed() && e.getClickCount() > 1) {
System.out.println("double");
timer.stop();
} else {
timer.restart();
}
}
#Override
public void actionPerformed(ActionEvent e) {
timer.stop();
singleClick(lastEvent);
}
public void singleClick(MouseEvent e) {
}
public void doubleClick(MouseEvent e) {
}
public static void main(String[] args) {
JFrame frame = new JFrame("Double Click Test");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.addMouseListener(new ClickListener() {
#Override
public void singleClick(MouseEvent e) {
System.out.println("single");
}
#Override
public void doubleClick(MouseEvent e) {
System.out.println("double");
}
});
frame.setPreferredSize(new Dimension(200, 200));
frame.pack();
frame.setVisible(true);
}
}

Categories