I have a JSlider with a min of 0 and a max of 10,000. I have the major tick marks set at 1,000. If I were to paint the labels now they would show up as 0, 1000, 2000, 3000, 4000, etc. What I would like to be shown would be 0, 1, 2, 3, 4, 5, etc. What would be a good way to accomplish this task?
Asked
Active
Viewed 6,808 times
2 Answers
2
using JSlider.setLabelTable(Dictionary)
EDIT
Alternatively you can rely on predefined label UI and just change the label text:
Enumeration e = jSlider.getLabelTable().keys();
while (e.hasMoreElements()) {
Integer i = (Integer) e.nextElement();
JLabel label = (JLabel) jSlider.getLabelTable().get(i);
label.setText(String.valueOf(i / 1000));
}

dfa
- 114,442
- 31
- 189
- 228
1
You could use JSlider.setLabelTable(Dictionary)
to set specific labels for the values you wish to render differently; e.g.
JSlider slider = ...
Dictionary dict = new Hashtable();
for (int i=0; i<=10000; i += 1000) {
dict.put(i, new JLabel(Integer.toString(i / 1000)));
}
slider.setLabelTable(dict);
(Edited based on previous comments.)

Adamski
- 54,009
- 15
- 113
- 152
-
Dictionary is an abstract class, so you might want to use Hashtable instead. You also need to get the number 10 in there. your for loop doesnt allow for that. – akf Jul 14 '09 at 14:24
-
Dictionary is abstract and cannot be instantied – dfa Jul 14 '09 at 14:24
-
rebuilding the label from scratch maybe a bad idea (using Java6 on windows the labels are broken) – dfa Jul 14 '09 at 14:44
-
How are they broken? I'm using Alloy L&F on Windows and JLabels seem ok. What would be the alternative to rebuilding the JLabel from scratch? – Adamski Jul 14 '09 at 14:47
-
check my answer (I'm on windows 7 with jdk 1.6u14) – dfa Jul 14 '09 at 15:00