tags:

views:

93

answers:

3

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.

A: 

Add a Box containing glue and your list to the scrollpane.

camickr
A: 

Inside your listener method that listens for a new item:

 String labelText = new String();
 for(int i = list.size()-1; i >= 0; i--)
 {
  labelText = list.get(i) + "<br>" + labelText;
 }
 label.setText(labelText);
Amber Shah
+1  A: 

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);
Joe Carnahan