Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

Update JList after remove/add element

3,221 views
Skip to first unread message

Dehong_Zhang

unread,
Nov 18, 2002, 2:25:50 PM11/18/02
to
Hi Everybody,

I have a JList on a JScrollPane, would like to update the view
after removing/adding some elements. I tried (JList).revalidate(),
(JList).repaint(), (JScrollPane).revalidate() and (JScrollPAne).repaint(),
just cannot get it to work. Please advise.

Thanks much and best regards,
Dehong

Bora Eryilmaz

unread,
Nov 18, 2002, 3:21:56 PM11/18/02
to
If you have a dynamic JList, it is better to use an extension (subclass) of
DefaultListModel and add/remove elements using its helper methods. Then the
JList will update itself without requiring intervention.

This is much more efficient than updating/repainting the whole JList, which
it seems you are trying to do.

Hope this helps,

Bora Eryilmaz

Steve W. Jackson

unread,
Nov 18, 2002, 3:22:35 PM11/18/02
to
In article <Pine.GSO.4.31.02111...@fsui02.fnal.gov>,
Dehong_Zhang <dhz...@fnal.gov> wrote:

:> Hi Everybody,

:>

Try using a ListModel with the JList. In my experience, that always
results in the displayed list immediately reflecting your changes.

= Steve =
--
Steve W. Jackson
Montgomery, Alabama

Nuno Ferreira

unread,
Nov 18, 2002, 8:31:33 PM11/18/02
to
Dehong_Zhang <dhz...@fnal.gov> wrote in message news:<Pine.GSO.4.31.02111...@fsui02.fnal.gov>...

Hi,
this should help:

/**
* @author Nuno Ferreira
*
* To change this generated comment edit the template variable "typecomment":
* Window>Preferences>Java>Templates.
* To enable and disable the creation of type comments go to
* Window>Preferences>Java>Code Generation.
*/
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;

public class Tester extends JFrame
{
private JList list = null;
DefaultListModel lm = null;
public Tester()
{
super("Tester");

initialize();

}

private void initialize()
{
setSize(300, 600);
int i = 0;
lm = new DefaultListModel();
lm.addElement(("value " + i++));
lm.addElement(("value " + i++));
lm.addElement(("value " + i++));
lm.addElement(("value " + i++));
lm.addElement(("value " + i++));
lm.addElement(("value " + i++));
lm.addElement(("value " + i++));
lm.addElement(("value " + i++));

list = new JList(lm);
getContentPane().setLayout(new BorderLayout(5, 5));
getContentPane().add(new JScrollPane(list), BorderLayout.CENTER);
JButton button = new JButton("Delete");
button.addActionListener
(
new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
int index = list.getSelectedIndex();
System.out.println("index: " + index);
if (index > -1)
lm.removeElementAt(index);

}
}
);
getContentPane().add(button, BorderLayout.SOUTH);
}

public static void main(String[] args)
{
Tester window = new Tester();
window.setVisible(true);
}
}

0 new messages