javaswingsortingjmenu

Sorting groups of JMenuItems inside the same JMenu without sorting other JMenuItems


An application I'm working on let's users establish connections to some industry-specific Hardware. Those connections (IP/Host couplings) can be saved and given a name, and optionally a group attribute that will pair saved connections belonging to the same group.

I now have a JMenu that provides the user with all kinds of options to do with connections. The structure of the JMenu is as follows:

  1. Establish new Connection
  2. A JSeparator
  3. 3 Standard revisor connection entries that always stay the same
  4. JSeparator
  5. Multiple entries for the defined Connection-Groups
  6. JSeparator
  7. Multiple entries not belonging to a group
  8. JSeparator
  9. Close Connection

The sorting algorithm I need would have to sort the groupped entries from 5. alphabetically and the ungroupped entries from 7. alphabetically, without sorting any other MenuItems. Basically, how do I sort sub-groups of MenuItems inside a JMenu without sorting all of them?


Solution

  • It's been a while since I've used Swing, but I'm assuming you can store the string for each menu item's text in an array of Objects and render the menu items in a for loop. You could then store 1, 3, and 9 as strings in the array, and 5 and 7 as ArrayLists of strings within the first array. You could then insert a JSeparator between each item in the first array when you render it, making sure that each item is a string by using the instanceof keyword. If the item is not an instanceof string and it is an instanceof ArrayList<String>, you could render a menu item for each string in that inner ArrayList. You can sort the items in each inner ArrayList alphabetically using Collections.sort(mainArray[indexesOfSubarrays]).