DefaultListModel and setElementAt()

I am pulling objects out of a vector and inserting them into a DefaultListModel within a JList. I want to be able to replace what is in the index already (or just add it if nothing is there). Problem is, unless I define a size for the DefaultListModel, it gives me an ArrayIndexOutOfBounds excpetion when it get to the setElementAt() line. Here is my code:
        String target=separate.nextToken().trim();
        System.err.println("target: "+target);
        String source=separate.nextToken().trim();
        System.err.println("source: "+source);
        //dataListModel.setSize(5);
        Vector targetVec=calculateValue("set", target);
        Vector sourceVec=calculateValue("set", source);
        for (int j=0; j < sourceVec.size(); j++)
          //dataListModel.ensureCapacity(j+1);
          System.err.println("sourceVec: "+(String)sourceVec.get(j));
          System.err.println("index: "+j)
          dataListModel.setElementAt(sourceVec.get(j), j);
        }I tried using ensureCapacity() instead of setting the size but that did not work. I also tried
    if the listModel is empty
       add the element
    else
       setElementAt(blah, blah)but everytime it throws the OutOfBounds exception! What am I doing wrong? I cannot set the size as I cannot have any empty indices since I need the user to be able to delete the last item in the list, and if I set the size they have all the empty indices to delete first!! If I just use add(), then of course anything already in an index, just gets moved up. There is a possibility I will need to keep some of what is already in the list.

Thanks for your reply. Unfortunately I cannot call removeAllElements() as I may need what is in the DefaultListModel, here is what I mean:
    for (the number of user instructions)
       get the index supplied by user
            if it is empty
                add the value specified by user at the index specified by user
             else
                 replace index(value specified with user) with another value specified by usermeaning that the user could specify replacing index 1 and 3 for example with new values, but if there were values in indices 0, 2, 4, 5 these would need to remain (and in fact are visible to the user in the DefaultListModel as are the new values inserted by the user), thus removeAllElements() would delete needed information. Is this clearer?

Similar Messages

  • DefaultListModel and defaultTableModel

    Hi, I am trying to change my current JList which takes in a defaultListModel into a JTable which takes in a defaultTableModel. I have mirrored everything and commented out ones that does not have same functionalities, but now the former JList just displays a gray area. what am i doing wrong? what can I do to see the data? thank you.

    Without seeing code it's hard to say. Perhaps you forgot to set a cell renderer?

  • How to search for a string in a DefaultListModel

    I have a list of names stored in a DefaultListModel and would like to know how i can search for a particular name
    i assume i would have to use the method below but not sure of how to implement it
    so basically i would have a texfield where a user can type in a name to find in the list
    public int indexOf(Object elem)
    Searches for the first occurence of the given argument.
    Parameters:
    elem - an object.
    or i might be wrong
    Any ideas of how to write this mechanism
    Can anyone please help on this

    The DefaultListModel uses a Collection of some sort (Vector at present) to store data. You can get this data in two ways:
       DefaultListModel model = (DefaultListModel)list.getModel();
        Enumeration e = model.elements();
        while(e.hasMoreElements()) {
          if (e.nextElement().equals(elem)) return;
        }or
        Object[] array = model.toArray();
        for (int i = 0; i < array.length; i++) {
          if (array.equals(elem)) return;

  • Searching for a string in a DefaultListModel

    I have a list of names stored in a DefaultListModel and would like to know how i can search for a particular name
    i assume i would have to use the method below but not sure of how to implement it
    so basically i would have a texfield where a user can type in a name to find in the list
    public int indexOf(Object elem)
    Searches for the first occurence of the given argument.
    Parameters:
    elem - an object.
    or i might be wrong
    Any ideas of how to build this mechanism
    Can anyone please help on this

    Yes, that is the method you would use. How to "build this mechanism"? Are you asking how to use the method, or how to write a program that uses it?

  • JList and ListModel, can anyone explain the basics?

    Hi
    I have an object A containing a Vector X of objects. I want to display them in a JList. I could always use DefaultListModel and copy the items of the Vector X into the default list model using addElement. But that would create a copy of the information in vector X. That is exactly why one should use a custom list model to ensure that the data is in sync with the GUI .
    I want to add and remove items from the JList, and simultaious add and remove items from the Vector X. Can anyone proviede a samll example of how to do this.
    I have tryed myselfe, but I can not get the JList updated with the changes of the listmodel. I have read the documentation about ListDataListener, but I just don't get it. A small example would realy be appreciated!
    // Mattias

    Yse I have read the tutorial. But I don't understand it.
    Here is a small example program. Can anyone change the code so the list is updated with the canges that obviously take place (as one can see by pressing the "Dump button")
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.event.*;
    import java.util.*;
    class ListTest extends JFrame implements ActionListener , ListDataListener {
        JList list;
        MyListModel myListModel;
        MyDataObject myDataObject;
        ListTest() {
            JPanel p = new JPanel();
            myDataObject = new MyDataObject();
            myListModel = new MyListModel(myDataObject.x);
            list = new JList(myListModel);
            myListModel.addListDataListener(this);
            JScrollPane listScrollPane = new JScrollPane(list);
            listScrollPane.setPreferredSize(new Dimension(200, 100));
            p.add(listScrollPane);
            JButton b1 = new JButton("Add");
            b1.addActionListener(this);
            p.add(b1);
            JButton b2 = new JButton("Remove");
            b2.addActionListener(this);
            p.add(b2);
            JButton b3 = new JButton("Dump");
            b3.addActionListener(this);
            p.add(b3);
            setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            getContentPane().add(p);
            pack();
            show();
        public void actionPerformed(ActionEvent e) {
            if (e.getActionCommand().equals("Add")) {
                myListModel.addElement(""+ (1+myListModel.getSize()) );
                System.out.println("Added a row to the list");
            if (e.getActionCommand().equals("Remove")) {
                if (myListModel.getSize()>0) {
                    myListModel.remove(myListModel.getSize()-1);
                    System.out.println("Removed last element from the list");
                else {
                    System.out.println("No more elements to remove");
            if (e.getActionCommand().equals("Dump")) {
                System.out.println("\n\nData in the list model:");
                for (int i=0; i<myListModel.getSize() ; i++) {
                    System.out.println(myListModel.getElementAt(i));
                System.out.println("That should be the same as the vector x in the object myDataObject  :");
                for (int i=0; i<myListModel.getSize() ; i++) {
                    System.out.println(myDataObject.x.get(i));
        public void contentsChanged(ListDataEvent e) {
            System.out.println("contentsChanged");
        public void intervalAdded(ListDataEvent e) {
            System.out.println("intervalAdded");
        public void intervalRemoved(ListDataEvent e) {
            System.out.println("intervalRemoved");
        public static void main(String args[]) {
            new ListTest();
    class MyDataObject {
        Vector x;
        MyDataObject() {
            x=new Vector();
            x.addElement("1");
            x.addElement("2");
    class MyListModel extends AbstractListModel {
        Vector v;
        MyListModel(Vector v) {
            this.v=v;
        public void addElement(Object o) {
            v.addElement(o);
        public Object remove(int index) {
            return v.remove(index);
        public Object getElementAt(int index) {
            return v.get(index);
        public int getSize() {
            return v.size();
    </pre>

  • Really dumb question about defaultlistmodel

    having a mental block, but i have a defaultlistmodel and i would like to make a copy of it. something like:
    myListmodel2 = myListModel1.clone()
    ?????????

    and also colours.. why is there no:
    myColour2 = myColour1.clone();
    or
    myColour2 = new Color(myColour);
    I have had to do:
    mycolour2 = new Color(mycolour2.getred(), mycolour2.getGreen(), mycolour2.getBlue());
    so mysterious......

  • Accessing model in other class

    Hi all,
    I have two classes, one is a JFrame and the the other one is a JDialog. In the JFrame, I have a JList that uses the DefaultListModel and an "Add" JButton. When the user clicks the Add button. The JDialog pops up and allows the user to enter the detail of a new entry for the JList. When the user click the "Save" JButton on the JDialog. The new entry is added to the JList. My problem is that I need to add the new entry to the DefaultListModel when they user click the "Save" button on the JDialog, but I have no idea how to access the DefaultListModel in the JFrame from the JDialog (in other words, to get the calling object reference).
    I've searched the web for examples of using DefaultListModel, but the examples that I can find only use inner class. So there is no problem on accessing the DefaultListModel. But, in my case, I need to separate the two classes. Please give me some hints!
    Thanks,
    Welles

    When you create the JList object, you can keep a reference to the ListModel and then pass it to the JDialog. Something like this:
    DefaultListModel myModel = new DefaultListModel();
    MyDialog myDialog = new MyDialog(myModel);Jimmy

  • FireContentsChanged doesbot work in 1.4.

    I have a MyComboBoxModel which extends DefaultListModel and implements ComboBoxModel.
    I implemented the method as
    public void setSelectedItem(Object item)
         selectedItem = item;
         fireContentsChanged(this, -1, -1);
    I want to fire the fireContentsChanged even when the item is not changed in the JComboBox. I have another JComboBox as JComboBox2.
    Suppose I have obj1 and obj2 in JCOmboBox2, and item1 and itm2 in JComboBox1. And I had set the MyComboBoxModel to JComboBox1.
    The items in the JComboBox1 will depend on the object selected in the JComboBox2. So when ever the object is selected in JComboBox2, All the items gets removed in JCombobox1 and gets relavent added items for the object selcted in JC2.
    And based on the item selceted in JC1 and JC2, the screen refreshes.
    Now the problem is the above coded worked fine in 1.2. But it doesnot work in 1.4. If the item does n't change the JC1 then the fireContentsChanged is not working. And my whole logic is in the JC1 item state changed method.
    I do have work around solution. But I wonder why fireContentsChanged is not working.
    thanks

    maybe showMessageDialog won't accept null as an argument?

  • Why won't my JList update?

    My JList is first dimensioned to an array with 100 elements in it but then in a function i set it to null and then I set it to a different array with a smaller amount of elements. Then i call repaint() to refresh the pane but it still doesn't change anything. The JList on my pane still shows the items in the old array. How do i fix this?

    you need to reset the listModel
    search the swing forum for
    listModel DefaultListModel
    and you'll find plenty of working examples

  • How to add rs.getString() into JList

    for add inf rs.getString data into my JList , i m using ---
    list.add(rs.getString(1));
    but its throws an exception: java.lang.IllegalArgumentException: adding container's parent to itself

    Use the DefaultListModel and setting this model of the JList.
    here's a code snippet:
    DefaultListModel model = new DefaultListModel()
    model.addElement(elementToBeAdded);
    jList.setModel(model);

  • A new fire-event?

    I am new in the company and my function is, that the program runs with Java 1.5 (now: java 1.4).. With debug i can isolatethe problem.
    debuglog("clear Model");
    getModel().clear();
    debuglog("now empty Model");Output with Java 1.4
    DEBUG: clear Model
    DEBUG: now empty Model
    Output with Java 1.5
    DEBUG: clear Model
    DEBUG: other debug messages
    DEBUG: clear Model
    DEBUG: now empty Model
    DEBUG: now empty Model
    When i write my own DefaultListModel and delete the line fireIntervalRemoved(this, 0, index1); then it works, but i get other errors by the result of the outage line?
    Anyone an idea? Is there a new event in Java 1.5 that can explain the error?
    thanks in advance
    Mickey
    Message was edited by:
    Mickey1606

    Dear Stefan,
    I face similar issue. Did you manage to get this resolved?
    My problem is precisely when user moves from ESS role - where TeamViewer iView is used on a page to return own personnel number - to the MSS role. Then previous employee selection (own personnel number) is carried through to the MSS screen.
    Any tips are welcome.
    Regards,
    Greg

  • JList not showing up

    I'm overlooking something stupid and just need a different pair of eyes to see what I'm missing.
    I've made a DefaultListModel and populated it.
    I created a JList, passing the Model as a parameter.
    I created a JScrollPane, passing my JList, and setting scroll bar options.
    I added my scroll pane to my frame.
    My frame is visible.
    public class ListTest extends JFrame {
         public ListTest() {
            super("NewClass");
            SwingUtilities.invokeLater(new Runnable() { public void run() { createAndShowGUI();     }});
         public void createAndShowGUI() {
            DefaultListModel modelScript = new DefaultListModel();
            modelScript.addElement("BLAH");
            JList listScript = new JList(modelScript);
            listScript.setSelectionMode(ListSelectionModel.SINGLE_INTERVAL_SELECTION);
            listScript.setLayoutOrientation(JList.VERTICAL);
            JScrollPane panScript= new JScrollPane(listScript, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,
                                                               JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
            add(panScript);
            setVisible(true);
         public static void main(String[] listArgs) {
            ListTest oListTest = new ListTest();
    }Edited by: porpoisepower on Mar 5, 2010 9:20 AM

    well pack() fixed my sample!
    but not my actual code :(
    So here's some of my non-sample code.
    I can make out a bevel on the right side of the frame, as if the ListBox was 0 wide.
        private void createAndShowGUI() {
            JPanel panTree;
            JPanel panScript;
            boolSystemTheme  = true;  // I know this looks stupid.
            if (boolSystemTheme) {
                try {
                    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                catch (Exception e) {
                    System.err.println("Couldn't use system look and feel.");
            txtResults = new JTextArea(8,15);
            frameMain = new JFrame("DynaRhino - Development");
            panTree = new JPanel();
            panTree.setLayout(new BorderLayout());
            panTree.add(initTree(), BorderLayout.CENTER); // Not included code returns a JScrollPane with a tree control
            panTree.add(initToolBar(),BorderLayout.NORTH); // Not included code returns a JToolBar
            panScript = new JPanel();
            panScript.setLayout(new BorderLayout());
            panScript.add(initScriptQueue(),BorderLayout.CENTER);
            frameMain.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frameMain.setSize (450,700);
            frameMain.setLayout(new BorderLayout());
            frameMain.add(initResults(),BorderLayout.SOUTH);
            frameMain.add(panTree,BorderLayout.WEST);
            frameMain.add(panScript,BorderLayout.EAST);
            frameMain.setLocationRelativeTo(null);
            frameMain.setVisible(true);
        private JScrollPane initScriptQueue() {
            DefaultListModel modelScript = new DefaultListModel();
            modelScript.addElement("Ping Client");
            JList listScript = new JList(modelScript);
            listScript.setSelectionMode(ListSelectionModel.SINGLE_INTERVAL_SELECTION);
            listScript.setLayoutOrientation(JList.VERTICAL);
            JScrollPane panScript= new JScrollPane();
            panScript.add(listScript);
            return panScript;
        }Edited by: porpoisepower on Mar 5, 2010 10:35 AM
    added comment regarding boolSystemTheme

  • CastException??? It implments IT!!!

    I tough I had understood inheritance pretty good but...
    What's wrong with this?
    (I've only used classes from the standard API)
        JFileChooser jfc = new JFileChooser();
        jfc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
        int choice = jfc.showDialog(null, "Select");
        if (choice == JFileChooser.APPROVE_OPTION) {
          java.io.File selection = jfc.getSelectedFile();
          DefaultListModel model = (DefaultListModel) sharedList.getModel();
          // returns ClassCastException in the prev line!!!
          model.addElement(selection.getAbsolutePath());
        }The error is in remarks.
    DefaultListModel implements ListModel which is returned by sharedList.getModel()!!!
    ListModel upcast to DefaultListModel is not possible? Why?!?

    ok, up or down, that doesn't matter right now :)
    I can do this:
    ListModel model = sharedList.getModel();
    as you suggest, but that's just an interface.
    DefaultListModel is an implementation which has
    addElemen, method I need.
    DefaultListModel implements ListModel. Why can't I:
    DefaultListModel defaultListModel = (DefaultListModel)
    listModel;
    ???DefaultListModel implementing ListModel means that there is a 'is-a' relationship between DefaultListModel and List model. The nature of this relationship is such that an instance of DefaultListModel is an instance of ListModel, but an instance of ListModel is not necessarily an instance of DefaultListModel. A lion is a cat, but a cat is not necessarily a lion. You need to make sure that the runtime type of the result of getModel() is DefaultListModel, or a subclass of DefaultListModel if you want to cast to DefaultListModel.

  • JList Displaying Text

    I have a database that I'm getting information from, in a JList called nameList I have a list if names from the database, when I click on a name I want the JList named statList to display some information but I can't seem to get it to display even though I did both JList's exactly the same.
    Heres my code: (sorry if you've seen this before)
    import java.awt.*;
    import javax.swing.*;
    import javax.swing.event.*;
    import java.sql.*;
    import java.util.*;
    public class Gifts extends JFrame
         static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
         static final String DATABASE_URL = "jdbc:mysql://localhost/gifts?user=root";
       private JList nameList;
         private JList statList;
         private JButton add;
       private Container container;
         private JPanel nameListPanel, statListPanel, buttonPanel;
         private Connection conn;
         private Statement stat;
         StringBuffer results = new StringBuffer();
         Vector vector2 = new Vector();
       public Gifts()
              super( "Spiritual Gift Database" );
              try
                   Class.forName(JDBC_DRIVER);
                   conn = DriverManager.getConnection(DATABASE_URL);
                   stat = conn.createStatement();
                   ResultSet rs = stat.executeQuery("SELECT FName FROM main");
                   Vector vector1 = new Vector();
                   while(rs.next()) vector1.add(rs.getObject(1));
                   container = getContentPane();
               container.setLayout( new FlowLayout() );
                   nameListPanel = new JPanel();
                   statListPanel = new JPanel();
                   buttonPanel = new JPanel();
               nameList = new JList(vector1);
               nameList.setVisibleRowCount( 9 );
                   nameList.setPrototypeCellValue("XXXXXXXXXXXX");
                   nameList.addListSelectionListener(
                        new ListSelectionListener()
                             public void valueChanged(ListSelectionEvent event)
                                  try
                                       ResultSet resultSet = stat.executeQuery("SELECT a FROM main");
                                       while(resultSet.next()) vector2.add(resultSet.getObject(1));                              
                                  catch(SQLException sqlException)
                                       JOptionPane.showMessageDialog(null,sqlException.getMessage(),
                                       "Database Error", JOptionPane.ERROR_MESSAGE);
                                       System.exit(1);
                   statList = new JList(vector2);
                   add = new JButton("Add Entry");
               nameList.setSelectionMode( ListSelectionModel.SINGLE_SELECTION );
                   statListPanel.add(new JScrollPane(statList));   
               nameListPanel.add( new JScrollPane(nameList));
                   buttonPanel.add(add);
                   container.add(nameListPanel, BorderLayout.EAST);
                   container.add(statListPanel, BorderLayout.WEST);
                   container.add(buttonPanel);
               setSize( 400, 300 );
               setVisible( true );
              }//end try block
              catch(SQLException sqlException)
                   JOptionPane.showMessageDialog(null,sqlException.getMessage(),
                   "Database Error1", JOptionPane.ERROR_MESSAGE);
                   System.exit(1);
              catch (ClassNotFoundException classNotFound)
                   JOptionPane.showMessageDialog(null, classNotFound.getMessage(),
                   "Driver Not Found", JOptionPane.ERROR_MESSAGE);
                   System.exit(1);
         }//end Gifts()
       public static void main( String args[] )
          Gifts application = new Gifts();
          application.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
    }

    [url http://java.sun.com/docs/books/tutorial/uiswing/components/list.html#mutable]How to Use Lists
    A Vector can be used to initially populate a ListModel. After that is you want to make changes to the ListModel you use the methods provided by the JList. You don't update the Vector directly. The above tutorial show how to do this.
    Another option is to create a new DefaultListModel and then use the JList.setModel(...) method to replace the existing ListModel.

  • Problems JList and DefaultListModel

    Hi!
    I've got a problem with the removing of items from a DefaultListModel.
    Assume this:
    public class ImageList extends JList implements DropTargetListener {
    private DefaultListModel dlm = new DefaultListModel();
    public void setListData(ArrayList al) {
    for(...) {
    //do some stuff here
    dlm.addElement(al.get(i));
    this.setModel(dlm);
    }In the main Frameclass are an instance of ImageList and a JButton for deleting a selected item from the list.
    content of the actionPerfomed-method of JButton:
    DefaultListModel model = (DefaultListModel)customContentPane.imageList.getModel();
    int index = customContentPane.imageList.getSelectedIndex();
    if(index!=-1) {
    imageData.remove(index);
    model.remove(index);
    }I'm developing with JBuilder and JDK 1.3.0_02 and there the removing works fine!
    But with JDK 1.4.1-rc-b19 i'm getting an ArrayIndexOutOfBoundsException when i try to delete the last item. The exceptions says index: 0, size: 0!
    But same code works without any problem with 1.3!!
    Does anybody knows a solution?
    Thanks in advance
    Martin

    Its me again!
    After some debugging i found out, the IndexOutOfBoundsException always gives 'Index: -1' back, although an item IS selected!
    And the imageList.getSelectedIndex() returns the true current selected item and not -1.
    Is it a bug in the JList and the DefaultListModel?

Maybe you are looking for