It works, but the textfield will still show values between the 10s (Like 73) when dragging, and then adjust it when i let go of the slider. Is there a way to ONLY show tens, even when dragging?
Simply round off current JSlider
value to the nearest 10 and than set the JTextField
to that number:
js.addChangeListener(new ChangeListener() {
@Override
public void stateChanged(ChangeEvent e) {
if(js.getValueIsAdjusting()) {//slider value is still being adjusted
int num=(int)(Math.rint((double) js.getValue() / 10) * 10);//round to nearest 10
tf.setText(String.valueOf(num));//set textfield with value of nearest 10
} else {//slider value has been set/no adjustments happenening
tf.setText(String.valueOf(js.getValue()));
}
}
});
Also have a read on Concurrency in Swing, specifically on Event Dispatch thread
(EDT), which requires us to create and manipulate all Swing components on the EDT via SwingUtilities.invokeXXX
block:
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
//create/manipulate UI, components etc here
}
});