javaswinguser-interfacejslider

Java JSlider: Dictionary is deprecated for method setLabelTable, what else should I use?


I am currently trying to setup a custom label for a JSlider in Java.

I looked up into the Java API and found this method: public void setLabelTable(Dictionary labels)

Unfortunately it turns out the Dictionary class and it's subclass Hashtable is obsolete.

According to the answer of this question: Using Java Dictionary...use a Hashtable?

The Hashtable class has been 'replaced' with HashMap.

So I tried to send a HashMap instead of a Hashtable, which I highly doubted it would work.

As expected, the compiler gave me this error:

incompatible types: HashMap<Integer, JLabel> cannot be converted to Dictionary

I can choose to use the Dictionary and the Hashtable class and compile with Xlint:Deprecated and it will give me the result that I want.

But I don't want to use something that's been obsolete for a while.

What should I use instead of setLabelTable(Dictionary labels)?

Or is there no other way than using setLabelTable(Dictionary labels)?

Desired Result

I want to produce this GUI without using a deprecated or obsolete API.


Solution

  • The Dictionary and Hashtable classes are deprecated for future use, and shouldn't be used for applications that just need to store key-value pairs. (As you saw, new applications should use the Collections class HashMap.)

    However, it is still perfectly fine to use the older classes for applications like yours where you are calling another function that needs a Dictionary or Hashtable as an argument. You really don't have any choice.

    If you wanted to minimize the amount of code in your project that used the older classes, you could use a HashMap to store your labels, and then use setLabelTable along with the Hashtable constructor that builds a Hashtable from a HashMap like this:

     mySlider.setLabelTable(new Hashtable(myLabelHashMap))