简体   繁体   中英

JTabbedPane - keep order of tabs

This problem is not necessarily specific to JTabbedPane, but this is where I came across it. The idea is that you have a list of priorities Priority[] according to which you would like to see the output tabs to be rendered. Each tab can have many objects associated with a given priority, and I want to generate the tab as the first object is detected for it. The objects are generated by external service and they may come in any order. So, let's say you have

[Low, Medium, Warning, Alert, Crash]

as your list of priorities. Now, this is what I want to generate

[] -> []
[Alert] -> [Alert]
[Alert, Alert] -> [Alert]
[Alert, Alert, Low] -> [Low, Alert]
[Alert, Alert, Low, Medium] -> [Low, Medium, Alert]

the RHS is the order of tabs and the LHS is the coming priorities. Any ideas how I can dynamically achieve this?

You can call the insertTab method on your JTabbedPane to insert your new tab at the specified position.

    insertTab(title, icon, panel, title, index);

So you can loop through each tab and insert it at the specified index based on the priority.

Something like this:

List<String> priorities = Arrays.asList("Low", "Medium", "Warning", "Alert", "Crash");
Map<List<String>> data = new LinkedHashMap<List<String>>();
for (String priority : priorities)
  data.put(priority, new ArrayList<String>());

...

Incoming data:

String priority = ...;

List<String> list = data.get(priority);
list.add("my new data");

if (list.size() == 1) {
  //insert tab
  int index = 0;
  int priorityIndex = priorities.indexOf(priority);
  while (priorityIndex > priorities.indexOf(tabbedPaned.getTitleAt(index))) {
    index++;
  }
  tabbedPane.insertTab(priority, ... , index); //includes index where to insert the tab
}

//update tabs
...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM