views:

214

answers:

2

Hi,

I have a JSlider which shows bet sizes (for a poker game) I am trying to achieve the effect that when a mouse click occurs the slider jumps forward by a bet amount (i.e. a big blind amount) rather than just incrementing by one. If the mouse click happens to the left of the bar i want it to decrement by a fixed amount else increment. I looked into attaching a mouse listener, but do not know how I can use the event to find out on what side of the bar the mouse was clicked.

Any ideas?

+2  A: 

I think you need to write a custom UI for this. This should get you started:

import java.awt.*;
import javax.swing.*;
import javax.swing.plaf.basic.*;
import javax.swing.plaf.metal.*;

public class SliderScroll extends JFrame
{
    public SliderScroll()
    {
        final JSlider slider = new JSlider(0, 50, 20);
        slider.setMajorTickSpacing(10);
        slider.setMinorTickSpacing(5);
        slider.setExtent(5);
        slider.setPaintTicks(true);
        slider.setPaintLabels(true);
        getContentPane().add( slider );

        slider.setUI( new MySliderUI() );
    }

    class MySliderUI extends MetalSliderUI
    {
        public void scrollByUnit(int direction)
        {
            synchronized(slider)
            {
                int oldValue = slider.getValue();
                int delta = (direction > 0) ? 10 : -5;
                slider.setValue(oldValue + delta);
            }
        }
    }

    public static void main(String[] args)
    {
        JFrame frame = new SliderScroll();
        frame.setDefaultCloseOperation( EXIT_ON_CLOSE );
        frame.pack();
        frame.setVisible( true );
     }
}
camickr
custom UIs are not good if you want to be able to use your program on different OSes (or versions of OSes) with their default look'n'feel
Fortega
Agreed, which I why I overrode the Metal LAF. It gives the poster an option to choose from. We can't assume that the requirement is to use the "platform" LAF.
camickr
+4  A: 

You just need to change your perspective on the problem.

Don't view the clicks as being to the 'left' or 'right' (below or above) the current bet.

Rather, you simply store the old tick, and look at what the new tick is. The difference will tell you if the user has tried to increase (positive delta) or decrease (negative delta).

Then you can increment by your desired 'fixed bet' amount.

Tim Drisdelle