Question

I have a JSlider that sets the speed of my metronome, from 40 - 200, where 120 is the default, in the middle.

When the user clicks the metronome button, the metronome plays at the speed displayed on the JSlider - the user drags the slider to the right, the speed of the metronome increases, and it decreases if they slide it to the left.

How do I add functionality so that if the user double-clicks on the JSlider button, it defaults back to 120 - in the middle?

Here is my code:

public Metronome() {
    tempoChooser = new JSlider();
    metronomeButton = new JToggleButton();

    JLabel metText = new JLabel("Metronome:");
    add(metText);

    ...

    tempoChooser.setMaximum(200);
    tempoChooser.setMinimum(40);
    tempoChooser.addChangeListener(new javax.swing.event.ChangeListener() {
        public void stateChanged(javax.swing.event.ChangeEvent evt) {
            tempoChooserStateChanged(evt);
        }
    });
    add(tempoChooser);
    ...
    }

private void tempoChooserStateChanged(javax.swing.event.ChangeEvent evt) {
    final int tempo = tempoChooser.getValue();
    if (((JSlider) evt.getSource()).getValueIsAdjusting()) {
        setMetronomeButtonText(tempo);
    } else {
        processTempoChange(tempo);
    }
}

thanks in advance!

Was it helpful?

Solution

This should help you out: http://docs.oracle.com/javase/tutorial/uiswing/events/mouselistener.html

You need to read up on that and implement MouseListener. You can use int getClickCount() to count how many times the user has clicked, which will help you read double clicks.

Hope this helps!

OTHER TIPS

Even though I dont see a question, my gues is you are looking for MouseListener.

Not simple job, you have to add javax.swing.Timer and listening if during fixed period Mouse cliked once or twice times, for example

I recently wrote something similar so I could differentiate between single and double left mouse-button clicks:

private Timer timer;
@Override
public void mouseClicked(MouseEvent e) {
    if(e.getButton() == MouseEvent.BUTTON1){
        if (timer == null) {
            timer = new Timer();
            timer.schedule(new TimerTask() {

                @Override
                public void run() { // timer expired before another click received, therefore = single click
                    this.cancel();
                    timer = null;
                    /* single-click actions in here */
                }

            }, (Integer) Toolkit.getDefaultToolkit().getDesktopProperty("awt.multiClickInterval"));
        }
        else { // received another click before previous click (timer) expired, therefore = double click
            timer.cancel();
            timer = null;
            /* double-click actions in here */
        }
    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top