Feb 02

You can use a MouseListener to listen for clicks on your JTable. It will report both clicks and double clicks, reporting the click count via MouseEvent.getClickCount(). However when you double click on an non-editable column in your table your MouseListener unfortunately receives two event. Firstly it receives a single click event for the first click, then it receives a second double click event for the second click. Not very useful if you want to perform different actions depending on the number of clicks.

To get around this problem we can use a Swing Timer. We’ll start the Timer after the first click to wait for the second click. If the second click happens before the timer stops then its a double click, otherwise treat it as a single click.

The following class provides an implementation of this behaviour.

public class MouseClickListener extends MouseAdapter {

    private Timer timer = new Timer(300, new ActionListener() {

        public void actionPerformed(ActionEvent e) {
        	
            // timer has gone off, so treat as a single click
        	
            singleClick();
            timer.stop();
        }

    });

	@Override
	public void mouseClicked(MouseEvent e) {
		
		// Check if timer is running 
		// to know if there was an earlier click
		
		if (timer.isRunning()) {
			
			// There was an earlier click so we'll treat it as a double click
			
            timer.stop();
            doubleClick();
            
        } else {
        	
        	// (Re)start the timer and wait for 2nd click
        	
            timer.restart();
        }

	}

	protected void singleClick() {
		System.out.println("single click");
	}
	
	protected void doubleClick() {
		System.out.println("double click");
	}

}

written by objects \\ tags: , , , ,

Dec 22

The java.util.Timer class can be used to schedule code to be executed repeated at a fixed interval. The TimerTask class is used to encapsulate the code to be executed.


Timer timer = new Timer();
timer.schedule(new TimerTask()
{
    public void run()
    {
        // put the code you want to run here
    }
}, initialDelay, interval); 

written by objects \\ tags: , ,

Oct 01

The java.util.Timer class can be used to schedule code to be executed in the future. The TimerTask class is used to encapsulate the code to be executed.


Date whenToExecute = getTimeToExecuteCode();
Timer timer = new Timer();
timer.schedule(new TimerTask()
{
    public void run()
    {
        // put the code you want to run here
    }
}, whenToExecute); 

written by objects \\ tags: ,