Search code examples
javaswingjpaneljlist

In Java Swing how can you manage a list of panels allowing multiple panels to be selected?


I’m working on an in-house app that tracks a bunch of tasks. I wanted to have a simple task monitor that would list the task name and the task’s status. I need this to look just a little nice, I’m no designer so whatever I do is going to suck, but a basic text display won’t work for the project requirements.

What I am essentially attempting to do is show something similar to the Firefox download window, the I-Tunes download window, and well I could name more but they all look basically the same. In each of these apps, each of the ‘progress panels’ is selectable. So to implement this I thought it would be simple to just use a list of JPanels each with a JProgressBar and a JLabel, each of which can just accept focus to determine if it and others are selected. I thought this was going to be an easy task, but if I use a JList it just displays text. I then just figured I would show all the task panels in a larger panel, but I cannot get the inner panels to recognize focus.

Is there a pattern for this? Is there a rolled standard solution that I just have not found? Or is there a better method for doing this? I don’t want to re-invent the wheel, but I thought this was just going to be simple.


Solution

  • It sounds like what you may be looking for is an JList.

    You can add your items to the JList's by first adding your "task" to the JList object's ListModel (see the Create a Model section from The Java Tutorials), and then you'll want to assigned a custom ListCellRenderer which will accept your "task" and render on the JList as a JPanel in the list itself. The key here is to make your custom ListCellRenderer be able to display your "task" in the JList the way you want to have it show on the JList.

    Take a look into the Writing a Custom Cell Renderer section from the How to Use Lists page of The Java Tutorials. It will describe how to make your custom ListCellRenderer so you can represent your "task" as anything you want.

    To keep it short, you will implement the ListCellRenderer interface by implementing the getListCellRendererComponent which will return a Component which is the representation of your task in the JList. You'll probably want to either construct or instantiate your JPanel in this method and return it as the Component.