Hi,
Anyone has sample code or ideas on how I could do this where I can
populate a JList, and user can reorder each item by highlighting it,
then clicking on Up/Down buttons? Thanks.
Pete Barrett - 24 Jul 2005 10:44 GMT
>Hi,
>
>Anyone has sample code or ideas on how I could do this where I can
>populate a JList, and user can reorder each item by highlighting it,
>then clicking on Up/Down buttons? Thanks.
Oddly enough, I was just doing this for a JTable on Friday. The
TableModel was backed by a Vector, and all that was necessary was to
move the object which represented one of the rows from its old
position to its new position in the Vector. I imagine something
similar could be done with JList and ListModel.
Pete Barrett
Lee Weiner - 24 Jul 2005 18:26 GMT
>Anyone has sample code or ideas on how I could do this where I can
>populate a JList, and user can reorder each item by highlighting it,
>then clicking on Up/Down buttons? Thanks.
In the following code, btnUp and btnDown are JButtons, lstNames is a JList,
and nameModel is a DefaultListModel assigned to the JList.
btnUp.addActionListener( new ActionListener()
{
public void actionPerformed( ActionEvent e )
{
int index = lstNames.getSelectedIndex();
if( index == -1 )
JOptionPane.showMessageDialog( null, "Select something to move." );
else if( index > 0 )
{
String temp = (String)nameModel.remove( index );
nameModel.add( index - 1, temp );
lstNames.setSelectedIndex( index - 1 );
}
}
} );
btnDown.addActionListener( new ActionListener()
{
public void actionPerformed( ActionEvent e )
{
int index = lstNames.getSelectedIndex();
if( index == -1 )
JOptionPane.showMessageDialog( null, "Select something to move." );
else if( index < nameModel.size() - 1 )
{
String temp = (String)nameModel.remove( index );
nameModel.add( index + 1, temp );
lstNames.setSelectedIndex( index + 1 );
}
}
} );
Notice that nothing happens if the first item is selected and the Up button is
clicked, or the last item is selected and the Down button is clicked.
Lee Weiner
lee AT leeweiner DOT org