Java – Displaying a list of items with Swing from bottom to top

javaswing

I need to display items in a list (read-only), but instead of the default top-to-bottom way of displaying a list, I need to display it bottom-to-top.

+-----------------+
|                 |
|                 |
|                 |
|                 |
|          value 3|
|          value 2|
|          value 1|
+-----------------+

If a new item is added, it should be added to the list like this :

+-----------------+
|                 |
|                 |
|                 |
|          value 4|
|          value 3|
|          value 2|
|          value 1|
+-----------------+

I couldn't find a Swing component allowing me to do this.
I have no experience in Swing and don't really know how I could solve this problem.

Best Answer

Somewhere in your code, each new item (value4, in your example) must be added to the list somewhere by adding it to a list model. Let's assume that your list is called list and that it is backed by a DefaultListModel called listModel, like this:

// Create a new list of items
DefaultListModel listModel = new DefaultListModel();
JList list = new JList(listModel);

Somewhere, you have code that actually adds new elements, like this:

public void addNewElement(Object elementToAdd)
{
    listModel.addElement(elementToAdd);
}

If you want to always add new elements at the beginning of the list, then you should just change the code to call insertElementAt() instead of addElement(), like this:

public void addNewElement(Object elementToAdd)
{
    listModel.insertElementAt(elementToAdd, 0);
}

Meanwhile, if your JList is displayed inside of a larger space, and you would like your JList to hug the bottom of the space, then you can put your JList inside of a JPanel and tell it to stick to the bottom of the JPanel using a BorderLayout.

So, for example, if you used to put your list into a JScrollPane, like this:

JScrollPane listScrollPane = new JScrollPane(list);

you could instead put your list into a JPanel that is the same color as the background of the list, and then you could put that list inside the scroll pane instead:

JPanel panel = new JPanel();
panel.setLayout(new BorderLayout());
panel.setBackground(list.getBackground());
panel.add(list, BorderLayout.SOUTH);
JScrollPane listScrollPane = new JScrollPane(panel);
Related Topic