Results 1 to 10 of 10
  1. #1
    Join Date
    Mar 2004
    Posts
    7

    Unanswered: clicking on a JTable holding resultSet

    hi there,

    i am a bit new to JDBC and swing, i have previously only used Java for cryptography...here is my question
    i have placed a resultSet into a Jtable by converting the rs to an object array and populating the table, i would like to be able to click on the table and bring up the record clicked, my idea for doing this was:
    the user clicks a row, and a search is done fOr the CustomerID that is displayed in the JTabel.
    So i guess my questions are:
    is this the best way of doing things?
    how do i retrive the contents of a cell in the row that is clicked on?

    i.e if a user clicks on row 1 i want to get the number held in the client ID column on that row?

    thanks for any help!
    dermot

  2. #2
    Join Date
    Mar 2004
    Posts
    16

    Re: clicking on a JTable holding resultSet

    I usually do something like this to retrieve information from a JTable:

    when you have your ResultSet object from a query, turn it into a java.util.Vector of java.util.Vector object (a matrix!!!) where each inner Vector object is a row of the table (thus containg only the fields of the JTtable, not all the fields in your database table) and the outer Vector contains all of the Vector/JTable rows you want ot display in your GUI!
    It looks like this:

    /*CODE BEGIN*/

    import java.util.Vector;

    ...

    JTabel jtable;
    Vector tableVector;

    ...

    private void updateJTable()
    {
    ...

    - tableVector= new Vector(xxx,yyy); /*where xxx is the number of rows you think your JTable will have and yyy is the increment capacity of the Vector when it's full*/

    try{
    - Connection conn = DriverManager.getConnection(...);
    - Statement st = conn.createStatement();
    - ResultSet rs = st.executeQuery("your query with projections on the attributes you want your JTable to show");

    - while (rs.next())
    {
    - Vector row = new Vector(zzz);/*zzz is the number of attributes you want your JTable to store*/

    - row.add(new Integer(rs.getInt(1))); /*pay attention: rs.getInt() returns primitive type int, while java.util.Vector.add(Object o) wants a java.lang.Object object, so you have to use wrapper classes!!!*/

    -row.add(rs.getString(2));
    /*I supposed the first attribute is an integer and the second a text attribute, then you have to write down a row.add for each attribute, considering his type for the getter method of rs!!!*/
    ...

    - tableVector.add(row);
    }

    rs.close();
    st.close();
    conn.close();
    }
    catch (SQLException SQLE){e.printStackTrace();}

    jtable = new JTable(tableVector);
    scrollpanel.getViewPort().removeAll();/*I use scrollpane otherwise table rows will not scroll!!!*/

    scrollpanel.getViewPort().add(jtable);
    scrollpanel.revalidate();
    }

    /*CODE END*/

    I removed jtable and then immediatly readded because it can be helpful if you want to put some controls in your GUI that allow user to change the result shown in the JTable (some filters for the query or something like this...), which will be replaced and repainted!!
    Each time you perform your query and you want to update the Jtable object you will only have to call this method!!!

    If you make like this at the end of the method you will have your JTable displayed and in tableVector you will have exactly the same entries of the table, so in the event handler for the mouse click on your table you will only ave to do something like this:

    public void mouseClicked(MouseEvent e)
    {
    ...

    /*if the first attribute is an integer like in the upper code!!!*/
    Integer i = (Integer)((Vector)tableVector.get(jtable.getSelect edRow())).get(0);

    /*Now in i you have the ID corresponding to the selected row in your JTable!!!*/
    ...
    }

    Maybe I have written too much and you already knew most of what I explained, but I hope I have been helpful for you... Clearly this is only one way to solve your problem (and maybe it's not the best), but it's my way!!!!

    Hi. :-)
    Last edited by danyver; 03-25-04 at 11:54.

  3. #3
    Join Date
    Mar 2004
    Posts
    7
    thanks so much for your reply
    i'll give that a go, the only thing is i used an object to place the results on the JTable, i couldnt get it to work with a vector.

    i dont have my Java compiler infront of me but if i was to replace your line:
    Integer i = (Integer)((Vector)tableVector.get(jtable.getSelect edRow())).get(0);

    with

    with Integer i = (Integer)((Object)tableObject.get(jtable.getSelect edRow())).get(0);

    would i get a similar result? i.e if i kept using an Object instead of a vector.

    also will this return the value of the cell the user clicks or the row value?
    i only ask because I see the .getSelectedRow call in there.

    thank you again for your help, it is really appreciated

    cheers
    Dermot

  4. #4
    Join Date
    Mar 2004
    Posts
    16
    ok, I have understood! No problem if you used an Object (if I suppose well you have used JTable(Object[][] rowData, Object[] columnNames)
    constructor!) but I can help you definitively if you post me the code you used to populate the JTable!!!

    P.s.: the replacement with Integer i = (Integer)((Object)tableObject.get(jtable.getSelect edRow())).get(0); would give you a compilation error because Object class does not contain any get method!!!!

    I wait for your reply!!!

    Hi, Daniele

  5. #5
    Join Date
    Mar 2004
    Posts
    7

    Smile

    thanks so much!
    i will post the code on monday, its on my other PC
    thanks again

  6. #6
    Join Date
    Mar 2004
    Posts
    7

    Smile

    Originally posted by danyver
    ok, I have understood! No problem if you used an Object (if I suppose well you have used JTable(Object[][] rowData, Object[] columnNames)
    constructor!) but I can help you definitively if you post me the code you used to populate the JTable!!!

    P.s.: the replacement with Integer i = (Integer)((Object)tableObject.get(jtable.getSelect edRow())).get(0); would give you a compilation error because Object class does not contain any get method!!!!

    I wait for your reply!!!

    Hi, Daniele

    ***********************************
    here is the code i am using to execute the query and place it into the JTable




    void cmdSearch_actionPerformed(ActionEvent e) {

    //build SQL Query

    String searchQuery = new String();
    String last = this.txtLastName.getText() ;
    searchQuery = ("select testMembers.LastName, testMembers.FirstName from testMembers where LastName like ('" + last + "')");


    System.out.println(dbConnection.toString());


    ResultSetMetaData md = null;
    try {
    dbConnection.createStatement();
    System.out.println( dbConnection.toString());
    resultSet = statement.executeQuery(searchQuery);
    md = resultSet.getMetaData();
    JOptionPane.showMessageDialog(null, "begin new code") ;
    // Convert the result set into an array of Objects
    Object[][] rows = getObjects(resultSet);
    String[] headings = { "firstName", "LastName" };
    // Initialize a JTable with the rows of objects and column headings
    JTable table = new JTable(rows, headings);
    table.setBounds(new Rectangle(20, 500, 500, 150));


    //to test if a user clicks a cell in the table
    table.addMouseListener(new MouseAdapter(){
    public void mouseClicked(MouseEvent e){
    if (e.getClickCount() == 1){

    JOptionPane.showMessageDialog(null, "clicked");
    //the next four lines were meant to show what cell the user clicked, doesnt seem to work
    x =e.getX();
    y =e.getY();
    Integer temp =new Integer(x);
    temp.toString(x);
    JOptionPane.showMessageDialog(null,temp.toString(x ));

    }
    }
    });

    JScrollPane scrollPane = new JScrollPane(table);

    // Add the scroll pane to the JFrame's container
    getContentPane().add(scrollPane);

    show();
    pack();
    JOptionPane.showMessageDialog(null, table.getValueAt(1,1));

    JOptionPane.showMessageDialog(null, "end new code") ;

    }

  7. #7
    Join Date
    Mar 2004
    Posts
    16
    //to test if a user clicks a cell in the table
    table.addMouseListener(new MouseAdapter(){
    public void mouseClicked(MouseEvent e){
    if (e.getClickCount() == 1){

    JOptionPane.showMessageDialog(null, "clicked");
    //the next four lines were meant to show what cell the user clicked, doesnt seem to work
    x =e.getX();
    y =e.getY();
    Integer temp =new Integer(x);
    temp.toString(x);
    JOptionPane.showMessageDialog(null,temp.toString(x ));

    }
    }
    });

    The problem is here!!! Precisely x = e.getX(); and y = e.getY(); return the x and y coordinates of the point you clicked over in JFrame reference axis... Thus you will have coordinates of a pixel!!!

    You should use instead something like this:

    table.addMouseListener(new MouseAdapter(){
    public void mouseClicked(MouseEvent e){
    if (e.getClickCount() == 1){

    int temp = rows[table.getSelectedRow()][0]; /*if in the row the attribute you're searching for is the first one (otherwise replace 0 in the second index!!!)*/


    JOptionPane.showMessageDialog(null, "clicked");
    JOptionPane.showMessageDialog(null,temp+"");

    }
    }
    });

    Clearly the matrix rows must contain exactly and always the same values your JTable display, or at least there must be corrispondency between JTable's rows and your matrix' rows!!!

    Tell me if it works now!!!

    A question: in which class is this code embedded??

    Bye, D.
    Last edited by danyver; 04-01-04 at 07:25.

  8. #8
    Join Date
    Mar 2004
    Posts
    7
    hi thanks for the reply,

    when i try the line

    temp = rows[table.getSelectedRow()][0];

    it gives me an error (on the [0] i think)
    the error is:

    Error #: 354 : incompatible types; found: java.lang.Object, required: int at line 164, column 52

    but i am giving it an int : 0

    i guess i am doing something simple wrong as i think i understand what your doing......i have tried putting the int from get selected row into its own variable but when i do that i get the same error,
    i have declared table as so:
    final JTable table = new JTable(rows, headings);

    i had to add the 'final' statement, becuase it was giving me an error when i tried to access the table from within the click rountine...


    thanks again,
    d

  9. #9
    Join Date
    Mar 2004
    Posts
    16
    You have to replace


    temp = rows[table.getSelectedRow()][0];
    with


    temp = ((Integer)rows[table.getSelectedRow()][0]).intValue();
    because
    rows[table.getSelectedRow()][0];
    statement will effectively return you an Object since rows is an Object[][] class (remember you created it with
    Object[][] rows = getObjects(resultSet);
    statement!!!)

    This will work if in the rows matrix
    rows[table.getSelectedRow()][0];
    is an Integer class value; if this is not you will have at runtime a ClassCastExceptionError the you have to do this:

    before the line I told you to replace add:

    System.out.println(rows[table.getSelectedRow()][0].getClass());
    and you will have printed to stdout to which Class
    rows[table.getSelectedRow()][0];
    belongs and then replace

    temp = ((Integer)rows[table.getSelectedRow()][0]).intValue();
    with

    temp = ((xxx)rows[table.getSelectedRow()][0]).intValue();
    where xxx will be the value written to stdout previously!!

    I hope I have been clear!
    If you find any ather problem just post it!!

    Bye, D.
    Last edited by danyver; 04-02-04 at 13:57.

  10. #10
    Join Date
    Mar 2004
    Posts
    7

    THANKS!

    this works per-fect-ly

    thank you so much!

    cheers
    D

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •