Link to home
Start Free TrialLog in
Avatar of Silversoft
Silversoft

asked on

RMI - filling up a JComboBox

the while(result.next()) loop runs 14-15 times (as many records i have in the DB) but doesnt fill the JComboBox[client-side]. All compiles fine, so it sounds like something stupid. got any clues?
Avatar of girionis
girionis
Flag of Greece image

Do you get any error messages? Can you post the relevant part of the code?
Avatar of nesnemis
nesnemis

Hi Silversoft,

what's your code for filling the combo?

nesnemis
Avatar of Silversoft

ASKER

gui_crafter:

class gui_crafter implements ActionListener, ItemListener
{
        //jcb is the name of my JComboBox

         jcb.addItemListener(this);
               
               
      try
      {

            INTERFACE I = (INTERFACE)Naming.lookup("localhost");
                  
            I.loadChoice(jcb);
                                    
      }catch(Exception ex6){System.out.println("ERROR");}

      public void itemStateChanged(ItemEvent ie)
      {}

}


thats my client side:

my server-side:

public void loadChoice(JComboBox jcb) throws RemoteException
{
      try
      {
            Statement sq=connection.createStatement();
                  
            ResultSet result=sq.executeQuery(
                        "SELECT crafter_sid "+      
                        " FROM crafter");
                  
            while(result.next())
            {
            jcb.addItem(""+result.getString(1));
                        
            System.out.println("added entry"); //this runs 15 times (or however many entries i got in the DB
            }
            sq.close();
            }catch(Exception ex6){System.out.println("ERROR LOADING");}      
      }


Can you show us the code that adds the items to the combo?
Do you add to the combo box *model*?
I do not see any GUI interaction in the client side. Are you trying to put items on the server or on the client? You should fill up the combo box on the client side. Normally you would read the data from the database on the server, you will fill up a collection object (should be serializable), you will return it to the client and then you will use it on the client to fill up the JComboBox.
Hmm.. Ok ignore my comment above. It seems that you are adding them but maybe you do not show/update the GUI. Show us the relevant code.
I would try:

       I.loadChoice((DefaultComboBoxModel)jcb.getModel());

and

        public void loadChoice(DefaultComboBoxModel model) throws RemoteException {

                 ...
                 while(result.next()) {
                    model.addElement(""+result.getString(1));

        }

complete GUI:

class gui_crafter implements ActionListener, ItemListener
{

        public JFrame frame;
        public Container con;
        public JScrollPane scrollPane;
        public Panel inputPanel, outputPanel, buttonPanel;
        public JLabel lblCrafterName, lblProductNo, lblCrafterNo, lblProductName;
        public JTextField txtCrafterName, txtProductNo, txtCrafterNo;
        public JTextArea ta;
        public Button btnshow, exitButton, btndel, btnadd, updateButton;
        public Statement statement;
        public Connection connection;      
        public JComboBox jcb;
        
        public gui_crafter()
        {            
          frame = new JFrame("Crafter Form");
          con = frame.getContentPane();
          con.setLayout(new BorderLayout() );
          frame.setSize(400,300);
      
          lblCrafterName = new JLabel("Crafter Name: ");
          lblProductNo = new JLabel("Product Number: ");
          lblCrafterNo = new JLabel("Crafter Number: ");
          lblProductName = new JLabel("");
          txtCrafterName = new JTextField(10);
          txtProductNo = new JTextField(5);
          txtCrafterNo = new JTextField(5);
          jcb = new JComboBox();
          
          inputPanel = new Panel();
          inputPanel.setLayout(new GridLayout(10,1) );
          inputPanel.add(jcb);
          inputPanel.add(lblCrafterNo);
          inputPanel.add(txtCrafterNo);
          inputPanel.add(lblCrafterName);
          inputPanel.add(txtCrafterName);
          inputPanel.add(lblProductNo);
          inputPanel.add(txtProductNo);
          inputPanel.add(lblProductName);
      
          ta=new JTextArea(10,20);
          scrollPane = new JScrollPane(ta);
          outputPanel = new Panel();    
          outputPanel.add(scrollPane);
      
          btnshow = new Button("Show All");
          exitButton = new Button("Main Menu");
          btndel = new Button("Delete");
          btnadd = new Button("Add");
          updateButton = new Button("Update");
          buttonPanel = new Panel();
          buttonPanel.add(btnadd);
          buttonPanel.add(btnshow);
          buttonPanel.add(updateButton);
          buttonPanel.add(btndel);
          buttonPanel.add(exitButton);
          con.add(inputPanel,"West");
          con.add(outputPanel,"Center");
          con.add(buttonPanel,"South");
               btnadd.addActionListener(this);
               btndel.addActionListener(this);      
               jcb.addItemListener(this);
                 System.out.println("jcb.addItemListener(this);");
              try
            {
                  INTERFACE I = (INTERFACE)Naming.lookup("localhost");
                  System.out.println("INTERFACE I = (INTERFACE)Naming.lookup('localhost');");                  I.loadChoice(jcb);
                  System.out.println("I.loadChoice(jcb);");            
            }catch(Exception ex6){System.out.println("ERROR ON INTERFACE NAMING");}            
          frame.setVisible(true);
        }
        public void itemStateChanged(ItemEvent ie)
      {
            System.out.println("public void itemStateChanged(ItemEvent ie)");      
      }
      public void actionPerformed(ActionEvent e)
                {
            if(e.getSource() == btnadd)
            {
                  String n = txtCrafterNo.getText();
                  int num = Integer.parseInt(n);
                  String name = txtCrafterName.getText();
                  System.out.println(num +"      " + name);
                  try
                  {
                        INTERFACE I = (INTERFACE)Naming.lookup("localhost");
                        I.add_crafter(num, name);                        
                  }catch(Exception ex6){}
                  ta.setText("");
                  ta.setText("CRAFTER ADDED TO DATABASE");
            }
            if(e.getSource() == btndel)
            {
                  String n = txtCrafterNo.getText();
                  int num = Integer.parseInt(n);
                  String name = txtCrafterName.getText();
                  System.out.println(num +"      " + name);
                  try
                  {
                        INTERFACE I = (INTERFACE)Naming.lookup("localhost");
                        I.del_crafter(num, name);
                  }catch(Exception ex6){}            
                  ta.setText("");
                  ta.setText("CRAFTER DELETED FROM DATABASE");
            }
            if(e.getSource() == btnshow)
            {
                  System.out.println("show button");
                  try
                  {
                        INTERFACE I = (INTERFACE)Naming.lookup("localhost");
                        I.showCrafter(ta);
                  }catch(Exception ex6){System.out.println("ERROR SHOWING CRAFTER ON TEXTAREA");}
            }
      }

}
thanks zzynx, i'll try that now
I would have:

public void loadChoice(JComboBox jcb) throws RemoteException

as

public ArrayList loadChoice() throws RemoteException

then fill up the combobox from the returned arraylist (in the client)
....sorry man i dont understand...

could you give me an example?
class working extends java.rmi.server.UnicastRemoteObject implements INTERFACE
{
        Statement statement;
        Connection connection;

        public working() throws RemoteException
        {
             try      
            {
                  Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
              String dataSourceName = "javadb1";
              String dbURL = "jdbc:odbc:" + dataSourceName;
              connection = DriverManager.getConnection(dbURL, "","");
              statement = connection.createStatement();
                   
            }catch(Exception ex1){System.out.println("could not connect to the DB");}
      }
      public void add_crafter(int num, String name) throws RemoteException
      {
            try
            {
                  Statement s = connection.createStatement();
                  int ok = s.executeUpdate(
                  "INSERT INTO crafter"+
                  "(crafter_sid, crafter_name)"+
                  " VALUES" +
                  "('"+num+"','"+name+"')");
            
                   s.close();
                                     
            }catch(Exception ex2){JOptionPane.showMessageDialog(null, "Crafter-ID already exists." + "\n" + "Please select another Crafter-ID");}

      }
      public void del_crafter(int num,String name) throws RemoteException
      {
            try
            {
                  Statement s = connection.createStatement();
                  int ok = s.executeUpdate(
                        "DELETE FROM crafter" +
                      " WHERE crafter_sid = "+num+"" +
                      " AND name = '"+name+"'");
                  
                  s.close();
            }
            catch(Exception ex4){JOptionPane.showMessageDialog(null, "Crafter doesn't Exist." + "\n" + "Please enter the crafter-ID AND Name");}
            
      }
      public void loadChoice(JComboBox jcb) throws RemoteException
      {
            System.out.println("public void loadChoice(JComboBox jcb)");
            try
            {
                  System.out.println("try {");
                  Statement sq=connection.createStatement();
                  System.out.println("Statement sq=connection.createStatement();");
                  ResultSet result=sq.executeQuery(
                        "SELECT crafter_sid "+      
                        " FROM crafter");
                  System.out.println("ResultSet result=sq.executeQuery(SELECT crafter_sid FROM crafter);");
                  while(result.next())
                  {
                        jcb.addItem(""+result.getString(1));
                        System.out.println("jcb.addItem(+result.getString(1));");
                  }
                  sq.close();
                  System.out.println("sq.close();");
            }catch(Exception ex6){System.out.println("ERROR ON LOADING");}
      }
      public void showCrafter(JTextArea ta) throws RemoteException
      {
            try
            {
                  Statement sq=connection.createStatement();
                  ResultSet result=sq.executeQuery(
                        "SELECT crafter_sid, crafter_name"+      
                        " FROM crafter");
                  ta.setText("");
                  while(result.next())
                  {
                        ta.append(""+result.getString(1)+
                              " \t"+result.getString(2)+"\n");
                              
                        System.out.println("ta.append(""+result.getString(1)+ result.getString(2)+)");
                  }
                  sq.close();      
            }catch(SQLException e){e.printStackTrace();}      
      }
}
Put everything into a collection object, lets say a vector and then return it, so the method should be:

public Vector loadChoice(JComboBox jcb) throws RemoteException

and you should have somethign like:

while (result.next())
{
    vector.addElement(result.getString(1));
}

...

return vector;

and in your client you do

 try
     {

          INTERFACE I = (INTERFACE)Naming.lookup("localhost");
          Vector v = I.loadChoice();
          for (int i=0; i<v.size(); i++)
          {
             jcb.addItem(v.elementAt(i));
          }
                             
     }catch(Exception ex6){System.out.println("ERROR");}




>> could you give me an example?

I think he means:

        public ArrayList loadChoice() throws RemoteException {

                 ...
                 List results = new ArrayList();
                 while(result.next()) {
                    results.add(""+result.getString(1));

                 return results;
        }

and

     List items = I.loadChoice();
     Iterator it = items.iterator();
     while (it.hasNext())
        jcb.addItem( (String)it.next() );

> I think he means:

Yup :-)

Doing it that way has the advantage that say someone wants you to make your application into a web app...  You would then need to put your options into an HTML SELECT rather than a combobox...

If it just returns an arraylist, this change is much easier (well, not easier, but cleaner -- you won't need to either add a new method, or create a jcombobox just to transfer the data)...

Basically, it keeps your "View" out of your "Controller" a bit better ;-)
Also, I am not 100% convinced that you can alter a method parameter over RMI, and recieve back the altered object...

ie:

    public void someMethod( ArrayList a ) throws RemoteException
    {
        a.add( "Hi" ) ;
    }
         

then:

    INTERFACE I = (INTERFACE)Naming.lookup("localhost");
    ArrayList a = new ArrayList() ;
    I.loadChoice( a );

I am not 100% sure that "a" will contain any data after this call...

It may do though...  But I have always returned data explicitly...

Tim
i get the data integrity bit. but my reason is i havnt had much experience with ArrayLists.

if you could give me the code to 'copy/paste' it would be great.
>> Also, I am not 100% convinced that you can alter a method parameter over RMI, and recieve back the altered object...

We will know if this try is successful :
>> thanks zzynx, i'll try that now

Is it, Silversoft?
>> if you could give me the code to 'copy/paste' it would be great.
I did
if it makes any difference, im not having much luck 'append'ing data to the JTextArea either... (from the server-side)
I repeat:

        public ArrayList loadChoice() throws RemoteException {

                 ...
                 List results = new ArrayList();
                 while(result.next()) {
                    results.add(""+result.getString(1));

                 return results;
        }

and

     List items = I.loadChoice();
     Iterator it = items.iterator();
     while (it.hasNext())
        jcb.addItem( (String)it.next() );
>> im not having much luck 'append'ing data to the JTextArea either
Well, first make that combo box work, then apply the same "technique" to the textarea
> if it makes any difference, im not having much luck 'append'ing data
> to the JTextArea either... (from the server-side)

It might be that database does not return anything. Are you sure it returns *something*?
> >> Also, I am not 100% convinced that you can alter a method parameter over RMI, and recieve back the altered object...
> We will know if this try is successful :

Hehehe, true...  (though I'm 90% sure I'm right) ;-)
i would rate that be the first asumption:

in the code:

while(result.next())
{
      jcb.addItem(""+result.getString(1));
      System.out.println("item added");
}

"item added" is printed 15 times (exactly the amount in the DB)

String s = result.getString(1); //this gives me an error
java:92: reference to List is ambiguous, both class java.util.List in java.util and class java.awt.List in java.awt match
                  List items = I.loadChoice();
whats this?
              java.util.List items = I.loadChoice();

AWT has a List component in it...
>> reference to List is ambiguous
The class List exists in java.util and in java.awt

You have to make clear which one you want to use by:

import java.util.List
or
import java.awt.List
as well as java.util.awt ..?
Remark the above can be combined with

import java.util.*;
import java.awt.*;
cool!!
>> as well as java.util.awt ..?
???
See my previous comments
>>You have to make clear which one you want to use by:
>>import java.util.List
>>or
>>import java.awt.List

Or indeed like Tim said by specifying it whereever it occurs:

      java.util.List items =  ...;


I prefer the first because that way I can just write List instead of java.util.List
im compiling and running the prog using the Arraylist now.....
Tim's way is necessary if you need to use both awt.List and util.List.
here is the code::: it gives me an error::::

java:143: incompatible types
found   : java.util.List
required: java.util.ArrayList
           return results;
                   

public ArrayList loadChoice() throws RemoteException
      {
          java.util.List results = new ArrayList();
       
            Statement sq=connection.createStatement();
                  
            ResultSet result=sq.executeQuery(
                        "SELECT crafter_sid, crafter_name"+      
                        " FROM crafter");
       
        while(result.next())
        {
                 results.add(""+result.getString(1));
        }
        sq.close();
                return results;
   }
>> Tim's way is necessary if you need to use both awt.List and util.List.
Affirmative
> java.util.List results = new ArrayList();

change it to

ArrayList results = new ArrayList();
Make that

    public java.util.List loadChoice() throws RemoteException                    // change ArrayList to List
> java:143: incompatible types
> found   : java.util.List
> required: java.util.ArrayList
>            return results;

... although this error seems weird since an ArrayList is essentially a List.
>>change it to
>>ArrayList results = new ArrayList();
That's not the problem, girionis
yaeh, im using both .awt & .util in the class.
Silversoft, just define your loadChoice as returning a java.util.List instead of an ArrayList
> >>change it to
> >>ArrayList results = new ArrayList();
> That's not the problem, girionis

I think this is the problem. It should return an ArrayList but it returns a List instead.
> I think this is the problem. It should return an ArrayList but it
> returns a List instead.

To add more, it is like expecting to return a Vector but you return an Object (which is not necessarily a Vector).
>> yaeh, im using both .awt & .util in the class
Sure that is really needed?
If it is, you'll have to prefix each occurrence of "List" with "java.util" or "java.awt"
>> It should return an ArrayList but it returns a List instead
That's why I advice to change the return type to java.util.List (interface) instead of the class (ArrayList) implementing the interface
sloooooow doooowwwn everybody ;)

We're asking and answering questions (and then asking 3 more) before Silversoft has a chance to respond ;)
>> That's why I advice to change the return type to java.util.List
...and then you don't need to change this

          java.util.List items = I.loadChoice();
> >> It should return an ArrayList but it returns a List instead
> That's why I advice to change the return type to java.util.List
> (interface) instead of the class (ArrayList) implementing the interface

It is easier to just change the declaration of the variable though. If you change the signature of the method, you will also need to change the RMI interfaces.
whats wrong now?

java:152: missing return statement
    }



public ArrayList loadChoice() throws RemoteException
      {
            try
            {
                ArrayList results = new ArrayList();
       
                  Statement sq = connection.createStatement();
                  
                  ResultSet result = sq.executeQuery(
                              "SELECT crafter_sid, crafter_name"+      
                              " FROM crafter");
       
       
                    while(result.next())
                    {
                     results.add(""+result.getString(1));
              }
       
                  sq.close();

              return results;

          }catch(Exception ex7){}

    } //the error points to here
> >> That's why I advice to change the return type to java.util.List
> ...and then you don't need to change this

>           java.util.List items = I.loadChoice();

I am not sure if you will need to change this at all. It should work as it is.
>>sloooooow doooowwwn everybody ;)
;°)


Well, to conclude:

Q:
>> here is the code::: it gives me an error::::

A:
>>Make that
>>
>>    public java.util.List loadChoice() throws RemoteException                    // change ArrayList to List
public ArrayList loadChoice() throws RemoteException
     {
          try
          {
              ArrayList results = new ArrayList();
       
               Statement sq = connection.createStatement();
               
               ResultSet result = sq.executeQuery(
                         "SELECT crafter_sid, crafter_name"+    
                         " FROM crafter");
       
       
                  while(result.next())
                  {
                   results.add(""+result.getString(1));
             }
       
               sq.close();

             return results;

         }catch(Exception ex7){}
         return null ;
    } //the error points to here
>  return results;

Put it outside the try... catch block.
And put a return null in the catch... block.
>> whats wrong now?
Each "path" of your function needs to return a List:

    }catch(Exception ex7){
        return new ArrayList();
    }
you need to return something if an exception is caught...

(although I'd probably do this):

 public ArrayList loadChoice() throws RemoteException
     {
          try
          {
              ArrayList results = new ArrayList();
       
               Statement sq = connection.createStatement();
               
               ResultSet result = sq.executeQuery(
                         "SELECT crafter_sid, crafter_name"+    
                         " FROM crafter");
       
       
                  while(result.next())
                  {
                   results.add(""+result.getString(1));
             }
       
               sq.close();

             return results;

         }catch(Exception ex7)
         {
             thrown new RemoteException( "Exception from loadChoice()", ex7 ) ;
         }
    } //the error points to here

so that it rethrows the exception back to your client code :-)
            thrown new RemoteException( "Exception from loadChoice()", ex7 ) ;

should be:

             throw new RemoteException( "Exception from loadChoice()", ex7 ) ;
>> Put it outside the try... catch block.
Why is that? Not needed.

>>And put a return null in the catch... block.
That's it. (or return new ArrayList(); )
the program places record 2 in the program, but not any of the others..? any idea why?
> the program places record 2 in the program, but not any of the others..?
> any idea why?

Are there any more?
Could you add some extra output to be sure that 15 different strings are really added?

replace
>> results.add(""+result.getString(1));

String item = result.getString(1);
results.add(item);
System.out.println("Item added: " +item);
i will try troubleshoot man, but my worry also comes in when viewing all 'crafters' on the JTextArea.

will i do the same (ie ArrayList)?
>> will i do the same (ie ArrayList)?
I would
> i will try troubleshoot man, but my worry also comes in when viewing
> all 'crafters' on the JTextArea.

> will i do the same (ie ArrayList)?

The idea behind debugging should be the same, yes.
i added the maual-item adding code and i get these 2 errors:

java:100: cannot find symbol
symbol  : variable result
location: class gui_crafter
                    String item = result.getString(1);
 

                                   ^
java:101: cannot find symbol
symbol  : variable results
location: class gui_crafter
                        results.add(item);
Post the code fragments. It seems that you have declared them outside the try... catch block.
Can you post your code as it is now?  It looks like you've pasted server code into the client...
In your loadChoice

results was
>>    java.util.List results
while result was
>>    ResultSet result=sq.executeQuery(...);

If you copy/pasted that code to another function you need to define what the variable results/result are
this is on client-side:

            try
            {

                  INTERFACE I = (INTERFACE)Naming.lookup("localhost");
                  
                  System.out.println("INTERFACE I = (INTERFACE)Naming.lookup('localhost');");            
                  
                  ArrayList items = I.loadChoice();
                  
                 Iterator it = items.iterator();
                 
                 while (it.hasNext())
                 {
                    //jcb.addItem((String)it.next());
                    
                    String item = result.getString(1);
                        results.add(item);
                        System.out.println("Item added: " +item);

              }
              
            }catch(Exception ex6){System.out.println("ERROR ON INTERFACE NAMING");}
Make that

              while (it.hasNext()) {
                 jcb.addItem((String)it.next());
              }

             ArrayList items = I.loadChoice();     // Get the items via RMI
              Iterator it = items.iterator();          
              while (it.hasNext()) {                      // Iterate over the items and add them one by one to the combo
                 jcb.addItem((String)it.next());
              }
               
Sorry, forgot the debug code:

             ArrayList items = I.loadChoice();     // Get the items via RMI
              Iterator it = items.iterator();          
              while (it.hasNext()) {                      // Iterate over the items and add them one by one to the combo
                 String item = (String)it.next();
                 jcb.addItem(item);
                 System.out.println("Item added: " +item);
              }
Btw, my original comment about adding some debugging code was meant for the server-side:

>>Could you add some extra output to be sure that 15 different strings are really added?

>>replace
>>>> results.add(""+result.getString(1));
by
>>String item = result.getString(1);
>>results.add(item);
>>System.out.println("Item added: " +item);

;°)
while (it.hasNext()) {
                 jcb.addItem((String)it.next());
//is it possible to write
System.out.println((String)it.next());

              }

No!
Each it.next() "takes" the next object of the iterator
> //is it possible to write
> System.out.println((String)it.next());

This will go to the next item, therefore it will be liek jumping two at a time, since you already have a it.next() in the line above.
So, you would add the first item to the combo and log/output the second.
Moreover, to be safe, each

      it.next()

should be called after a check that there really still IS a next item (that's what hasNext() does)
yeah, i get the function. its just when i get

String item = result.getString(1);
                    results.add(item);
                    System.out.println("Item added: " +item);

it gives me an error:

java:100: cannot find symbol
symbol  : variable result
location: class gui_crafter
                  String item = result.getString(1);
 

                                   ^
java:101: cannot find symbol
symbol  : variable results
location: class gui_crafter
                    results.add(item);
Post the relevant part of code.
   public List loadChoice() throws RemoteException
    {
        Statement sq = null ;
        ResultSet result = null ;
        List ret = new ArrayList() ;
        try
        {
            sq = connection.createStatement();
            result = sq.executeQuery( "SELECT crafter_sid, crafter_name FROM crafter" ) ;
            while( result.next() )
            {
                ret.add( result.getString( 1 ) );
            }
        }
        catch( SQLException ex )
        {
            throw new RemoteException( "Exception from loadChoice()", ex7 ) ;
        }
        finally
        {
            try { if( result != null ) result.close() ; } catch( SQLException ex ) {}
            try { if( sq != null ) sq.close() ; } catch( SQLException ex ) {}
        }
        return ret;
    }

should be your server code...
Pheewww ;°)

1) On the client side (gui_crafter) you can add this debugging code:

             ArrayList items = I.loadChoice();     // Get the items via RMI
              Iterator it = items.iterator();          
              while (it.hasNext()) {                      // Iterate over the items and add them one by one to the combo
                 String item = (String)it.next();
                 jcb.addItem(item);
                 System.out.println("Item added: " +item);
              }

2) on the server side (loadChoice) you could replace this:

         results.add(""+result.getString(1));
by

         String item = result.getString(1);
         results.add(item);
         System.out.println("Item added: " +item);

Don't mix both up!!!

And as zzynx said;

             List items = I.loadChoice();     // Get the items via RMI
             Iterator it = items.iterator();          
             while (it.hasNext()) {                      // Iterate over the items and add them one by one to the combo
                 String item = (String)it.next();
                 jcb.addItem(item);
                 System.out.println("Item added: " +item);
              }

should be your client code...
haha cool man, thanks for the help as well!

              System.out.println("stage 1");
                    while(result.next())
                    {
                     results.add(""+result.getString(1));
                     String str = result.getString(1);
                     Systtem.out.println(str);
              }
              System.out.println("stage 2");

if i run this code it only gets to "stage 1"

but if i change the code to

         //System.out.println("stage 1");
              while(result.next())
              {
                     results.add(""+result.getString(1));
                     //String str = result.getString(1);
                     Systtem.out.println(result.next());
              }
              //System.out.println("stage 2");

i get:
true
true
true
true
true
true
true
true
true
true
            System.out.println("stage 1");
                  while(result.next())
                  {
                   String str = result.getString(1);
                   results.add( str ) ;
                   System.out.println(str);
                  }
             System.out.println("stage 2");
Same as with the it.next() don't call result.getString(1) twice
...but save it in a String variable as Tim showed.
it gives everyone of the fields in the DB perfect as the DB lists it.

but doent fill the ComboBox!!
Try to upgrade the GUI or something. Or try zzynx's original suggestion, add then items to the model.
>> it gives everyone of the fields
Where? In the server side-debug code? Or in the client-side debug code? Or in both?
Can you post the output(s) you get?

>> but doent fill the ComboBox!!
Didn't you tell before it filled up with one item?

sorry man.

>> it gives everyone of the fields
all System.output on the server side:

1234
222
423
253
235
523452
234
5235
52345
67
346784
546
etc.
etc.
etc.


>> but doent fill the ComboBox!!
yeah the '222' is filled in, but none of the rest
Use a combobox model...

             DefaultComboBoxModel model = new DefaultComboBoxModel() ;
             List items = I.loadChoice();     // Get the items via RMI
             for( int i = 0 ; i < items.size() ; i++ )
                 model.addElement( items.get( i ) ) ;
             jcb.setModel( model ) ;
What is the output of thsi on the client:

List items = I.loadChoice();     // Get the items via RMI
System.out.println("no of elements: " + items.size());
>> all System.output on the server side:
Any debugging output on the client side?

>>yeah the '222' is filled in, but none of the rest
If you added that debugging, do you see only "222" or also the others?

>>Use a combobox model...
that will be my next step. only problem is:

public DefaultComboBoxModel dcbm;          //fine
dcbm = new DefaultComboBoxModel();      //fine
inputPanel.add(dcbm);                             //not fine!!::
                                                                                 java:46: cannot find symbol
                                                                                 symbol  : method add(javax.swing.DefaultComboBoxModel)
                                                                                 location: class java.awt.Panel
                                                                       inputPanel.add(dcbm);


>>What is the output of this on the client:

                  ArrayList items = I.loadChoice();
                  System.out.println("no of elements: " + items.size());

    no of elements: 22
    (and there are 22 items output [on the server-side] the first one been 222 and the only one on the JComboBox)
     the list above was made up (i cant copy/paste out of the server dos window)


>>Any debugging output on the client side?
none.

>>If you added that debugging, do you see only "222" or also the others?
what debugging, client or server?
No, no, no!

You add your combobox as you used to do (exactly the same)

Add the items to the comboboxmodel

then call

combobox.setModel( model ) ;

look at the code I posted...
>>    no of elements: 22
That means that the list on the client side is nicely filled with 22 items.
Try Tim's suggestion on the client side:

>>             DefaultComboBoxModel model = new DefaultComboBoxModel() ;
>>             List items = I.loadChoice();     // Get the items via RMI
>>             for( int i = 0 ; i < items.size() ; i++ )
>>                 model.addElement( items.get( i ) ) ;
>>             jcb.setModel( model ) ;



>>    (and there are 22 items output [on the server-side]
>>  the first one been 222 and the only one on the JComboBox)

The first one?
I thought you told us:

>>all System.output on the server side:
>>
>>1234
>>222              // <<<<<<< the second???
>> ...

???????
>>The first one? I thought you told us:

'222' is the second entry in the DB...!!!

but '222' is the first in the: System.out.println("no of elements: " + items.size());
>> '222' is the second entry in the DB...!!!
I see. In a database there is no order.
You only query them in *some* ordered way. (e.g. by ID, by date, by...)

How's Tim's suggestion going?


Don't shoot at me :
You do know that
- a combo box only shows one possible item by default
- to see all possible items in a combo box you have to click on it
Don't you?

Just to be sure ;°)
>>How's Tim's suggestion going?

not going good. its still doing to same!

>>Don't shoot at me :

yeah the funny arrow thing you click and it brings a drop-down list with a scroll if necesary.

ANY OTHER SUGGESTIONS??
>> not going good. its still doing to same!
You mean empty combo or combo just containing "222"? Sorry for asking again.
Anyway, both are really IMPOSSIBLE if you have as output:
>> no of elements: 22

>> ANY OTHER SUGGESTIONS??
Are you sure you don't have code that clears the combo box afterwards?


Could you post your client-code once again? (As it is now)
>>Are you sure you don't have code that clears the combo box afterwards?
guarenteed. i havent cleared a single field

CLIENT CODE:::

import java.rmi.*;
import java.rmi.server.UnicastRemoteObject;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.sql.*;
import java.lang.*;
import java.util.*;


class gui_crafter implements ActionListener, ItemListener
{

        public JFrame frame;
        public Container con;
        public JScrollPane scrollPane;
        public Panel inputPanel, outputPanel, buttonPanel;
        public JLabel lblCrafterName, lblProductNo, lblCrafterNo, lblProductName;
        public JTextField txtCrafterName, txtProductNo, txtCrafterNo;
        public JTextArea ta;
        public Button btnshow, exitButton, btndel, btnadd, updateButton;
        public Statement statement;
        public Connection connection;      
        public JComboBox jcb;
        public DefaultComboBoxModel model;

        
        public gui_crafter()
        {            
          frame = new JFrame("Crafter Form");
          con = frame.getContentPane();
          con.setLayout(new BorderLayout() );
          frame.setSize(400,300);
      
          lblCrafterName = new JLabel("Crafter Name: ");
          lblProductNo = new JLabel("Product Number: ");
          lblCrafterNo = new JLabel("Crafter Number: ");
          lblProductName = new JLabel("");
          txtCrafterName = new JTextField(10);
          txtProductNo = new JTextField(5);
          txtCrafterNo = new JTextField(5);
          jcb = new JComboBox();
          model = new DefaultComboBoxModel();
          
          inputPanel = new Panel();
          inputPanel.setLayout(new GridLayout(10,1) );
          inputPanel.add(jcb);
          inputPanel.add(lblCrafterNo);
          inputPanel.add(txtCrafterNo);
          inputPanel.add(lblCrafterName);
          inputPanel.add(txtCrafterName);
          inputPanel.add(lblProductNo);
          inputPanel.add(txtProductNo);
          inputPanel.add(lblProductName);
      
          ta=new JTextArea(10,20);
          scrollPane = new JScrollPane(ta);
          outputPanel = new Panel();    
          outputPanel.add(scrollPane);
      
          btnshow = new Button("Show All");
          exitButton = new Button("Main Menu");
          btndel = new Button("Delete");
          btnadd = new Button("Add");
          updateButton = new Button("Update");
          buttonPanel = new Panel();
          buttonPanel.add(btnadd);
          buttonPanel.add(btnshow);
          buttonPanel.add(updateButton);
          buttonPanel.add(btndel);
          buttonPanel.add(exitButton);
      
          con.add(inputPanel,"West");
          con.add(outputPanel,"Center");
          con.add(buttonPanel,"South");
                   
               btnadd.addActionListener(this);
               btndel.addActionListener(this);      
      
               jcb.addItemListener(this);
               
              System.out.println("jcb.addItemListener(this);");
              
            try
            {

                  INTERFACE I = (INTERFACE)Naming.lookup("localhost");
                  
                  System.out.println("INTERFACE I = (INTERFACE)Naming.lookup('localhost');");            
                  
                  ArrayList items = I.loadChoice();
                  
                  for( int i = 0 ; i < items.size() ; i++ )
                  {
                        model.addElement(items.get(i));
                        jcb.setModel(model);
                  }
                  
      

                        
            //      I.loadChoice((DefaultComboBoxModel)jcb.getModel());

            //      System.out.println("no of elements: " + items.size());
                  
           //      Iterator it = items.iterator();
                 
           //      while (it.hasNext())
           //      {
        //            jcb.addItem((String)it.next());
                    
              //      String item = result.getString(1);
                  //      results.add(item);
                  //      System.out.println("Item added: " +item);

        //      }
              
            }catch(Exception ex6){System.out.println("ERROR ON INTERFACE NAMING");}
               
                           
          frame.setVisible(true);
        }
 
 
      public void itemStateChanged(ItemEvent ie)
      {
            System.out.println("public void itemStateChanged(ItemEvent ie)");      
      }
      
      
        public void actionPerformed(ActionEvent e)
    {
            if(e.getSource() == btnadd)
            {
                  String n = txtCrafterNo.getText();
                  int num = Integer.parseInt(n);
                  
                  String name = txtCrafterName.getText();
                  
                  System.out.println(num +"      " + name);
                  try
                  {
                        INTERFACE I = (INTERFACE)Naming.lookup("localhost");

                        I.add_crafter(num, name);
                                    
                  }catch(Exception ex6){}

                  
                  ta.setText("");
                  ta.setText("CRAFTER ADDED TO DATABASE");
            }
            
            
            if(e.getSource() == btndel)
            {
                  
                  String n = txtCrafterNo.getText();
                  int num = Integer.parseInt(n);
                  
                  String name = txtCrafterName.getText();
                  
                  System.out.println(num +"      " + name);
                  
                  try
                  {
                        INTERFACE I = (INTERFACE)Naming.lookup("localhost");
            
                        I.del_crafter(num, name);
            
                  }catch(Exception ex6){}
                  
                  ta.setText("");
                  ta.setText("CRAFTER DELETED FROM DATABASE");

            }
      }
}
WORKING CLASS:: [SERVER-SIDE]      


class working extends java.rmi.server.UnicastRemoteObject implements INTERFACE
{
        Statement statement;
        Connection connection;

        public working() throws RemoteException
        {
 
            try      
            {
                  Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
              String dataSourceName = "javadb1";
              String dbURL = "jdbc:odbc:" + dataSourceName;
              connection = DriverManager.getConnection(dbURL, "","");
              statement = connection.createStatement();
                   
            }catch(Exception ex1){System.out.println("could not connect to the DB");}
      }

                public ArrayList loadChoice() throws RemoteException
      {
            try
            {
                ArrayList results = new ArrayList();
       
                  Statement sq = connection.createStatement();
                  
                  ResultSet result = sq.executeQuery(
                              "SELECT crafter_sid, crafter_name"+      
                              " FROM crafter");
       
              System.out.println("stage 1");
                    while(result.next())
                    {
                          //String str = result.getString(1);
                //results.add( str ) ;
                //System.out.println(str);

                          
                     results.add(""+result.getString(1));
                     //String str = result.getString(1);
                     //System.out.println(str);
              }
              System.out.println("stage 2");
                  sq.close();

              return results;

          }catch(Exception ex7){throw new RemoteException( "Exception from loadChoice()", ex7 ) ;}
    }  

}
MY INTERFACE:::

interface INTERFACE extends Remote
{
      public ArrayList loadChoice() throws RemoteException;      
}
      
GUI code:

That's not how Tim told you:

               for( int i = 0 ; i < items.size() ; i++ )
               {
                    model.addElement(items.get(i));
                    jcb.setModel(model);
               }

replace by

             DefaultComboBoxModel model = new DefaultComboBoxModel() ;
             List items = I.loadChoice();     // Get the items via RMI
             for( int i = 0 ; i < items.size() ; i++ )
                 model.addElement( items.get( i ) ) ;
             jcb.setModel( model ) ;                                // <<<<<<< this one NOT in the for loop!!!

              for( int i = 0 ; i < items.size() ; i++ )
               {
                    model.addElement(items.get(i));
                    jcb.setModel(model);
               }

should be:

               model = new DefaultComboBoxModel();
               for( int i = 0 ; i < items.size() ; i++ )
               {
                    model.addElement(items.get(i));
               }
               jcb.setModel(model);
And you've gone back to not having a finally block in your server code...

loadChoice should be (like I said before):

        Statement sq = null ;
        ResultSet result = null ;
        ArrayList ret = new ArrayList() ;
        try
        {
            sq = connection.createStatement();
            result = sq.executeQuery( "SELECT crafter_sid, crafter_name FROM crafter" ) ;
            while( result.next() )
            {
                ret.add( result.getString( 1 ) );
            }
        }
        catch( SQLException ex )
        {
            throw new RemoteException( "Exception from loadChoice()", ex7 ) ;
        }
        finally
        {
            try { if( result != null ) result.close() ; } catch( SQLException ex ) {}
            try { if( sq != null ) sq.close() ; } catch( SQLException ex ) {}
        }
        return ret;
Let's copy the whole stuff:   changes are marked with // <<<<<<<<<<<<<<<<

import java.rmi.*;
import java.rmi.server.UnicastRemoteObject;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.sql.*;
import java.lang.*;
import java.util.*;


class gui_crafter implements ActionListener, ItemListener
{

       public JFrame frame;
       public Container con;
       public JScrollPane scrollPane;
       public Panel inputPanel, outputPanel, buttonPanel;
       public JLabel lblCrafterName, lblProductNo, lblCrafterNo, lblProductName;
       public JTextField txtCrafterName, txtProductNo, txtCrafterNo;
       public JTextArea ta;
       public Button btnshow, exitButton, btndel, btnadd, updateButton;
       public Statement statement;
       public Connection connection;    
       public JComboBox jcb;
       // public DefaultComboBoxModel model;               // <<<<<<<<< not needed

       
       public gui_crafter()
       {          
         frame = new JFrame("Crafter Form");
         con = frame.getContentPane();
         con.setLayout(new BorderLayout() );
         frame.setSize(400,300);
     
         lblCrafterName = new JLabel("Crafter Name: ");
         lblProductNo = new JLabel("Product Number: ");
         lblCrafterNo = new JLabel("Crafter Number: ");
         lblProductName = new JLabel("");
         txtCrafterName = new JTextField(10);
         txtProductNo = new JTextField(5);
         txtCrafterNo = new JTextField(5);
         jcb = new JComboBox();
         model = new DefaultComboBoxModel();
         
         inputPanel = new Panel();
         inputPanel.setLayout(new GridLayout(10,1) );
         inputPanel.add(jcb);
         inputPanel.add(lblCrafterNo);
         inputPanel.add(txtCrafterNo);
         inputPanel.add(lblCrafterName);
         inputPanel.add(txtCrafterName);
         inputPanel.add(lblProductNo);
         inputPanel.add(txtProductNo);
         inputPanel.add(lblProductName);
     
         ta=new JTextArea(10,20);
         scrollPane = new JScrollPane(ta);
         outputPanel = new Panel();    
         outputPanel.add(scrollPane);
     
         btnshow = new Button("Show All");
         exitButton = new Button("Main Menu");
         btndel = new Button("Delete");
         btnadd = new Button("Add");
         updateButton = new Button("Update");
         buttonPanel = new Panel();
         buttonPanel.add(btnadd);
         buttonPanel.add(btnshow);
         buttonPanel.add(updateButton);
         buttonPanel.add(btndel);
         buttonPanel.add(exitButton);
     
         con.add(inputPanel,"West");
         con.add(outputPanel,"Center");
         con.add(buttonPanel,"South");
                 
             btnadd.addActionListener(this);
             btndel.addActionListener(this);    
     
             jcb.addItemListener(this);
             
            System.out.println("jcb.addItemListener(this);");
           
          try
          {

               INTERFACE I = (INTERFACE)Naming.lookup("localhost");
               
               System.out.println("INTERFACE I = (INTERFACE)Naming.lookup('localhost');");          
               
               ArrayList items = I.loadChoice();
               
               DefaultComboBoxModel model = new DefaultComboBoxModel() ;           // <<<<<<<<<< define this one here
               for( int i = 0 ; i < items.size() ; i++ )
               {
                    model.addElement(items.get(i));
                    System.out.println("Item added: " + items.get(i));              // <<<<<<<<<< add this debugging output
               }
               jcb.setModel(model);             // <<<<<<<<<<<<<<<< move this one outside the for loop
               
     

                   
          //     I.loadChoice((DefaultComboBoxModel)jcb.getModel());

          //     System.out.println("no of elements: " + items.size());
               
          //     Iterator it = items.iterator();
               
          //     while (it.hasNext())
          //     {
        //          jcb.addItem((String)it.next());
                 
             //     String item = result.getString(1);
               //     results.add(item);
               //     System.out.println("Item added: " +item);

        //     }
             
          }catch(Exception ex6){System.out.println("ERROR ON INTERFACE NAMING");}
             
                       
         frame.setVisible(true);
       }
 
 
     public void itemStateChanged(ItemEvent ie)
     {
          System.out.println("public void itemStateChanged(ItemEvent ie)");    
     }
     
     
       public void actionPerformed(ActionEvent e)
    {
          if(e.getSource() == btnadd)
          {
               String n = txtCrafterNo.getText();
               int num = Integer.parseInt(n);
               
               String name = txtCrafterName.getText();
               
               System.out.println(num +"     " + name);
               try
               {
                    INTERFACE I = (INTERFACE)Naming.lookup("localhost");

                    I.add_crafter(num, name);
                             
               }catch(Exception ex6){}

               
               ta.setText("");
               ta.setText("CRAFTER ADDED TO DATABASE");
          }
         
         
          if(e.getSource() == btndel)
          {
               
               String n = txtCrafterNo.getText();
               int num = Integer.parseInt(n);
               
               String name = txtCrafterName.getText();
               
               System.out.println(num +"     " + name);
               
               try
               {
                    INTERFACE I = (INTERFACE)Naming.lookup("localhost");
         
                    I.del_crafter(num, name);
         
               }catch(Exception ex6){}
               
               ta.setText("");
               ta.setText("CRAFTER DELETED FROM DATABASE");

          }
     }
}
>>jcb.setModel( model ) ;                                // <<<<<<< this one NOT in the for loop!!!
i tried it outside and inside to test, but it did the same.

Please, use the code I just posted and post the output you got.
(PS. I'm still a quarter online)
Going offline.
Success.
>>Please, use the code I just posted and post the output you got.
all done and still just the '222'
waaaaa! dont leave me here.. please!!
ok i got good news and some bad news:

the good news is that the JComboBox is (and i think always was) populated.

the only problem is that it doesn't work with the mouse pointer and create a drop-down list... it only works once highligted and the directional keys 'up' and 'down' are used to scroll through them.

would you know how to sort this issue out?
If you want to close the connection, uncomment the obvious below:


      jcb.setModel(new DefaultComboBoxModel(I.loadChoice());
      
      
      ..............
      
      

      public Vector loadChoice() throws RemoteException {
            Statement sq = null;
            ResultSet rs = null;
            Vector v = new Vector();
            try {
                        try {
                        sq = connection.createStatement();
                        rs = sq.executeQuery("SELECT crafter_sid, crafter_name FROM crafter");
                        while(rs.next()) {
                              v.add("" + rs.getString(1));
                        }
                        return v;
                  }
                  catch(Exception e) {
                        throw new RemoteException( "Exception from loadChoice()", e );
                  }
            }
            finally {
                  try { rs.close(); } catch (Exception e) { /* ignore */ }
                  try { sq.close(); } catch (Exception e) { /* ignore */ }
                  //try { connection.close(); } catch (SQLException e) { /* ignore */ }
            }
      }
Correction to indentation:

      public Vector loadChoice() throws RemoteException {
            Statement sq = null;
            ResultSet rs = null;
            Vector v = new Vector();
            try {
                  try {
                        sq = connection.createStatement();
                        rs = sq.executeQuery("SELECT crafter_sid, crafter_name FROM crafter");
                        while(rs.next()) {
                              v.add("" + rs.getString(1));
                        }
                        return v;
                  }
                  catch(Exception e) {
                        throw new RemoteException( "Exception from loadChoice()", e );
                  }
            }
            finally {
                  try { rs.close(); } catch (SQLException e) { /* ignore */ }
                  try { sq.close(); } catch (SQLException e) { /* ignore */ }
                  //try { connection.close(); } catch (SQLException e) { /* ignore */ }
            }
      }
SOLUTION
Avatar of TimYates
TimYates
Flag of United Kingdom of Great Britain and Northern Ireland image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
sorry Tim,

let me ask something and give some points
ASKER CERTIFIED SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Question reopened

Venabili
Java Page Editor
:-)  Thanks :-)

Good luck with it all!

Tim