1 2 Previous Next 15 Replies Latest reply on Jun 11, 2008 4:41 PM by 807601

    Table Column to Array for JList

    807601
      I would post my code here.. but I've tried so many different approaches to this that I wouldn't even know where to begin to post.

      Here's what I'm looking for, and I'm sure it's something easy for the awesomely skilled programmers who view this forum

      I need to take a column from a database and turn it into an array to be used in a JList.

      I managed to create a ArrayList but I can't convert an array list to an array to be used in the JList. (I've tried numerous times and it just won't work)

      I imagine doing the database pull the proper way (into an array to begin with) would be the best approach... but I'm lost on that one as well. (I've been working on this project non stop since friday night)

      one last question... Isn't there a way to make sure at least one item on a JList is checked at all times??? Am I totally missing the boat with the method for this? Combo Boxes have it, I wouldn't see why JList wouldn't ( I need it to prevent a nullpointer)

      Thanks Again! (and thanks to the folks who insisted I switch from a flat file to a database.. it took me the weekend to figure out the coding, but I'm glad I took the time to figure it out)

      String[] test = (String[]) dl.retrieveMovieNames().toArray(

      new String[dl.retrieveMovieNames().size()]);



      Exception in thread "main" java.lang.ArrayStoreException

      at java.lang.System.arraycopy(Native Method)

      at java.util.ArrayList.toArray(ArrayList.java:306)

      at UserInterface.buildQueryPanel(UserInterface.java:204)

      at UserInterface.<init>(UserInterface.java:63)

      at UserInterface.main(UserInterface.java:581)
        • 1. Re: Table Column to Array for JList
          807601
          Going to need a little more info. Or, more of the code that you have. What is dl? What is retrieveMovieNames()? Post some more code, so we know where you are currently.
          • 2. Re: Table Column to Array for JList
            807601
            hopefully I can give you what you need. Please don't laugh

            Below is the method in my public class DataLayer
            (Basically datalayer holds my deletes retrieves and modifies)
             /**
                 * @return movietitle titles of the movies in database
                 */
                public ArrayList<MovieTitleRecord> retrieveMovieTitles() {
            
                 // declarations
                 ArrayList<MovieTitleRecord> movieTitles = new ArrayList<MovieTitleRecord>();
                 Connection con = null;
                 Statement statement = null;
            
                 // use a try block for opening the file, reading the line by line,
                 // parsing each line,
                 // and filling the attributes into objects. For each object,
                 // add it to the array.
                 try {
            
                     Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
                     con = DriverManager.getConnection("jdbc:odbc:Movies");
            
                     statement = con.createStatement();
            
                     ResultSet rs = statement
                          .executeQuery("SELECT MOVIETITLE FROM MOVIES");
            
                     while (rs.next()) {
            
                      // create a object
                      MovieTitleRecord movieTitle = new MovieTitleRecord();
            
                      // set the attributes of the object
                      movieTitle.setMovieTitle(rs.getString(1));
            
                      // add it to the arraylist
                      movieTitles.add(movieTitle);
            
                      System.out.println(rs.getString(1));
                     }
            
                 } catch (Exception e) {
                     System.err.print(e);
                 } finally {
                     // if the filereader or the buffered reader are open, YOU MUST CLOSE
                     // THEM
                     try {
                      if (statement != null) {
                          statement.close();
                      }
            
                      if (con != null) {
                          con.close();
                      }
                     } catch (Exception e) {
                      // do nothing
                     }
                 }
            
                 // return the array list of movie records
                 return movieTitles;
            
                }
            Here is the code I'm using to try and convert the arrayList to an array. (not working) The array is being used in my JList
            This is also the place where I need to make sure there is something selected at all times... otherwise if a user does not select an item in the list and hits return record you end up with a null pointer exception. With radio buttons I can easily do it.. with JList I'm not sure...

            Looking through the methods i could probably add an if statement to the action listener that will only allow the action listener to take place if the isSelectionEmpty is false (I need to try that one)
            DataLayer dl = new DataLayer();
            
                 String[] array = dl.retrieveMovieTitles().toArray(
                      new String[dl.retrieveMovieTitles().size()]);
            
                 // create new JList for movie data
                 dqMovieList = new JList(array);
            
                 // assure only one selected
                 dqMovieList
                      .setSelectionMode(DefaultListSelectionModel.SINGLE_SELECTION);
            • 3. Re: Table Column to Array for JList
              807601
              Your retrieveMovieTitles() method returns an array of type MovieTitleRecord, but when you call it you treat it like a String array:
              String[] array = dl.retrieveMovieTitles().toArray(
                        new String[dl.retrieveMovieTitles().size()]);
              • 4. Re: Table Column to Array for JList
                807601
                but wouldnt the .toArray convert it to a String Array? Or am I once again making stuff up ><


                String[] array = dl.retrieveMovieTitles().toArray(
                          new String[dl.retrieveMovieTitles().size()]);
                • 5. Re: Table Column to Array for JList
                  807601
                  How would it convert it to a String array if it's not filled with Strings? Read the API for toArray():
                  [http://java.sun.com/javase/6/docs/api/java/util/ArrayList.html#toArray()]

                  Notice this part:
                  Throws:
                  ArrayStoreException - if the runtime type of the specified array is not a supertype of the runtime type of every element in this list
                  So unless String is a supertype of MovieTitleRecord, you can't convert your ArrayList into a String array.
                  • 6. Re: Table Column to Array for JList
                    807601
                    I tried to create a method that would return an actual string array from the database, but I think I've made more of a mess because this doesn't work either (but then again, I'm trying to piece mail it from multiple articles)

                        public String[] createArray() {
                    
                         Connection con = null;
                         Statement statement = null;
                    
                         try {
                    
                             Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
                             con = DriverManager.getConnection("jdbc:odbc:Movies");
                    
                             statement = con.createStatement();
                    
                             ResultSet rs = statement
                                  .executeQuery("SELECT MOVIETITLE FROM MOVIES");
                    
                             while (rs.next()) {
                              java.sql.Array t = rs.getArray("MOVIETITLE");
                              String[] mtitles = (String[]) t.getArray();
                              for (int i = 0; i < mtitles.length; i++)
                                  ;
                             }
                         } catch (Exception e) {
                             System.err.print(e);
                         } finally {
                             // if the filereader or the buffered reader are open, YOU
                             // MUST CLOSE
                             // THEM
                             try {
                              if (statement != null) {
                                  statement.close();
                              }
                    
                              if (con != null) {
                                  con.close();
                              }
                             } catch (Exception e) {
                              // do nothing
                             }
                         }
                         
                    
                        }
                    • 7. Re: Table Column to Array for JList
                      807601
                      java.sql.Array t = rs.getArray("MOVIETITLE");
                      Whoa! You are getting off track. I suggest you keep your code as simple as possible, until you learn more about Java and programming. So:
                      Vector<String> names = new Vector<String>();
                      ...
                      while (rs.next()) {
                          names.add(rs.getString(1));
                      }
                      ...
                      Jlist list = new JList(names);
                      • 8. Re: Table Column to Array for JList
                        807601
                        words cannot describe the feelings that are rushing through me right now. I'm almost at 50 hours of work into this final project and that tiny code snipet made it all the worth while. My project finally works forwards and backwards (minus the exception handling that I need to figure out how to do.. ie if I try to enter a new record with @#$()@#$ the database kicks back an error.. but I'm hoping this is something I can easily figure out)

                        My summer reading is Java Head Start so that I will hopefully understand inside and out all the concepts and methods.

                        Again, thank you, and everyone else who's assisted with this.
                        • 9. Re: Table Column to Array for JList
                          807601
                          Woo-hoo! Good luck and read that book. It's a good one.
                          • 10. Re: Table Column to Array for JList
                            807601
                            ok one last question I hope :)

                            Below is the code that is working. The program has the ability to add/delete/modify records in the database. If I query the records the JList/Vector does not refresh. What am I missing?

                            This is what I'm using to call the code

                            Vector<String> queryList = dlQuery.getVector();



                             public Vector<String> getVector() {
                            
                                 Vector<String> titles = new Vector<String>();
                                 
                            
                                 Connection con = null;
                                 Statement statement = null;
                            
                                 try {
                            
                                     Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
                                     con = DriverManager.getConnection("jdbc:odbc:Movies");
                            
                                     statement = con.createStatement();
                            
                                     ResultSet rs = statement
                                          .executeQuery("SELECT MOVIETITLE FROM MOVIES");
                            
                                     while (rs.next()) {
                                      titles.add(rs.getString(1));
                                     }
                                 } catch (Exception e) {
                                     System.err.print(e);
                                 } finally {
                                     // if the filereader or the buffered reader are open, YOU
                                     // MUST CLOSE
                                     // THEM
                                     try {
                                      if (statement != null) {
                                          statement.close();
                                      }
                            
                                      if (con != null) {
                                          con.close();
                                      }
                                     } catch (Exception e) {
                                      // do nothing
                                     }
                                 }
                            
                                 return titles;
                                }
                            • 11. Re: Table Column to Array for JList
                              807601
                              !. Is the database being updated? Have you verified this?
                              2. You say your GUI is not updating, but what about the data this method is returning. Print it to System.out. There are three possibilities:
                              a- the database isn't being updated after all.
                              b. this method doesn't return updated data (odd if a is not the case) or
                              c. You aren't updating your GUI.

                              Narrow down the problem.
                              • 12. Re: Table Column to Array for JList
                                807601
                                The data is being updated because I can close out the program and then reopen it and when I do a query the new or adjusted data is there.

                                I have 2 methods for looking at the data.

                                1. The vector that pulls in all the titles for my JList(s) that I use on 3 different screens for retrieving records for modifications/deletes/viewing.

                                If I add a new record the new record does not show on the JList(which displays the vector) unless I shutdown the program and restart. (The same for deleting, the title still shows on the JList because it's not refreshing)

                                If I retrieve a record and change a a datafield I can actually see the change on my display full record screen.

                                This screen's retrieval is done via a Select * from table where field = selection. The output is basically a textarea where I dump a string "The Title is :" + rs.String(1) + "The Blah blah is:" + rs.String(2) ...

                                I tried doign a vectorName.Clear() thinking that this is what it took to refresh, but that didn't appear to work.
                                • 13. Re: Table Column to Array for JList
                                  807601
                                  I can only guess what's going wrong. Perhaps you are not actually updating your GUI layer, or perhaps you are not really calling the method to reselect the data. You need to debug your code to see where it is failing.
                                  • 14. Re: Table Column to Array for JList
                                    807601
                                    The young padawan is learning :-)

                                    I created this method that will create a new vector and revalidate the panels.
                                    I added the method to the action events that call the display panels.
                                    Success!

                                    totally out of scope... but if I could figure a way to tap in to the IMDB when I add records to my database, I'd have a nice little toy I could pass on as freeware. and here I got all excited with Hello World ;-)

                                    Thanks again!
                                    1 2 Previous Next