Results 1 to 14 of 14
  1. #1
    Kenjitsuka is offline Member
    Join Date
    Oct 2010
    Posts
    18
    Rep Power
    0

    Default GUI does not update table when variables are set to datamodel using JButton

    EDIT: Tried to make the main class as SSCCE as I could

    I've written a looong class with a GUI showing a JComboBox, a JTextField and a JButton. These control a searchable database table.

    The data displayed is controlled by a custom TableModel I have specified in a different class. The final step in making my GUI a viable, working class is getting the data from the JComboBox called zoeker_combobox (which uses a hashmap from a class I wrote called ComboBoxItem. This makes it possible to show a value to the user, but return a different value. The returned value is the columnname on which the user wants to search. The text the user wants to find is then typed into the JTextField zoeker_TextField_zoekwaarde.

    Of course I want the table shown to update using the search parameters when the user hits the button zoeker_zoekknop.

    I have been trying to make the button set the values from the JComboBox and JTextField into the TableModel class (called DbUtils).
    So far, no luck.

    I have not programmed anything for 8 years, and it took me 50 hours to get here. I am totally oblivious to writing getter methods, but can use setters. I tested the getters in DbUtils with a dummy class, they work. But I can't get the setters in the GUI class to trigger an update of the datamodel (or it's view in my GUI, can't be 100% sure to be honest).

    Here's the GUI class called zoekInterface, after that I will post DbUtils.
    Java Code:
    import java.awt.*;
    import java.sql.Connection;
    import java.sql.DriverManager;
    import java.sql.ResultSet;
    import java.sql.ResultSetMetaData;
    import java.sql.Statement;
    import java.util.Vector;
    import javax.swing.table.DefaultTableModel;
    import javax.swing.table.TableColumn;
    import javax.swing.table.TableModel;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import javax.swing.*;
    
    
    public class ZoekShort extends javax.swing.JFrame implements ActionListener {
      private JTable databaseResultaat_tabel;
      private JScrollPane jScrollPane1;
      private JComboBox zoeker_combobox;
      private JButton zoeker_zoekknop;
      private JTextField zoeker_TextField_zoekwaarde;
      public static String zoekterm;
      public static String zoektekst;
    
      public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
          public void run() {
            ZoekShort inst = new ZoekShort();
            inst.setLocationRelativeTo(null);
            inst.setVisible(true);}});}
      
      public ZoekShort() {super();
        initGUI();}
      private void initGUI() {
        try {{getContentPane().setLayout(null);
            this.setResizable(false);
            this.setTitle("Eurovip Paspoortzoeker - Menno Hagens 2010");
            {   jScrollPane1 = new JScrollPane();
              getContentPane().add(jScrollPane1);
              jScrollPane1.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
              jScrollPane1.setBounds(12, 133, 1057, 317);
              
              {  
                Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/eurovip", "root", "admin");
                //Connection conn = null;
                Statement stmt = null;
                stmt = conn.createStatement();
                ResultSet rs = stmt.executeQuery("SELECT MRZ1, MRZ2, MRZ_TYPE, MRZ_ISSUE_COUNTRY, MRZ_NAME, MRZ_DOCUMENT_NUMBER, MRZ_NATIONALITY, MRZ_SEX, MRZ_BIRTH_DATE, MRZ_EXPIRY_DATE, MRZ_PERSONAL_DATA, TYPE, ISSUE_COUNTRY, NAME, SURNAME, GIVENNAME, DOCUMENT_NUMBER, NATIONALITY, SEX, BIRTH_DATE, EXPIRY_DATE, PERSONAL_DATA, MRZ_FIELDS, HOTEL, bestandsnaam FROM namen");
                databaseResultaat_tabel = new JTable(DbUtils.resultSetToTableModel(rs ));
                jScrollPane1.setViewportView(databaseResultaat_tabel);
                }
            }
            {
              ComboBoxModel zoeker_comboboxModel = new DefaultComboBoxModel();
              final Object items[] = {new ComboBoxItem("Voornaam", "NAME")};  
              zoeker_combobox = new JComboBox(items);
              getContentPane().add(getZoeker_combobox());
              //zoeker_combobox.setModel(zoeker_comboboxModel);
              zoeker_combobox.setBounds(24, 65, 235, 23);
              zoeker_combobox.addActionListener(
              new ActionListener() {
              public void actionPerformed(ActionEvent e) {    
              Object o = zoeker_combobox.getSelectedItem();
              String naam = ((ComboBoxItem)o).getValue();
              zoekterm = naam;
              System.out.println(zoekterm);
              }});
            }  
              }
            {
              zoeker_TextField_zoekwaarde = new JTextField();
              getContentPane().add(getZoeker_TextField_zoekwaarde());
              zoeker_TextField_zoekwaarde.setBounds(319, 65, 303, 23);
              zoeker_TextField_zoekwaarde.addActionListener(
                    new ActionListener() {
                        public void actionPerformed(ActionEvent e) {    
                         String zoektekst = zoeker_TextField_zoekwaarde.getText();
                         System.out.println(zoektekst);}
                      });}
            {
              zoeker_zoekknop = new JButton();
              getContentPane().add(zoeker_zoekknop);
              zoeker_zoekknop.setText("Zoek!");
              zoeker_zoekknop.setBounds(668, 65, 173, 23);
              zoeker_zoekknop.addActionListener(new ActionListener()
              {
                public void actionPerformed(ActionEvent e)
                {
                  System.out.println("Zoekknop is ingedrukt");
                  jScrollPane1.setViewportView(databaseResultaat_tabel);
                // String zoektermReturn = zoekterm;
                }});
            }
        this.setSize(1091, 530);
        } catch (Exception e) {
          e.printStackTrace();
        }
      }
      public static String geefZoekTerm(){
      return zoekterm;
      }
      public static String geefZoekTekst(){
      return zoektekst;
      }  
      public JComboBox getZoeker_combobox() {
        return zoeker_combobox;
      }
      public JTextField getZoeker_TextField_zoekwaarde() {
        return zoeker_TextField_zoekwaarde;
      }
    }
    DbUtils:
    Java Code:
    package laadpackage;
    import java.sql.Connection;
    import java.sql.DriverManager;
    import java.sql.ResultSet;
    import java.sql.ResultSetMetaData;
    import java.sql.Statement;
    import java.util.Vector;
    import javax.swing.table.DefaultTableModel;
    import javax.swing.table.TableModel;
    
    public class DbUtils {
        public static TableModel resultSetToTableModel(ResultSet rs) {
            Statement stmt = null;
            //ResultSet rs = null;
            try {
            	 Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/eurovip", "root", "admin");
                 //Connection conn = null;
    
                 stmt = conn.createStatement();
                 String zoeksoort = zoekInterface.geefZoekTerm(); 
                 System.out.println(zoeksoort);
                 //String zoekterm = dataInvoer.NAME();
                 String zoekterm =zoekInterface.geefZoekTekst();
                 System.out.println(zoekterm);
                 //rs = stmt.executeQuery("SELECT NAME, SURNAME, GIVENNAME, DOCUMENT_NUMBER, NATIONALITY, SEX, BIRTH_DATE, EXPIRY_DATE, PERSONAL_DATA, ISSUE_COUNTRY, HOTEL, bestandsnaam, MRZ1, MRZ2, MRZ_TYPE, MRZ_ISSUE_COUNTRY, MRZ_NAME, MRZ_DOCUMENT_NUMBER, MRZ_NATIONALITY, MRZ_SEX, MRZ_BIRTH_DATE, MRZ_EXPIRY_DATE, MRZ_PERSONAL_DATA, MRZ_FIELDS, TYPE FROM namen where "+zoeksoort+" like '%"+zoekterm+"%'");
                 rs = stmt.executeQuery("SELECT NAME, SURNAME, GIVENNAME, DOCUMENT_NUMBER, NATIONALITY, SEX, BIRTH_DATE, EXPIRY_DATE, PERSONAL_DATA, ISSUE_COUNTRY, HOTEL, bestandsnaam, MRZ1, MRZ2, MRZ_TYPE, MRZ_ISSUE_COUNTRY, MRZ_NAME, MRZ_DOCUMENT_NUMBER, MRZ_NATIONALITY, MRZ_SEX, MRZ_BIRTH_DATE, MRZ_EXPIRY_DATE, MRZ_PERSONAL_DATA, MRZ_FIELDS, TYPE FROM namen where "+zoeksoort+" like '%"+zoekterm+"%'");
                 
            	
                ResultSetMetaData metaData = rs.getMetaData();
                int numberOfColumns = metaData.getColumnCount();
                Vector columnNames = new Vector();
    
                // Get the column names
                for (int column = 0; column < numberOfColumns; column++) {
                    columnNames.addElement(metaData.getColumnLabel(column + 1));
                }
    
                // Get all rows.
                Vector rows = new Vector();
    
                while (rs.next()) {
                    Vector newRow = new Vector();
    
                    for (int i = 1; i <= numberOfColumns; i++) {
                        newRow.addElement(rs.getObject(i));
                    }
    
                    rows.addElement(newRow);
                }
    
                return new DefaultTableModel(rows, columnNames);
            } catch (Exception e) {
                e.printStackTrace();
    
                return null;
            }
        }
    }
    Your help is extremely appreciated, I've been at it for hours on end and desperate. :confused:
    Last edited by Kenjitsuka; 10-24-2010 at 05:24 PM. Reason: Made it as SSCCE as I could

  2. #2
    DarrylBurke's Avatar
    DarrylBurke is offline Forum Police
    Join Date
    Sep 2008
    Location
    Madgaon, Goa, India
    Posts
    11,458
    Rep Power
    20

    Default

    TL;DR

    To get better help sooner, post a SSCCE (Short, Self Contained, Compilable and Executable) example that demonstrates the problem. The important word is short.

    db

  3. #3
    JosAH's Avatar
    JosAH is offline Moderator
    Join Date
    Sep 2008
    Location
    Voorschoten, the Netherlands
    Posts
    13,773
    Blog Entries
    7
    Rep Power
    21

    Default

    Quote Originally Posted by Kenjitsuka View Post
    Your help is extremely appreciated, I've been at it for hours on end and desperate. :confused:
    I didn't read all that code (way too much for a Saturday) but maybe when your table model has changed you have to notify your table of the change(s) by doing:

    Java Code:
    yourTable.tableChanged(new TableModelEvent(yourTable.getModel()));
    kind regards,

    Jos

  4. #4
    Kenjitsuka is offline Member
    Join Date
    Oct 2010
    Posts
    18
    Rep Power
    0

    Default

    Per request by db here are, what I think, the most important parts of code:

    -Making the table and filling it with data via my custom TableModel:
    Java Code:
    databaseResultaat_tabel = new JTable(DbUtils.resultSetToTableModel(rs ));						jScrollPane1.setViewportView(databaseResultaat_tabel);
    Making the JComboBox with custom Items, this will be the database columnname the user wants to search in:
    Java Code:
    ComboBoxModel zoeker_comboboxModel = 
    						new DefaultComboBoxModel(
    								);
    					final Object items[] = {
    //Omited all but one Items
    						new ComboBoxItem("Voornaam", "NAME"),
    						};	
    					zoeker_combobox = new JComboBox(items);
    					getContentPane().add(getZoeker_combobox());
    
    					
    					zoeker_combobox.addActionListener(
    					new ActionListener() {
    					public void actionPerformed(ActionEvent e) {    
    					Object o = zoeker_combobox.getSelectedItem();
    					String naam = ((ComboBoxItem)o).getValue();
    					zoekterm = naam;
    					System.out.println(zoekterm);}
    					});
    Making the JTextField which gets the users searchterm:
    Java Code:
    zoeker_TextField_zoekwaarde = new JTextField();
    getContentPane().add(getZoeker_TextField_zoekwaarde());
    zoeker_TextField_zoekwaarde.addActionListener( new ActionListener() {
    public void actionPerformed(ActionEvent e) {String zoektekst = zoeker_TextField_zoekwaarde.getText();}});}
    And finally the JButton is made, which I want to pass the values entered by user in the JComboBox and JTextField to the DbUtils class (this is the class that has the custom TableModel in it);
    Java Code:
    zoeker_zoekknop = new JButton();
    getContentPane().add(zoeker_zoekknop);
    zoeker_zoekknop.addActionListener(new ActionListener(){public void actionPerformed(ActionEvent e)
    {jScrollPane1.setViewportView(databaseResultaat_tabel);
    // String zoektermReturn = zoekterm;
    Like I said, my problem is that the table "databaseResultaat_tabel" does not show any change when I input values. All the parts work, I have checked with dummy variables and classes etc. The thing is I can't seem to write getters to output the changes made in the GUI. I'm just that bad at programming...

    I've tried several things, like writing a separate getter method and then having the actionlistener update the global variables created for this reason:
    Java Code:
    public static String geefZoekTerm(){return zoekterm;}
    These are some excerpts from the full classes from the first post.
    I hope this helps clarify the situation a bit.
    Thanks for your continued input! :)

  5. #5
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,315
    Blog Entries
    1
    Rep Power
    26

    Default

    Quote Originally Posted by Kenjitsuka View Post
    Per request by db here are, what I think, the most important parts of code:
    Did you read the link that Darryl provided? I doubt it since your code isn't close to an SSCCE. If you still need our help, please read the link that I will provide again for you and consider creating and posting your SSCCE:

    SSCCE

    Good luck.

  6. #6
    Kenjitsuka is offline Member
    Join Date
    Oct 2010
    Posts
    18
    Rep Power
    0

    Default

    I've replaced the original class with a much shorter one.
    Stripping out as much as I safely could
    I've left all the imports in, as it won't compile without them.

    I hope it's SSCCE now!

  7. #7
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,315
    Blog Entries
    1
    Rep Power
    26

    Default

    Quote Originally Posted by Kenjitsuka View Post
    I hope it's SSCCE now!
    sigh....

    Don't guess.
    Does it compile as written? Nope

    Is it free from outside dependencies? Nope -- it requires a database which we don't have.

  8. #8
    Kenjitsuka is offline Member
    Join Date
    Oct 2010
    Posts
    18
    Rep Power
    0

    Default

    Is it free from outside dependencies? Nope -- it requires a database which we don't have.
    The SSCCE page states "Obviously there are things that cannot be included in an example that is posted to a usenet forum, 'a database' etcetera".
    I'm not sure how to work around that. And is it nescecary?
    The code retrieves the information from database itself no problem.
    It's just that the update needs to be triggered, or processed by the viewport/tablemodel as far as I know.

    It compiles no problem for me, except that the components didn't show.
    I've re-added three lines and now the GUI displayes the very basics.
    I'll repost that code in the original post

  9. #9
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,315
    Blog Entries
    1
    Rep Power
    26

    Default

    Quote Originally Posted by Kenjitsuka View Post
    The SSCCE page states "Obviously there are things that cannot be included in an example that is posted to a usenet forum, 'a database' etcetera".
    I'm not sure how to work around that. And is it nescecary?
    It's hard to say as nothing is absolutely necessary of course, and you may run into a volunteer here who takes one glance at your code and says "aha! the problem is such and such!", but unfortunately, if they exist, they haven't replied to your post yet, and so far your stuck with only me. And as for me, I find that I understand code problems much better if I can run the code myself, modify the code, experience the problem first hand, and play with the code until I can see a solution. So until a possible genius comes around, all I can say is that your chances of getting decent help here will increase by orders of magnitude if you can tease out your database-related code and instead use some hard coded data such as arrays and such. But also your GUI won't compile even if I did have you database since the class implements an interface but does not implement the interface's methods. Coding is unforgiving.

    Luck.

  10. #10
    Kenjitsuka is offline Member
    Join Date
    Oct 2010
    Posts
    18
    Rep Power
    0

    Default

    Thanks for your continued support, Fubarable.
    I'll look into replacing the database with an array, I hadn't thought of that yet, but I think that will be a viable option.

    Unfortunately I have had a filling fall out and the toothache is driving me up the walls at the moment. I hope to get a dentists appointment tomorrow, as I really can't concentrate like this.

    Cheers,
    Kenji.

    EDIT: Oh, you get a compiler error because you don't have the database, now I get it. Duh, stupid me!
    Last edited by Kenjitsuka; 10-24-2010 at 05:59 PM.

  11. #11
    al_Marshy_1981 is offline Senior Member
    Join Date
    Feb 2010
    Location
    Waterford, Ireland
    Posts
    748
    Rep Power
    5

    Default

    If the JButton is pulling the info from the ComboBox and JTextField why dont you use the JButton actionListener only to do this? and then inside its actionPerformed method make a call to a DbUtils method(or whatever way you are implementing it) passing said ComboBox item and JTextField text.

  12. #12
    Kenjitsuka is offline Member
    Join Date
    Oct 2010
    Posts
    18
    Rep Power
    0

    Default

    If the JButton is pulling the info from the ComboBox and JTextField why dont you use the JButton actionListener only to do this
    I wasn't sure the JButton could get information from the ComboBox and JTextField. But I tried it, and sure enough; now a press on the JButton processes the content of the other two!
    Thanks, al_Marshy_1981! This makes it far less cluttered!

    I am unsure how to call DbUtils tho, which I guess might be the original problem.
    In the main class ZoekInterface I have two simple setter methods like this:
    Java Code:
    public static String geefZoekTerm(){
    return zoekterm;}
    And in DbUtils I read them like so
    Java Code:
    String zoeksoort = ZoekInterface.geefZoekTerm();
    What I need to make happen is that ZoekInterface tells the table to update.
    I am not sure if I need to do this via the viewport or by reloading the JTable itself (i.e. DbUtils.resultSetToTableModel(rs) ):
    Java Code:
    databaseResultaat_tabel = new JTable(DbUtils.resultSetToTableModel(rs ));
    jScrollPane1.setViewportView(databaseResultaat_tabel);
    This is the part I am stuck with, logically:
    How do I make the button reload/re-run the DbUtils class?
    I'm pretty sure it's the tablemodel I need to update, but I can't seem to get it fixed.:rolleyes:

  13. #13
    al_Marshy_1981 is offline Senior Member
    Join Date
    Feb 2010
    Location
    Waterford, Ireland
    Posts
    748
    Rep Power
    5

    Default

    Try making a DbUtils object inside your ZoekInterface Construtor, so you will have a reference to update the table

    Java Code:
    private DbUtils mydb=null;
    public ZoekInterface(DbUtils db){
     mydb=db;
    }
    then you can have an update method inside ZoekInterface...
    Java Code:
    public void updateTable(DbUtils db){
        // update table using your DbUtils reference
    }

    Inside DbUtils have a method which runs ZoekInterface class and pass the current DbUtils object
    e.g.
    Java Code:
    public void runZoekInterface(){
        new ZoekInterface(this);
    }
    Best I can think of
    Last edited by al_Marshy_1981; 10-25-2010 at 07:18 PM. Reason: ...

  14. #14
    Kenjitsuka is offline Member
    Join Date
    Oct 2010
    Posts
    18
    Rep Power
    0

    Default

    Hi all,

    I have played around with Al's suggestions a lot, but I still can't figure it out.
    I've looked at TableModelEvent, faking a response to data changes (databaseResultaat_tabel.fireTableChanged() and other methods), and tried
    filling the Vector with values so it could be an SSCCE.
    But there's a problem with that last thing; the whole problem hinges on re-passing a SQL select command and handling the new data in the GUI. So if I use an Object[][] and it works I don't think that will help me figure out what to do?

    al_Marshy_1981, I have implemented your idea, but I can't, for the life of me, figure out what to put here:
    // update table using your DbUtils reference

    I looked around on Google a lot, and find many very interesting pages like http://www.cs.sun.ac.za/rw214/2008/r...nts/table.html
    But none seem to deal with handling events from a simple search GUI. Is it so rare?
    :(
    Last edited by Kenjitsuka; 10-30-2010 at 05:03 PM.

Similar Threads

  1. Replies: 0
    Last Post: 02-21-2010, 12:51 PM
  2. Access datamodel
    By Scale in forum JavaServer Pages (JSP) and JSTL
    Replies: 0
    Last Post: 11-18-2009, 05:14 PM
  3. What are Instance variables and static variables?
    By sandeshforu in forum New To Java
    Replies: 3
    Last Post: 09-09-2009, 06:48 PM
  4. Update jButton from ListSelectionHandler
    By daveyboy79 in forum AWT / Swing
    Replies: 2
    Last Post: 09-02-2009, 02:30 PM
  5. [SOLVED] JTable DataModel - how to get
    By AZMichael in forum AWT / Swing
    Replies: 3
    Last Post: 07-09-2008, 09:27 AM

Posting Permissions

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