Filling a listbox with the results of a query — fast and dirty

Ok in this snippet of code using NB 6.0.1 I have create a swing List box and I want to fill it from the results of a query. The List box can actually go ahead and list the results of the query by using the  toArray() function. But I wanted to clean up the data first and get rid of the square brackets.

In this example I wanted to list 2 fields, the record id followed by a comma then the problem in the knowledgebase table.

  // Connect  	EntityManagerFactory emf = javax.persistence.Persistence.createEntityManagerFactory("PHJSupport-app-clientPU");
        EntityManager em = emf.createEntityManager();
        try {
        Query q = em.createNativeQuery("select id,problem from Knowledgebase");
        Object[] results=q.getResultList().toArray();
        int icount;
        // now clean them up
        for (icount=0;icount<results.length;++icount) {
            results[icount]=results[icount].toString().replace("[", "");
            results[icount]=results[icount].toString().replace("]", "");
        } catch (Exception e) {
            System.out.println("Error " + e.getMessage());

Note that I could replace the code

            results[icount]=results[icount].toString().replace("[", "");
            results[icount]=results[icount].toString().replace("]", "");


           results[icount]=results[icount].toString().replace("[", "").replace("]","");

Remember loops are costly and so we want to make things as efficient as possible.


About Paul C

I am a Senior Java programmer/Web Technologies, Play in a band called Mandolin Monday, I have a cat and I live on a boat.

Posted on February 26, 2008, in Uncategorized. Bookmark the permalink. Leave a comment.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: