This is a discussion on JSlider to setValue to where clicked on - Java ; maybe not in the spirit of Q&A, but picked up on some archived posts from a few years ago with same problem. (with no clear solutions) when clicked on a JSlider seems to go only to the next tick increment, ...
maybe not in the spirit of Q&A, but picked up on some archived posts
from a few years ago with same problem. (with no clear solutions)
when clicked on a JSlider seems to go only to the next tick increment,
not to where it was clicked on.
this code solved the problem for me
it would be better to be placed into an extended class of JSlider that
could be reused,
assumptions: the slider is the only JComponent in its parent and fully
occupying it (otherwise watch out for the getBounds, X value (relative
to parent, I think?).
public void mousePressed(MouseEvent e)
{
JSlider slider = (JSlider) e.getSource();
System.out.println(this.getClass().getName() + " mousePressed on
slider " + slider.getName());
// JSlider is useless in that clicking on it will increment by
ticks, not goto the location clcked on
// need to get the mouseX
// then relate this to the graphic, to get a proportion
// then set the slider to this value
Rectangle rect = slider.getBounds();
double length = rect.getWidth();
int leftX = rect.getLocation().x; // seemds to be 0 (relative to
parent)
int mouseX = e.getX();
int max = slider.getMaximum();
double ratio = mouseX/length;
double value = max*ratio;
int valueI = (int)value; // the value to set the slider to
}
then use SwingUtiilities to set the Slider.
final int valueF = valueI;
try
{
SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
sliderTrackDuration.setValue(valueF);
long time = (int) sliderTrackDuration.getValue(); // just
getting it back again
}
});
}
catch (Exception ex)
{
System.out.println("error" + ex.toString());
}
}
regards