Jlist Model?

Hi all,
can anyone please help me with a Jlist model. All I want to do is remove all the elements of a Jlist when a new action is performed:
  void jList1_mouseClicked(MouseEvent e)
    Room selectedRoom = SetOfRooms.getRoomFromID((String) jList1.getSelectedValue());
    if (e.getClickCount() == 1)
      SetOfPerson tempPerson = selectedRoom.getOccupants();
      for(int i = 0; i < tempPerson.length(); i++)
        displayOccupant(tempPerson.getNthMember(i));
  /*displayOccupant and display name are both
   used for displaying the room occupants in the JList*/
  public void displayOccupant(Person person)
    //I want to refresh the list heres o that new data can be added!
    String forename = person.getForename();
    String surname = person.getSurname();
    displayName(forename,surname);
  }Can anyone please help me with this, as I have looked everywhere and cant get it to work.
Thanks
Z.

I'd need more information than that. You have a JList model to display the JList data right? This should have your data structure (ArrayList or whatever) and the methods that act on it.
Just add a method called removeAll() or something thaty includes the listData.clear() call or equivilent.
public class YourExtendedModel extends AbstractListModel {
    private List theList;
    // Remove all items from the data list.
    public void removeAll() {
        theList.clear();
        this.fireContentsChanged(this, 0, theList.size());
}Then in your calling code, just use something like....
((YourExtendedModel)yourJList.getModel()).removeAll();But since I don't know how you've set up your JList, this may or may not work.

Similar Messages

  • JList.setModel() vs. new JList(model)

    Hi,
    i have some problems with setModel() in a way that it behaves differently as when using new JList(model).
    This works fine:
    wordsModel = new WordsListModel(Word.GOOD_WORD);
    wordList = new JList(wordsModel);
    wordsModel.addData(w);
    public class WordsListModel extends AbstractListModel{
    ArrayList data = new ArrayList();
    public WordsListModel(int wordsType) {
    createData(wordsType);
    public int getSize() {
    return data.size();
    public Object getElementAt(int index) {
    return data.get(index);
    public void addData(Word w) {
    data.add(w);
    fireIntervalAdded(this, data.size()-1, data.size());
    private void createData(int wordsType) {
    This works perfect, because when i add data dynamicly, the List gets updated via fireIntervalAdded().
    But when doing:
    wordList.setModel(newModel).
    wordsModel.addData(w);
    i cant update the list anymore, the model is updated but the JList doesnt get informed of the change. I noticed while studying the Swing docs, that with setModel() the JList is not in the listener list of my Model anymore. See the code of the AbstractListModel:
    protected void fireIntervalAdded(Object source, int index0, int index1)
         Object[] listeners = listenerList.getListenerList();
         ListDataEvent e = null;
         for (int i = listeners.length - 2; i >= 0; i -= 2) {
         if (listeners[i] == ListDataListener.class) {
              if (e == null) {
              e = new ListDataEvent(source, ListDataEvent.INTERVAL_ADDED, index0, index1);
              ((ListDataListener)listeners[i+1]).intervalAdded(e);
    When defining my Model with setModel() and triggering fireintervallAdded, i dont get inside the for loop, thus i dont have any listener which listens for updates.
    Whats wrong? Thanks

    i called the addData on the wrong (outdated) model object. So when i debuged the fireInteralAdded method in abstractModel, i only see the debug from the outdated model, which indeed didnt have any listeners/components ascociated anymore.

  • Customizing JList Cell Renderer

    Hi all,
    I got a problem with JList not rendering properly in my program. basically I create a customized renderer by extending JPanel and implementing ListCellRenderer.
    but somehow i cannot get the tooltiptext from the JLabel inside my JPanel (the renderer) to display the tooltiptext and responding to my mouse gesture. here's a snippet of my code.
    did i do something wrong?
    import java.awt.event.*;
    import javax.swing.*;
    import java.awt.*;
    public class TestR {
         private static class ListItem {
              private Color color;
              private String value;
              public ListItem(Color c, String s) {
                   color = c;
                   value = s;
              public Color getColor() {
                   return color;
              public String getValue() {
                   return value;
         private static class MyCellRenderer extends JPanel implements
                   ListCellRenderer {
              private JLabel lbl;
              public MyCellRenderer() {
                   // Don't paint behind the component
                   setOpaque(true);
                   setLayout(new BorderLayout());
                   lbl = new JLabel();
                   add(lbl);
              // Set the attributes of the
              //class and return a reference
              public Component getListCellRendererComponent(JList list, Object value, // value to display
                        int index, // cell index
                        boolean iss, // is selected
                        boolean chf) // cell has focus?
                   // Set the text and
                   //background color for rendering
                   lbl.setText(((ListItem) value).getValue());
                   lbl.setToolTipText("tooltip: "+((ListItem) value).getValue());
                   setBackground(((ListItem) value).getColor());
                   // Set a border if the
                   //list item is selected
                   if (iss) {
                        setBorder(BorderFactory.createLineBorder(Color.blue, 2));
                   } else {
                        setBorder(BorderFactory.createLineBorder(list.getBackground(),
                                  2));
                   return this;
         // Create a window
         public static void main(String args[]) {
              JFrame frame = new JFrame("Custom List Demo");
              frame.addWindowListener(new WindowAdapter() {
                   @Override
                   public void windowClosing(WindowEvent e) {
                        System.exit(0);
              // Use a list model that
              //allows for updates
              DefaultListModel model = new DefaultListModel();
              JList statusList = new JList(model);
              statusList.setCellRenderer(new MyCellRenderer());
              // Create some dummy list items.
              ListItem li = new ListItem(Color.cyan, "test line one");
              model.addElement(li);
              li = new ListItem(Color.yellow, "foo foo foo");
              model.addElement(li);
              li = new ListItem(Color.green, "quick brown fox");
              model.addElement(li);
              // Display the list   
              JPanel panel = new JPanel();
              panel.add(statusList);
              frame.getContentPane().add("Center", panel);
              frame.pack();
              frame.setVisible(true);
    }

    hi!
    import java.awt.event.*;
    import javax.swing.*;
    import java.awt.*;
    public class TestR {
         private static class ListItem {
              private Color color;
              private String value;
              public ListItem(Color c, String s) {
                   color = c;
                   value = s;
              public Color getColor() {
                   return color;
              public String getValue() {
                   return value;
         private static class MyCellRenderer extends JPanel implements
                   ListCellRenderer {
              private JLabel lbl;
              public MyCellRenderer() {
                   // Don't paint behind the component
                   setOpaque(true);
                   setLayout(new BorderLayout());
                   lbl = new JLabel();
                   add(lbl);
              // Set the attributes of the
              //class and return a reference
              public Component getListCellRendererComponent(JList list, Object value, // value to display
                        int index, // cell index
                        boolean iss, // is selected
                        boolean chf) // cell has focus?
                   // Set the text and
                   //background color for rendering
                   lbl.setText(((ListItem) value).getValue());
                   /*lbl.*/setToolTipText("tooltip: "+((ListItem) value).getValue());
                   setBackground(((ListItem) value).getColor());
                   // Set a border if the
                   //list item is selected
                   if (iss) {
                        setBorder(BorderFactory.createLineBorder(Color.blue, 2));
                   } else {
                        setBorder(BorderFactory.createLineBorder(list.getBackground(),
                                  2));
                   return this;
         // Create a window
         public static void main(String args[]) {
              JFrame frame = new JFrame("Custom List Demo");
              frame.addWindowListener(new WindowAdapter() {
                   @Override
                   public void windowClosing(WindowEvent e) {
                        System.exit(0);
              // Use a list model that
              //allows for updates
              DefaultListModel model = new DefaultListModel();
              JList statusList = new JList(model);
              statusList.setCellRenderer(new MyCellRenderer());
              // Create some dummy list items.
              ListItem li = new ListItem(Color.cyan, "test line one");
              model.addElement(li);
              li = new ListItem(Color.yellow, "foo foo foo");
              model.addElement(li);
              li = new ListItem(Color.green, "quick brown fox");
              model.addElement(li);
              // Display the list   
              JPanel panel = new JPanel();
              panel.add(statusList);
              frame.getContentPane().add("Center", panel);
              frame.pack();
              frame.setVisible(true);
    }try this out. this may help you. note at line no 50. /*lbl.*/setToolTipText("tooltip: "+((ListItem) value).getValue());:)
    Aniruddha

  • JList run time errors when removing items from list

    Hi there
    I am having trouble removing items from a JList. For a While it was working fine and now it outputs runtime errors everytime samething gets removed from the lsit
    Here is the code
    //declare
    public class Consumertab1gui extends JPanel implements ActionListener
         public static JList conList = null;
         private static DefaultListModel model = null;
    // Create a list with some items
    model = new DefaultListModel();
    conList = new JList(model);
    //set the size of cells in the list with the length of the string
    conList.setPrototypeCellValue("Lenght 1234567890");
    conList.setSelectionMode(ListSelectionModel.SINGLE_INTERVAL_SELECTION);
    conList.addListSelectionListener(new ValueReporter());
    //set a scroll onto the list
    JScrollPane conScroll = new JScrollPane(conList);
    add(conScroll,c);
    //when the button gets pressed to drop the selected item the following code is called
    private void dropConsumer()
    int selItem=0;
    componentsV.comVRemove(conList.getSelectedValue().toString());
    selItem=conList.getSelectedIndex();
    System.out.println("No:"+(model.getSize()-1));
    System.out.println("S:"+selItem);
    remConList(selItem);
    dropCon.setEnabled(false);
    //which in turns calls this
    public void remConList(int pos)
         model.remove(pos);
    when the model.remove(pos) code is executed the following runtime errors are given:
    java.lang.NullPointerException
    at Consumertab1gui$ValueReporter.valueChanged(Consumertab1gui.java:197)
    at javax.swing.JList.fireSelectionValueChanged(JList.java:1321)
    at javax.swing.JList$ListSelectionHandler.valueChanged(JList.java:1335)
    at javax.swing.DefaultListSelectionModel.fireValueChanged(DefaultListSelectionModel.java:187)
    at javax.swing.DefaultListSelectionModel.fireValueChanged(DefaultListSelectionModel.java:167)
    at javax.swing.DefaultListSelectionModel.fireValueChanged(DefaultListSelectionModel.java:214)
    at javax.swing.DefaultListSelectionModel.removeIndexInterval(DefaultListSelectionModel.java:546)
    at javax.swing.plaf.basic.BasicListUI$ListDataHandler.intervalRemoved(BasicListUI.java:1561)
    at javax.swing.AbstractListModel.fireIntervalRemoved(AbstractListModel.java:160)
    at javax.swing.DefaultListModel.remove(DefaultListModel.java:478)
    at Consumertab1gui.remConList(Consumertab1gui.java:38)
    at Consumertab1gui.dropConsumer(Consumertab1gui.java:58)
    at Consumertab1gui.actionPerformed(Consumertab1gui.java:46)
    at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:1786)
    at javax.swing.AbstractButton$ForwardActionEvents.actionPerformed(AbstractButton.java:1839)
    at javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:420)
    at javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:258)
    at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(BasicButtonListener.java:245)
    at java.awt.Component.processMouseEvent(Component.java:5100)
    at java.awt.Component.processEvent(Component.java:4897)
    at java.awt.Container.processEvent(Container.java:1569)
    at java.awt.Component.dispatchEventImpl(Component.java:3615)
    at java.awt.Container.dispatchEventImpl(Container.java:1627)
    at java.awt.Component.dispatchEvent(Component.java:3477)
    at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:3483)
    at java.awt.LightweightDispatcher.processMouseEvent(Container.java:3198)
    at java.awt.LightweightDispatcher.dispatchEvent(Container.java:3128)
    at java.awt.Container.dispatchEventImpl(Container.java:1613)
    at java.awt.Window.dispatchEventImpl(Window.java:1606)
    at java.awt.Component.dispatchEvent(Component.java:3477)
    at java.awt.EventQueue.dispatchEvent(EventQueue.java:456)
    at java.awt.EventDispatchThread.pumpOneEventForHierarchy(EventDispatchThread.java:201)
    at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:151)
    at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:145)
    at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:137)
    at java.awt.EventDispatchThread.run(EventDispatchThread.java:100)
    can anyone spot any mistakes in the code or suggest possible resons as to why these run time errors occur?
    Thanks
    alexis

    java.lang.NullPointerException
    at Consumertab1gui$ValueReporter.valueChanged(Consumertab1gui.java:197)The NullPointerException occurs at line 197, in the valueChanged method of your ValueReporter inner class. I have looked through your post several times but I don't see where you posted that method. Anyway, that is where you should look.
    PC&#178;

  • Why do we need JList?

    Why do we need JList, if JTable with one column can play its role?

    JTable models a table, JList models a list. Thus, JTable can do more and is more complex. JList can be used whenever just a list is needed.

  • JList in JScrollPane never shows horizontal scroll bar

    I have a JList inside a JScrollPane. When I add a lot of cells to the list, the vertical scroll bar appears as expected. However, if I add a cell that would require lots of horizontal space in which to render, the horizontal scroll bar never appears.
    Is there a way to make the JList take on the width of the widest rendered cell?
    Josh

    Here's some code that will demonstrate the problem. Run the code, then resize the window so that the horizontal scroll bar should appear.
    Code for jds.toys.Main:
    package jds.toys;
    import javax.swing.DefaultListModel;
    import javax.swing.JFrame;
    import javax.swing.JList;
    import javax.swing.JScrollPane;
    import javax.swing.SwingUtilities;
    public class Main extends JFrame {
         protected DefaultListModel model;
         public Main()
              super("JList in JScrollPane");
              model = new DefaultListModel();
              model.addElement("A very very very very very very long String");
              model.addElement("A very very very very very very very long String");
              model.addElement("A very very very very very very very very long String");
              model.addElement("A very very very very very very very very very long String");
              model.addElement("A very very very very very very very very very very long String");
              model.addElement("A very very very very very very very very very very very long String");
                      JList list = new JList(model);
                      list.setSize(300,300);
                      list.setFixedCellHeight(30);
                      list.setCellRenderer(new MyCellRenderer());
                      JScrollPane scrollPane = new JScrollPane(list);
                      add(scrollPane);
                      setSize(400,400);
        public static void main(String[] args) throws InterruptedException {
             final Main m = new Main();
            SwingUtilities.invokeLater(new Runnable() {
                public void run() {
                     m.setVisible(true);
    Code for jds.toys.MyCellRenderer:
    package jds.toys;
    import java.awt.Component;
    import java.awt.Graphics;
    import javax.swing.JList;
    import javax.swing.JPanel;
    import javax.swing.ListCellRenderer;
    public class MyCellRenderer extends JPanel implements ListCellRenderer
         private Object currentValue;
         private JList currentList;
         public MyCellRenderer()
         public Component getListCellRendererComponent(     JList list,
                                             Object value,
                                       int index,
                                       boolean isSelected,
                                       boolean cellHasFocus)
              currentValue = value;
              currentList = list;
              return this;
         public void paintComponent(Graphics g)
              int stringLen = g.getFontMetrics().stringWidth(currentValue.toString());
              int ht = currentList.getFixedCellHeight();
              g.setColor(getBackground());
              g.fillRect(0,0,stringLen,ht);
              g.setColor(getForeground());
              g.drawString(currentValue.toString(),0,ht/2);
    }

  • JList's setSelectedValue

    Hi!
    I'm using the "setSelectedValue" method from the JList class to
    select an item from a list of objects extending a class I developed named "Transition". This is the code I cannot get to work:
    DefaultListModel model=new DefaultListModel();
    JList list=new JList(model);
    model.addElement(new DefaultTransition());
    model.addElement(new FadeTransition());
    Transition transition=getTransition();
    list.setSelectedValue(transition,true);
    I supposed the "setSelectedValue" method would select one of the two
    items in the list but nothing gets selected. What am I doing wrong ?
    Thanks in advance

    Either getTransition() has to return one of the actual objects in the list or Transition needs to override the equals() method.

  • JList drag and drop to reorder items

    I like to see a implementation of a JList supporting drag and drop to reorder items. The solution has to work with any object type in the datamodel.

    import java.awt.event.MouseAdapter;
    import java.awt.event.MouseEvent;
    import javax.swing.DefaultListModel;
    import javax.swing.JFrame;
    import javax.swing.JList;
    import javax.swing.JScrollPane;
    import javax.swing.SwingUtilities;
    public class ReorderList {
       public static void main(String[] args) {
          SwingUtilities.invokeLater(new Runnable() {
             @Override
             public void run() {
                new ReorderList().makeUI();
       public void makeUI() {
          Object[] data = {"One", "Two", "Three", "Four", "Five",
             "Six", "Seven", "Eight", "Nine", "Ten", "Eleven", "Twelve"
          DefaultListModel model = new DefaultListModel();
          for (Object object : data) {
             model.addElement(object);
          JList list = new JList(model);
          MouseAdapter listener = new ReorderListener(list);
          list.addMouseListener(listener);
          list.addMouseMotionListener(listener);
          JFrame frame = new JFrame();
          frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
          frame.setSize(200, 200);
          frame.add(new JScrollPane(list));
          frame.setLocationRelativeTo(null);
          frame.setVisible(true);
    class ReorderListener extends MouseAdapter {
       private JList list;
       private int pressIndex = 0;
       private int releaseIndex = 0;
       public ReorderListener(JList list) {
          if (!(list.getModel() instanceof DefaultListModel)) {
             throw new IllegalArgumentException("List must have a DefaultListModel");
          this.list = list;
       @Override
       public void mousePressed(MouseEvent e) {
          pressIndex = list.locationToIndex(e.getPoint());
       @Override
       public void mouseReleased(MouseEvent e) {
          releaseIndex = list.locationToIndex(e.getPoint());
          if (releaseIndex != pressIndex && releaseIndex != -1) {
             reorder();
       @Override
       public void mouseDragged(MouseEvent e) {
          mouseReleased(e);
          pressIndex = releaseIndex;     
       private void reorder() {
          DefaultListModel model = (DefaultListModel) list.getModel();
          Object dragee = model.elementAt(pressIndex);
          model.removeElementAt(pressIndex);
          model.insertElementAt(dragee, releaseIndex);
    }edit Reduced a few LoC
    Edited by: Darryl.Burke

  • JList.getSelectedValue() ----- Casting problem

    Hi. I have a JList renderer named MyListCellRenderer which returns a JPanel;
    public class MyListCellRenderer implements ListCellRenderer{
         public Component getListCellRendererComponent(JList jList, Object value, int index, boolean selected, boolean focused){
              Object[] pairs = (Object[])value;
              ImageViewer imageViewer = new ImageViewer(((ImageIcon)pairs[0]).getImage());
              imageViewer.setStretched(true);
              JPanel jPanel = new JPanel(new BorderLayout());
              jPanel.add(imageViewer, BorderLayout.WEST);
              jPanel.add(new JLabel(pairs[1].toString()));
              if (selected) {
                   jPanel.setForeground(jList.getSelectionForeground());
                   jPanel.setBackground(jList.getSelectionBackground());
              }else {
                   jPanel.setForeground(jList.getForeground());
                   jPanel.setBackground(jList.getBackground());
              jPanel.setBorder(focused ? new LineBorder(Color.BLUE, 1) : new EmptyBorder(2, 2, 2, 2));
              return jPanel;
         }But when i try to cast it by my JList object like this;
    (JPanel)jList.getSelectedValue()it throws a java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to javax.swing.JPanel
    I got a little bit confused. I had returned the value as JPanel, why cant i cast the object, which returns by the jList.getSelectedValue(), to JPanel
    Is there another way to reach the JPanel in the jList?
    Thank you for any help                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           

    I dont know. I had supposed that it held JPanel. But if it canhelp you to understand here is the main program;
    public class ListCellRendererDemo extends JFrame implements ListSelectionListener{
         private static final int NUMBER_OF_COUNTRIES = 10;
         private DefaultListModel model = new DefaultListModel();
         private JList jList = new JList(model);
         private String[] countries = {"Canada", "China", "Norway", "France", "Germany", "India", "Norway",
         "Turkey", "United Kingdom", "United States of America"};
         private ImageIcon[] flagIcons = new ImageIcon[NUMBER_OF_COUNTRIES];
         private ImageIcon[] flags = new ImageIcon[NUMBER_OF_COUNTRIES];
         private ImageViewer imageViewer;
         public ListCellRendererDemo(){
              setDefaultCloseOperation(EXIT_ON_CLOSE);
              setTitle("List CellRenderer Demo");
              jList.setCellRenderer(new MyListCellRenderer());
              for(int i = 0; i < NUMBER_OF_COUNTRIES; i++){
                   flagIcons[i] = new ImageIcon("images/" + i + ".gif");
                   model.addElement(new Object[]{flagIcons, countries[i]});
                   flags[i] = new ImageIcon("images/" + i + ".gif");
              imageViewer = new ImageViewer(flags[0].getImage());
              imageViewer.setStretched(true);
              JSplitPane jSplitPane = new JSplitPane();
              jSplitPane.setLeftComponent(new JScrollPane(jList));
              jSplitPane.setRightComponent(imageViewer);
              jList.addListSelectionListener(this);
              add(jSplitPane);
              setSize(500, 250);
         public static void main(String[]args){
              new ListCellRendererDemo().setVisible(true);
         public void valueChanged(ListSelectionEvent evt){
              System.out.println((JPanel)jList.getSelectedValue());

  • JList update/paint problem

    I've got some problems with updating a JList. This code adds an element to the bottom of the list and makes it visible.
    Lines are added dynamicaly. It could be just 1 update a minute, but it could easely be 20 lines a split second...
    Sometimes the last line is not visible (shows line before lastline). And sometimes the list goes totaly blank, until the next repaint. I think it must be a syncro ploblem between various "repaint"-threads. I already made the add function syncronized, but that didn't help.
    Here's the code:
    //     DEFINITIONS
    JList list;
    DefaultListModel model;
    //     INITIALIZE
    model=new DefaultListModel();
    list=new JList(model);
    list.setDoubleBuffered(true);     //     same with or without dbfr
    add(new JScrollPane(list),BorderLayout.CENTER);
    //     ADD LINE
    public void add(Object obj){
         model.addElement(obj);
         list.ensureVisible(model.size()-1);
    }How to solve this?

    Just call ensureVisible(row) 2 timesThis may solve the problem, but it appears you still don't know the cause. Not sure, but this thread may help explain why you have the problem to begin with:
    http://forum.java.sun.com/thread.jsp?forum=57&thread=437592

  • JList, and problem related

    I use DefaulListModel to insert data into JList:
    DefaultListModel model =new DefaultListModel();
    model.addElement("item1");
    model.addElement("item2");
    JList list=new JList(model);
    but i use method: list.getSelectedvalue();
    result value is always null.
    please, help me

    duplicate post
    http://forum.java.sun.com/thread.jspa?messageID=4317841

  • Remove Selection from jList ??

    Hi,
    How do I remove a Selection from a jList??
    The items in the jList are Vectors
    I now use jList.clearSelection() but the selection stays there..
    Thanks,
    Marie

    Funny you should ask. I just now decided to try out what I suggested because I've never actually used a Vector in a JList. In my simple example below, I actually have to call repaint on the list to get it to refresh. I should NOT have to do that. Might be a bug in the VM?Please try it out on your machine and see if you can remove the 'repaint' statement in my action listener and get the list to refresh.
    I use 1.4.1_02 JDK. Let me know also which JDK you're using. Thanks!
    import javax.swing.*;
    import java.awt.event.*;
    import java.awt.BorderLayout;
    import java.util.Vector;
    public class MyList extends JFrame {
         Vector model = new Vector();
         public MyList() {
              super();
              setSize(300,400);
              getContentPane().setLayout(new BorderLayout());
              buildModel();
              final JList list = new JList(model);
              getContentPane().add(list, BorderLayout.CENTER);
              JButton btn = new JButton("remove");
              btn.addActionListener(new ActionListener() {
                   public void actionPerformed(ActionEvent e) {
                        model.remove(list.getSelectedIndex());
                        list.repaint(); //why should I have to force a repaint???
              getContentPane().add(btn, BorderLayout.NORTH);
              addWindowListener(new WindowAdapter() {
                   public void windowClosing(WindowEvent e) {
                        System.exit(0);
              show();
         private void buildModel() {
              model.add("one");
              model.add("two");
              model.add("three");
         public static void main(String[] args) {
              new MyList();

  • Avoid resize of JList with setFixedCellWidth

    I have functionality in my application such that when I select an item in one list, information that is associated with the item appears in a second list. I notice however that the width of this second list box is changing according to the contents of the list. The result is that each time I select an item in the first list, the second list changes size.
    I have tried using two methods, setFixedCellWidth(int value) and setPrototypeCellValue(" ") to control this behaviour. But the consequence is that although the second list does not change size, it also does not update with the information that is associated with the selected item in the first list.
    So my question is how do these methods effect the repaint and revalidation of the panel when the listmodel of the list is updated?
    Thanks so much.

    Excuse dupe post if there is one. You have other problems if you are not seeing updates in second list when using setProto. . . method. See Below:
    public class ListTest extends JFrame {
        Label label;
        DefaultListModel model;
        DefaultListModel targetModel;
        JList testList;
        JList targetList;
        public static void main( String[] args){
            new ListTest();
        public ListTest(){
            //super("Closing Test");
            getContentPane().setLayout(new BorderLayout());
            model = new DefaultListModel();
            for (int i = 0 ; i < 10 ;i++){
                model.addElement("test "+i);
            testList = new JList(model);
            testList.setDragEnabled(true);
            testList.setPrototypeCellValue("                                 ");
            testList.setTransferHandler(new ListTransferHandler());
            targetModel = new DefaultListModel();
            targetModel.addElement("test 6");
            testList.addListSelectionListener(new ListSelectionListener(){
                public void valueChanged(ListSelectionEvent lse){
                    System.out.println(((String)testList.getSelectedValue()));
             JPanel centerPanel = new JPanel(new GridLayout(0,2,5,5));
            targetList = new JList(targetModel);
            targetList.setPrototypeCellValue("                                 ");
            targetList.setDragEnabled(true);
            targetList.setTransferHandler(new ListTransferHandler());
            JScrollPane targetJsp = new JScrollPane(targetList);
            JScrollPane jsp = new JScrollPane(testList);
            centerPanel.add(jsp);
            centerPanel.add(targetJsp);
            getContentPane().add(centerPanel);
            //setSize(200,300);
            addWindowListener(new WindowAdapter(){
                public void windowClosing(WindowEvent we){
                    setVisible(false);
                    dispose();
                    System.exit(0);
            JPanel buttonPanel = new JPanel();
            JButton addButton = new JButton("add");
            addButton.addActionListener(new ActionListener(){
                public void actionPerformed(ActionEvent e){
                    Object[] selections = testList.getSelectedValues();
                    for (int counter = 0 ; counter < selections.length; counter++){
                        String tester = (String)selections[counter];
                        targetModel.addElement(selections[counter]);
            JButton subButton = new JButton("subtract");
            subButton.addActionListener(new ActionListener(){
                public void actionPerformed(ActionEvent e){
                    if ( targetList.getSelectedIndex() >= 0){
                        targetModel.removeElementAt(targetList.getSelectedIndex());
            buttonPanel.add(addButton);
            buttonPanel.add(subButton);
            getContentPane().add(buttonPanel, BorderLayout.SOUTH);
                    setVisible(true);
            pack();
    }Cheers
    DB

  • Problem repainting JList

    Hi everybody,
    I'm having big trouble repainting a JList after an element is inserted. So any help is mery much appreciated.
    I've a JDialog,let's say ElementListWindow with a JList, let's say ElementList , along with other components such as JComboBox, JtextArea etc. At the start up, the ElementList is populated throught "DefaultListModel" by fetching the data form database via the object ListElementDAO. Next to the ElementList i've a button which opens a modal window (also a JDialog) so that the user can add an element to the JList. The new element is inserted to the base via ListElementDAO and what i'm tryin to do is that the change is reflected to the ElementList as well. So i'm using the pattern Observer/Observable so that the ListElementDAO, which extends Observable, notifies the ElementListWindow which implements Overver and it's method "update".
    So when i insert a new element, the method "update" receives the new element. I put it in the DefaultListModel. Everything is fine until here. and try to repaint the ElementList butnothing seems to happen. The new item is not in the ElementList .
    public void update(Observable arg0, Object arg1) {
         model.insertElementAt(((Vector) arg1).get(0), 0);//model is an instance of DefaultListModel. Here, model contains the the element I just inserted to the database
         jListF.repaint();
         jListF.validate();     
    }I've printed some of the properties of ElementList .
    jListF.isValid() :true
    jListF.isVisible():true
    jListF.getParent()javax.swing.JViewport[,1,1,221x70,layout=javax.swing.ViewportLayout,alignmentX=0.0,alignmentY=0.0,
    border=,flags=25165832,maximumSize=,minimumSize=,preferredSize=,isViewSizeSet=true,
    lastPaintPosition=java.awt.Point[x=0,y=0],scrollUnderway=false]
    jListF.getPeer() instanceof LightweightPeer =true
    i've also tried
    model.add(int index,Object element) ;and also
    model.addElement(Object obj);but nothing works.
    i've also tried the "paintImmediately(...) method but no success.
    Just for information, if i try repainting a JLabel or a JTestPane inside "update" method that works perfectly but not in the case of list.
    I don't understand where the problem is.
    Please help. I'm trying to solve it for several days.

    Thanks for your replies.
    I'm sure the Vector is not empty and when i debug i see that the model contains previous elements (those already present in the list) + the one which was just inserted in the database and send to "update" method from the DAO object.
    private DefaultListModel model;
    private JList getJListF() {
         if (jListF == null) {
              model = bd_fournisseur.getListModelF();// retrieve list model form database     
              jListF = new JList(model);
              jListF.setSelectedIndex(0);
              jListF.setVisibleRowCount(4);
              jListF.setEnabled(true);
              jListF.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
         return jListF;
    }the jlistF is placed in a scrollpane. Nothing special regarding the code here.
    private JScrollPane getJScrollPane() {
         if (jScrollPane == null) {
              jScrollPane = new JScrollPane();
              jScrollPane.setBounds(new Rectangle(0, 0, 404, 66));
              jScrollPane.setBorder(null);
              jScrollPane.setViewportView(getJTextPane());
         return jScrollPane;
    }which in turn is in a JPanel.
    private JPanel getJContentPane() {
              if (jContentPane == null) {
                   jLabel7 = new JLabel();
                   jLabel7.setBounds(new Rectangle(12, 405, 61, 16));
                   jLabel7.setText("Prix TTC:");
                   jLabel6 = new JLabel();
                   jLabel6.setBounds(new Rectangle(12, 371, 72, 16));
                   jLabel6.setText("Taux TVA:");
                   jLabel5 = new JLabel();
                   jLabel5.setBounds(new Rectangle(12, 341, 53, 16));
                   jLabel5.setText("Prix HT:");
                   jLabel4 = new JLabel();
                   jLabel4.setBounds(new Rectangle(12, 311, 76, 16));
                   jLabel4.setText("Prix unitaire:");
                   jLabel3 = new JLabel();
                   jLabel3.setBounds(new Rectangle(12, 278, 56, 16));
                   jLabel3.setText("Quantité:");
                   jLabel2 = new JLabel();
                   jLabel2.setBounds(new Rectangle(12, 219, 58, 16));
                   jLabel2.setText("Libellé:");
                   jLabel1 = new JLabel();
                   jLabel1.setBounds(new Rectangle(12, 180, 64, 16));
                   jLabel1.setText("Catégorie:");
                   Fournisseur = new JLabel();
                   Fournisseur.setBounds(new Rectangle(12, 100, 75, 16));
                   Fournisseur.setText("Fournisseur:");
                   jLabel = new JLabel();
                   jLabel.setBounds(new Rectangle(12, 75, 38, 16));
                   jLabel.setText("Date:");
                   jContentPane = new JPanel();
                   jContentPane.setLayout(null);
                   jContentPane.add(getJScrollPane(), null);
                   jContentPane.add(jLabel, null);
                   jContentPane.add(getJTextFieldDate(), null);
                   jContentPane.add(Fournisseur, null);
                   jContentPane.add(getJScrollPane1(), null);
                   jContentPane.add(jLabel1, null);
                   jContentPane.add(getJComboCat(), null);
                   jContentPane.add(jLabel2, null);
                   jContentPane.add(getJScrollPane2(), null);
                   jContentPane.add(jLabel3, null);
                   jContentPane.add(getJTextFieldQuantite(), null);
                   jContentPane.add(jLabel4, null);
                   jContentPane.add(getJTextFieldPU(), null);
                   jContentPane.add(jLabel5, null);
                   jContentPane.add(getJTextFieldHT(), null);
                   jContentPane.add(jLabel6, null);
                   jContentPane.add(getJPanel(), null);
                   jContentPane.add(getJComboTaux(), null);
                   jContentPane.add(jLabel7, null);
                   jContentPane.add(getJTextFieldTTC(), null);
                   jContentPane.add(getJButton(), null);
                   jContentPane.add(getJButton1(), null);
                   jContentPane.add(getJButton2(), null);
                   jContentPane.add(getJButton3(), null);
              return jContentPane;
         }There is nothing special in my code.
    I just try to fetch the new element for DAO object and populate the list. BUT no way making it work.

  • Searcing in JList through JTextField

    My problem is as under:-
    1. I want searching through JTextField
    2. When i will enter any text in the JTextfield it will automatically search that text from the JList while typing
    3. And it comes on the top of the JList just like the pattern present in windows help.
    Thanks...
    Looking for solution...

    [url http://java.sun.com/docs/books/tutorial/uiswing/events/documentlistener.html]How to Write a Document Listener
    For every DocumentEvent you would get the text from the document and then search the JList model.

Maybe you are looking for

  • How do I add a signature manually using Ctrl + another key?

    I had programmed the Ctrl + S key so that I could manually add a signature. I upgraded to the new version of the software and it no longer works. Any suggestions?

  • Mass Change for Indirect Role Assignment

    Hi all, I am in the process of changing the company’s authorisations from a standard SU01 role assignment to a position based indirect role assignment. At the moment I am using PFCG going to the Org Mg button under the User tab then attaching the pos

  • Mail sending option at the work flow lavel

    Hi all, i m working for a Web Dynpro java where for my project "Classified" after creation of any classified item work flow is there name as approver and publisher. I m in search of the functionality where mail need to be trigger for the correspondin

  • Black & White Raw Images are Automatically Colorized -- Why?

    I am using a Lumix GF1 and shooting in black & white and raw.  I have the latest Adobe Camera Raw Program (5.6, I think), Photoshop CS4 and Bridge.  I upload the images from the camera to my pc using Bridge.  They appear in Brdige one-by-one in black

  • Will using your own router allow loopback connections?

    SomeJoe7777 you are correct regarding the route of a given packet when using a WAN IP locally (NAT loopback). However will again state that NAT loopback does not work using a router behind the NVG589. As you stated it should...which is why the issue