Detect double click in mouseReleased method - java

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);
}
}
}

Related

How can we do undo and redo functionality for a swt texteditor

I have created a swt textbox and trying to do undo and redo functionality but when i press "ctrl+z" the listener itself is not working .so how can we do undo and redo operations.the code to implement undo and redo is as follows
private static class CTabItemControl extends Composite {
private static class UndoRedoStack<T> {
private Stack<T> undo;
private Stack<T> redo;
public UndoRedoStack() {
undo = new Stack<T>();
redo = new Stack<T>();
}
public void pushUndo(T delta) {
undo.add(delta);
}
public void pushRedo(T delta) {
redo.add(delta);
}
public T popUndo() {
T res = undo.pop();
return res;
}
public T popRedo() {
T res = redo.pop();
return res;
}
public T peekUndo() {
T res = undo.peek();
return res;
}
public void clearRedo() {
redo.clear();
}
public void clearUndo() {
undo.clear();
}
public boolean hasUndo() {
return !undo.isEmpty();
}
public boolean hasRedo() {
return !redo.isEmpty();
}
}
//private StyledText editor;
private UndoRedoStack<ExtendedModifyEvent> stack;
private boolean isUndo;
private boolean isRedo;
public CTabItemControl(Composite parentComposite,final CTabItem tabitem){
super(parentComposite, SWT.NONE);
setLayout(new GridLayout(1, false));
editor = new StyledText(this, SWT.MULTI | SWT.V_SCROLL);
editor.setLayoutData(new GridData(GridData.FILL_BOTH));
editor.setFont(new Font(Display.getDefault(),"Cambria", 10, SWT.NORMAL));
editor.addListener(SWT.KeyDown, new Listener(){
public void handleEvent(Event event) {
event.doit = true;
if(!tabitem.getText().contains("*"))
{
tabitem.setText('*'+tabitem.getText());
System.out.println("inserted *");
}
}
});
editor.addExtendedModifyListener(new ExtendedModifyListener(){
//editor.addKeyListener(this);
public void modifyText(ExtendedModifyEvent event) {
if (isUndo) {
stack.pushRedo(event);
} else { // is Redo or a normal user action
stack.pushUndo(event);
if (!isRedo) {
stack.clearRedo();
}
}
}
});
editor.addKeyListener(new KeyListener() {
public void keyPressed(KeyEvent e) {
// Listen to CTRL+Z for Undo, to CTRL+Y or CTRL+SHIFT+Z for Redo
boolean isCtrl = (e.stateMask & SWT.CTRL) > 0;
boolean isAlt = (e.stateMask & SWT.ALT) > 0;
if (isCtrl && !isAlt) {
boolean isShift = (e.stateMask & SWT.SHIFT) > 0;
if (!isShift && e.keyCode == 'z') {
{
System.out.println("call undo");
undo();
}
} else if (!isShift && e.keyCode == 'y' || isShift
&& e.keyCode == 'z') {
redo();
}
}
if(e.stateMask == SWT.CTRL && e.keyCode == 'a'){
editor.selectAll();
}
}
public void keyReleased(KeyEvent e) {
// ignore
}
});
//this.editor = editor;
stack = new UndoRedoStack<ExtendedModifyEvent>();
}
private void revertEvent(ExtendedModifyEvent event) {
System.out.println("calling revertevent");
editor.replaceTextRange(event.start, event.length, event.replacedText);
// (causes the modifyText() listener method to be called)
editor.setSelectionRange(event.start, event.replacedText.length());
}
private void undo() {
System.out.println("calling undo");
if (stack.hasUndo()) {
isUndo = true;
revertEvent(stack.popUndo());
isUndo = false;
}
}
private void redo() {
if (stack.hasRedo()) {
isRedo = true;
revertEvent(stack.popRedo());
isRedo = false;
}
}
public void clearUndoRedo() {
stack.clearUndo();
stack.clearRedo();
}
public boolean hasUndo() {
return stack.hasUndo();
}
public String peekUndo() {
return stack.peekUndo().toString();
}
}
When you press Ctrl + Z or Ctrl + Y, you get 2 key events, one for Ctrl and one for another key. So it is better to check for the character of the second event
e.character == 0x1a
for Ctr + Z, and
e.character == 0x19
for Ctrl + Y

jScrollPane.viewport MouseListener doesn't work if added its viewport.view MouseListener

I have a JScrollPane subclass with this methods.
private MouseListener currentViewportMouseListener;
private MouseMotionListener currentViewportMouseMotionListener;
private MouseListener currentScrollableMouseListener;
private MouseMotionListener currentScrollableMouseMotionListener;
#Override
public void setViewportMouseListener(MouseListener mouseListener)
{
if (currentViewportMouseListener == mouseListener) return;
viewport.removeMouseListener(currentViewportMouseListener);
viewport.addMouseListener(mouseListener);
currentViewportMouseListener = mouseListener;
}
#Override
public void setViewportMouseMotionListener(MouseMotionListener mouseMotionListener)
{
if (currentViewportMouseMotionListener == mouseMotionListener) return;
viewport.removeMouseMotionListener(currentViewportMouseMotionListener);
viewport.addMouseMotionListener(mouseMotionListener);
currentViewportMouseMotionListener = mouseMotionListener;
}
#Override
public void setScrollableMouseListener(MouseListener mouseListener)
{
if (currentScrollableMouseListener == mouseListener) return;
viewport.getView().removeMouseListener(currentScrollableMouseListener);
viewport.getView().addMouseListener(mouseListener);
currentScrollableMouseListener = mouseListener;
}
#Override
public void setScrollableMouseMotionListener(MouseMotionListener mouseMotionListener)
{
if (currentScrollableMouseMotionListener == mouseMotionListener) return;
viewport.getView().removeMouseMotionListener(currentScrollableMouseMotionListener);
viewport.getView().addMouseMotionListener(mouseMotionListener);
currentScrollableMouseMotionListener = mouseMotionListener;
}
So when I use first pair of methods its ok.
scrollPane.setViewportMouseListener(mouseListener);
scrollPane.setViewportMouseMotionListener(mouseListener);
But if I set viewport and view listeners at the same time, viewport Mouse(Motion)Listener does not catch any events.
scrollPane.setViewportMouseListener(mouseListener);
scrollPane.setViewportMouseMotionListener(mouseListener);
scrollPane.setScrollableMouseListener(scrollableMouseListener);
scrollPane.setScrollableMouseMotionListener(scrollableMouseListener);
And I've checked it out in debugger, both viewport and view listener properties fill correct (different objects).
public void constructorOrMethodThatCreatesViewport()
{
// ...
this.viewport.addMouseListener(mainMouseListener);
this.viewport.addMouseMotionListener(mainMouseListener);
}
private MouseListener currentViewportMouseListener;
private MouseMotionListener currentViewportMouseMotionListener;
private MouseListener currentScrollableMouseListener;
private MouseMotionListener currentScrollableMouseMotionListener;
private final MyMouseListener mainMouseListener = new MyMouseListener();
private class MyMouseListener implements MouseListener, MouseMotionListener
{
private MouseEvent viewportToScrollableEvent(MouseEvent event)
{
Rectangle viewRect = viewport.getViewRect();
MouseEvent r = new MouseEvent((Component) event.getSource(),
event.getID(), event.getWhen(), event.getModifiers(),
event.getX()+viewRect.x, event.getY()+viewRect.y,
Math.abs(event.getX()+viewRect.x),
Math.abs(event.getY()+viewRect.y),
event.getClickCount(), event.isPopupTrigger(),
event.getButton());
return r;
}
public void mouseClicked(MouseEvent e)
{
if (null != currentScrollableMouseListener)
{
currentScrollableMouseListener.mouseClicked(viewportToScrollableEvent(e));
}
if (null != currentViewportMouseListener)
{
currentViewportMouseListener.mouseClicked(e);
}
}
public void mousePressed(MouseEvent e)
{
if (null != currentScrollableMouseListener)
{
currentScrollableMouseListener.mousePressed(viewportToScrollableEvent(e));
}
if (null != currentViewportMouseListener)
{
currentViewportMouseListener.mousePressed(e);
}
}
public void mouseReleased(MouseEvent e)
{
if (null != currentScrollableMouseListener)
{
currentScrollableMouseListener.mouseReleased(viewportToScrollableEvent(e));
}
if (null != currentViewportMouseListener)
{
currentViewportMouseListener.mouseReleased(e);
}
}
public void mouseEntered(MouseEvent e)
{
if (null != currentScrollableMouseListener)
{
currentScrollableMouseListener.mouseEntered(viewportToScrollableEvent(e));
}
if (null != currentViewportMouseListener)
{
currentViewportMouseListener.mouseEntered(e);
}
}
public void mouseExited(MouseEvent e)
{
if (null != currentScrollableMouseListener)
{
currentScrollableMouseListener.mouseExited(viewportToScrollableEvent(e));
}
if (null != currentViewportMouseListener)
{
currentViewportMouseListener.mouseExited(e);
}
}
public void mouseDragged(MouseEvent e)
{
if (null != currentScrollableMouseMotionListener)
{
currentScrollableMouseMotionListener.mouseDragged(viewportToScrollableEvent(e));
}
if (null != currentViewportMouseMotionListener)
{
currentViewportMouseMotionListener.mouseDragged(e);
}
}
public void mouseMoved(MouseEvent e)
{
if (null != currentScrollableMouseMotionListener)
{
currentScrollableMouseMotionListener.mouseMoved(viewportToScrollableEvent(e));
}
if (null != currentViewportMouseMotionListener)
{
currentViewportMouseMotionListener.mouseMoved(e);
}
}
}

Get key combinations

How can I get key combination of keys on keyboard E.G. (Ctrl+somekey, Alt+somekey) with Java?
I use KeyEvent listener, MouseEvent listener for all keys on keyboard. I can catch all key event on keyboard by using that listener. But, I cannot catch key combination such as (Ctrl+Alt+Del)....etc.
public void keyPressed(KeyEvent kevt) {
if(kevt.getKeyChar()=='c') {
if(kevt.isAltDown())
//Code if Alt+c pressed
if(kevt.isControlDown())
//Code if Ctrl+c pressed
if(kevt.isShiftDown())
//Code if Shift+c pressed
if(kevt.isAltDown()&&kevt.isControlDown()&&(!kevt.isShiftDown()))
//Code if Alt+Ctrl+c pressed
if(kevt.isAltDown()&&kevt.isShiftDown()&&(!kevt.isControlDown()))
//Code if Alt+Shift+c pressed
if(!(kevt.isAltDown())&&kevt.isControlDown()&&(kevt.isShiftDown()))
//Code if Shift+Ctrl+c pressed
if(kevt.isAltDown()&&kevt.isControlDown()&&kevt.isShiftDown())
//Code if Alt+Ctrl+Shift+c pressed
}
Use the above code, use any character
If you want to check if Alt+C+E is pressed do the following
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.swing.*;
public class Sample implements KeyListener {
private JTextField lbl=new JLabel("Hello");
private JPanel pnl=new JPanel(new BorderLayout());
private JFrame frm=new JFrame ("Sample");
int []arr;int i=0;
public Sample() {
pnl.add("North", lbl);
frm.setContentPane(pnl);
frm.pack();
frm.setVisible(true);
lbl.addKeyListener(this);
arr= new int[3];
public void keyPressed(KeyEvent key) {
arr[i]=key.getKeyCode();
i++;
if((arr[0]==VK_ALT||arr[1]==VK_ALT||arr[2]==VK_ALT)&& (arr[0]==VK_C||arr[1]==VK_C||arr[2]==VK_C)&&(arr[0]==VK_E||arr[1]==VK_E||arr[2]==VK_E)) {
//Code you want
}
}
public void keyReleased(KeyEvent evt) {
arr[i]=null;
}
public void keyTyped(KeyEvent kvt) {
}
}
}
Many of these answers seem very complicated, just thought I'd add my solution.
I wrote a KeyBinder class:
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.util.Hashtable;
public abstract class KeyBinder implements KeyListener
{
private Hashtable<Integer, Boolean> keyMap;
private int[] keyCodes;
public KeyBinder(final int... keyCodes)
{
this.keyMap = new Hashtable<>();
this.keyCodes = keyCodes;
}
#Override
public void keyTyped(final KeyEvent e) { }
#Override
public void keyPressed(final KeyEvent e)
{
getKeyMap().put(e.getKeyCode(), true);
if (getKeysDown())
{
onKeysDown();
}
}
#Override
public void keyReleased(final KeyEvent e)
{
getKeyMap().put(e.getKeyCode(), false);
}
private Hashtable<Integer, Boolean> getKeyMap()
{
return this.keyMap;
}
public boolean getKeysDown()
{
for (final int key : this.keyCodes)
{
if (getKeyMap().containsKey(key))
{
if (!getKeyMap().get(key))
{
return false;
}
} else {
return false;
}
}
return true;
}
public abstract void onKeysDown();
}
And then on my control:
final KeyBinder binder = new KeyBinder(KeyEvent.VK_ALT, KeyEvent.VK_A)
{
#Override
public void onKeysDown()
{
System.out.println("Alt+A");
}
};
startButton.addKeyListener(binder);
Easy :)
#Override
public void keyPressed(KeyEvent evt) {
if (evt.getKeyCode()==KeyEvent.VK_CONTROL) { ctrl = true; }
else if (evt.getKeyCode()==KeyEvent.VK_SHIFT) { shift = true; }
else if (evt.getKeyCode()==KeyEvent.VK_ALT) { alt = true; }
else {
keyHit = KeyEvent.getKeyText( evt.getKeyCode() );
System.out.println("Key Hit is "+keyHit);
}
processLocalKeyEvent(evt);
}
#Override
public void keyReleased(KeyEvent evt) {
if (evt.isControlDown() && keyHit != "") ctrl = true;
if (evt.isAltDown() && keyHit != "") alt = true;
if (evt.isShiftDown() && keyHit != "") shift = true;
if (ctrl) sb.append("Ctrl");
if (shift) sb.append("Shift");
if (alt) sb.append("Alt");
if (!ctrl && !shift && !alt) {
sb.append(keyHit);
} else {
sb.append("_"+keyHit);
}
if (ctrl || shift || alt) {
Thread thread = new Thread();
try {
thread.sleep(300);
rfbProto.capture();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} else if ((ctrl || shift || alt) && keyHit=="") {
rfbProto.capture();
} else if ((!ctrl || !shift || !alt) && keyHit!="") {
rfbProto.capture();
}
ctrl = false;
shift = false;
alt = false;
keyHit = "";
sb = new StringBuffer();
processLocalKeyEvent(evt);
}
private void jTable1KeyReleased(java.awt.event.KeyEvent evt) {
System.out.println(evt.getKeyCode()); //showing code of released button
if(evt.isControlDown() && evt.getKeyCode()==40) // 40 is code for arrow down
{
//if ctrl is pressed and arrow down is released
System.out.println("Released " + evt.getKeyCode());
}
Simple version

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);
}
}

Distinguish between a single click and a double click in 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();
}

Categories