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 calledlist
and that it is backed by aDefaultListModel
calledlistModel
, like this:Somewhere, you have code that actually adds new elements, like this:
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 ofaddElement()
, like this:Meanwhile, if your
JList
is displayed inside of a larger space, and you would like yourJList
to hug the bottom of the space, then you can put yourJList
inside of aJPanel
and tell it to stick to the bottom of theJPanel
using aBorderLayout
.So, for example, if you used to put your list into a
JScrollPane
, like this: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: