This week's book giveaways are in the Jython/Python and Object-Oriented programming forums.
We're giving away four copies each of Machine Learning for Business: Using Amazon SageMaker and Jupyter and Object Design Style Guide and have the authors on-line!
See this thread and this one for details.
Win a copy of Machine Learning for Business: Using Amazon SageMaker and JupyterE this week in the Jython/Python forum
or Object Design Style Guide in the Object-Oriented programming forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Bear Bibeault
  • Paul Clapham
  • Jeanne Boyarsky
  • Knute Snortum
Sheriffs:
  • Liutauras Vilda
  • Tim Cooke
  • Junilu Lacar
Saloon Keepers:
  • Ron McLeod
  • Stephan van Hulst
  • Tim Moores
  • Tim Holloway
  • Carey Brown
Bartenders:
  • Joe Ess
  • salvin francis
  • fred rosenberger

Question about JComboBox with database data in JTable

 
Ranch Hand
Posts: 119
2
Netbeans IDE PHP Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Best ranchers!

I have encountered a huge problem in one of my projects. I need a JTable that will consist of two columns, one is "Soundformat" and the other is "Language". Both columns shall have editors and renderers attached to them, theese editors and renderers are JComboBox<String> which I wan't to populate with data from two database tables "tbl_soundformat" and "tbl_language".  To the right of the JTable I have two JButtons. When the user clicks on the first JButton - the first one has a plus-icon on it, and the second a minus-icon - a new row will be added in the JTable containing a row with two jcomboboxes that contains selectable data picked from the soundformat -and language tables. I know how to attach celleditors and renderers to a JTable using



But i am extremely unsure what to do with table models in this case. I wan't to use an AbstractTableModel for the JTable in question. Can anyone hint me out with this problem step by step? Any help will be greatly much appreciated.

Best regards,
Robert!

 
Saloon Keeper
Posts: 11189
244
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Uhh, well the Javadocs do a pretty good job. Just read the class documentation. It also gives a description of the default implementation for all methods, so you can just override the methods that don't do what you want them to do.

You will want to override the following methods:

  • getRowCount()
  • getColumnCount()
  • getColumnName(int columnIndex)
  • getColumnClass(int columnIndex)
  • getValueAt(int rowIndex, int columnIndex)
  • isCellEditable(int rowIndex, int columnIndex)
  • setValueAt(Object value, int rowIndex, int columnIndex)

  • You will also want to add the following methods:

  • insertRow(int rowIndex, Map<? super String, ?> rowData)
  • removeRow(int rowIndex)

  • When your database has updated as a result of a call to setValueAt(), insertRow() or removeRow(), you will want to fire the appropriate event from these method calls, using fireTableCellUpdated​(int row, int column), fireTableRowsInserted​(int firstRowIndex, int lastRowIndex) and fireTableRowsDeleted​(int firstRowIndex, int lastRowIndex) respectively.

    When you want the table to be updated to account for external changes that have been made to the database (using a refresh button or something), all you need to do is call either fireTableDataChanged() or fireTableStructureChanged().
     
    Robert Ingmarsson
    Ranch Hand
    Posts: 119
    2
    Netbeans IDE PHP Java
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    Best, Mr. Van Hulst!

    Thank you so much for your kind reply! I am pretty lost when it comes to the problem in question. This is what I have tried so far when it comes to the AbstractTableModel part:



    I have a main list that will consists of SoundTrack objects which will be added to the table when the user clicks the insert button. And i update the model after each insertion with the fireTableDataChanged(); and fireTableStructureChanged(); methods. But it is not working the way I wan't. I somehow manage to put two lists in the model, that must be totally wrong.

    This is what my SoundTrack object looks like



    I am very confused about this part of my project. What shall I add to the "main" list in this case? Am I even close or not? Could you show me some code so I know where to correct my mistake? Sorry for a lot of confusion ...

    Best regards,
    Robert!

     
    Rancher
    Posts: 3111
    26
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator

    I somehow manage to put two lists in the model, that must be totally wrong.



    Correct. The TableModel is NOT used to store all the possible values for your "soundFormat" and "language".

    Your SoundTrack class should only ever be used to create the JComboBoxes that are used for the editor of your table.

    There is no need for you to create a custom TableModel. You can use the DefaultTableModel with two columns.

    Then you attach the combo boxes as editors to each column.

    So your basic code would be something like:


    Read the section from the Swing tutorial on Using a Combo Box as an Editor for more information and working examples.

    The main difference between the example and your code is that the example is that the data that is loaded into the combo box is hard coded, but you get your data from a database.

    It does not affect how the TableModel is created.

    When the user clicks on the first JButton - the first one has a plus-icon on it,


    Now when you click on the button you invoke the DefaultTableModel.addRow(...) method to add an empty row of data.

    Then when the user edits the cell the combo box will drop down with the list of valid values that can be selected.

     
    Robert Ingmarsson
    Ranch Hand
    Posts: 119
    2
    Netbeans IDE PHP Java
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    Hi, again!

    I think I'm going crazy on this one. I have tried using AbstractTableModel and then DefaultTableModel as suggested earlier for this part but I fail in both attempts. I wan't to add an object of my SoundTrack class to a JTable. The trick is that the SoundTrack consists of data from two tables one called "tbl_soundformat" and the other "tbl_language". How can I make a JTable row-object that contains data from both of the forementioned tables? Also I have tried using joins for this but it has failed. Im very puzzled about this but don't wan't to give up just yet.

    My JTable columns have both JComboBox cellrenderers and celleditors attached to them. I hope someone sees what I am trying to accomplish here?. Any further enlightment is greatly much appreciated here.

    Best wishes,
    Robert!    
     
    Rob Camick
    Rancher
    Posts: 3111
    26
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator

    I know how to attach celleditors and renderers to a JTable using


    Do you know what an editor is?

    An editor is NOT data that is stored in the TableModel.

    It is an editor. That means it edits the data the user selects before adding the data to the TableModel.

    In your case you are choosing to use a JComboBox as an editor. So the combox displays a list of all possible values and the user selects one.

    How can I make a JTable row-object that contains data from both of the forementioned tables?


    I showed you how to create an empty JTable with two column.

    If you want one row of data then you use:


    Now the model will be created with one empty row of data.

    Then you click on the cell and the combo box will open and you select a value from the combo box.

    The TableModel will then be updated to reflect the value you selected.

    Repeat the above steps for the other cell.

    Or another approach is to use the addRow(...) method of the DefaultTableModel to add a row of data:



    If you are trying to create multiple rows (one for each format) then you need to iterate through all the items in the List and add each row manually.
     
    Robert Ingmarsson
    Ranch Hand
    Posts: 119
    2
    Netbeans IDE PHP Java
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    Many thanks to all who have replied to my problem. In short I don't know how to make a table row of two lists of database table data. I simply wonder how this is done in the real world. Right now I am going through a heavy "trial and error" process regarding this subject. I know how to make a table row of one list - using the toArray()-method - but not two lists. Please can someone enlighten me on this?

    Best Regards,
    Robert!
     
    Marshal
    Posts: 24950
    61
    Eclipse IDE Firefox Browser MySQL Database
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    I don't understand what it means to have "two lists" in a table row. Would that translate into two columns, each of which contains a list?

    And if so, how should each of the two lists be displayed in the two columns?

    Or would it translate into one column for each entry in the two lists?

    The latter seems kind of fragile as it would require all of the rows to have the same size lists.
     
    Rob Camick
    Rancher
    Posts: 3111
    26
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator

    In short I don't know how to make a table row of two lists of database table data.



    What on earth does that mean? I'm glad to see I am not the only one confused.

    What if you have 20 "format" items and only 3 "language" items. How do you expect that to be displayed?

    Give us an ascii drawing of what you expect the table to look like.

    For example a JTable of peoples names might look like:

    First Name | Last Name
    --------------------------
    Bill            | Smith
    Tom          | Jones

     
    Robert Ingmarsson
    Ranch Hand
    Posts: 119
    2
    Netbeans IDE PHP Java
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    Best ranchers!

    I've been away for a while, but I'm back now. I'm a terrible poster. Right now I am working on this JTable that will consist of two columns one is called "Format" and the other "Languge". I am really confused on this one so excuse me if I'm not making any sense at all. But i'll do my best to describe the problem better. Each column in this JTable will have a renderer and a celleditor of a JComboBox class attached to them.
    In a class called SoundTrackTable that extends JTable and has an instanceof of a DefaultTableModel registered to it - I first install the table columns and then my renderers and editors like below:





    This is what my TableCellEditor class looks like, it extends DefaultTableCellEdior



    This is what my TableCellRenderer class looks like



    My goal is to populate this JTable with data from two lists that in turn are populated with data from two database tables. When the user clicks on the insert button I wan't to add a new row with comboboxes of format and language data to the JTable. But hence nothing works. I have tried the following:





    //Ascii version of my JTable in question ...

    ---------------------------------
    SoundFormat       | Language |
    ---------------------------------
    Dolby Digital 5.1  | Swedish
    ---------------------------------
    Dolby Digital 7.1 |  English
    ---------------------------------



    But all that is showing up in the JTable is a row of two blank columns! I can't not understand any longer what I'm doing wrong. How would something like this be done out there in the real world? I'm I on the right track or not? Sorry for the confusion, folks, I'm struggling very hard but I'm still a beginner after all theese years of coding  

    I hope I have been clear enough on what the problem is or what I'm trying to accomplish. Thank you so much for your time!

    Best regards
    Robert!
     
    Rob Camick
    Rancher
    Posts: 3111
    26
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator

    I am working on this JTable that will consist of two columns one is called "Format" and the other "Languge".


    You just create the DefaultTableModel with an Array containing the column names.

    In a class called SoundTrackTable that extends JTable


    There is no need to extend JTable. You are not adding any new functionality to the table.

    This is what my TableCellEditor class looks like, it extends DefaultTableCellEdior


    There is no need to extend the DefaultTableCellEditor. You can just provide the JComboBox as a parameter.

    My goal is to populate this JTable with data from two lists that in turn are populated with data from two database tables


    Makes no sense (to me).

    You should NOT be adding data from the database directly to the JTable.

    The data should only be used to populate the combo boxes that will be used as the editors for the JTable.

    When the user clicks on the insert button I wan't to add a new row with comboboxes of format and language data to the JTable


    So you add an empty row of data to the TableModel.

    When the user clicks on the cell the combo box drop down will display and the user can select an item. The item will then be stored in the TableModel.

    Below is my SSCCE showing the solution. I added the "getXXX(...)" methods to simulated getting data from the resource bundle and from the database.


     
    Robert Ingmarsson
    Ranch Hand
    Posts: 119
    2
    Netbeans IDE PHP Java
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    Best, Mr. Camick!

    Thank you so very much for your kind reply! I have adapted your code to my project but still nothing works. Somehow completely empty table cells appear when the user clicks the insert button. This is almost bizarre now since I've been struggling with this JTable object for quite some time now. Here I am posting what my SoundTrackPanel looks like. I'm sorry I haven't commented the code but hopefully it speaks for itself. I just don't understand those blank cells despite me having set up editors for the JTable. Oh, well here is the forementioned code:



    I hope I haven't been to much confusing for anyone this time.

    Best regards,
    Robert!
     
    Paul Clapham
    Marshal
    Posts: 24950
    61
    Eclipse IDE Firefox Browser MySQL Database
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    There's a lot of code there, but maybe not all of it?

    I found where you create the table model, it's called "model". But I don't see anywhere where you add rows to that table model. If you didn't add any rows then that would explain the blank cells you're seeing. Maybe you have a version of the original posted code which just inserts the values instead of the lists? If that's the case then I would start by removing your editors and see what the raw values are in the table cells.
     
    Rob Camick
    Rancher
    Posts: 3111
    26
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator

    I just don't understand those blank cells despite me having set up editors for the JTable.


    One of the first questions I asked you was if you understood what an editor is?

    A combo box editor just store possible values that can be added to the TableModel.

    It does NOT automatically add the data to the TableModel.

    A combo box editor replaces a basic text field editor.

    In a text field editor the user can type any value and it will be stored in the TableModel.

    The combo box editor provides a list of valid values that the user must select from.

    So an editor is used when data is entered (or changed) manually by the user.

    Somehow completely empty table cells appear when the user clicks the insert button.



    Did you execute my code? That is exactly how the code should work.

    You don't know in advance was values should be populated in each cell. It is up to the user to select a valid from each editor.

    To add data you had to:

    1. click on the "Add Row" button
    2. manually go to each cell to select a value

    I hope I haven't been to much confusing



    The code you posted is NOT an SSCCE. We can't compile or execute the code, so we can't help. We don't have access to your ResourceBundle or Database

    Again, forget about making your code dynamic. First get it working by hard coding the data. That is why I provided the simple getXXX() methods.

    I made it easy for you to test my code. If you want us to help make it easy for us to test your code.

    Part of creating the SSCCE is learning how to simplify the problem.
     
    Robert Ingmarsson
    Ranch Hand
    Posts: 119
    2
    Netbeans IDE PHP Java
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    Hi, again!

    Thank you so much for all the advice and hints on this post. I have solved the problem. It is working fine now. What I did was to remove a couple of lines from the actionEvent method in my action class. The method in that class looked like this before I chaged it:



    After I deleted theese lines



    Everything worked and the celleditors appeared in the previously empty cells. I wonder why this happened?



    @Mr Camick

    I know I am a terrible SSCCE-poster here. I must do better in the future. I'm truly sorry about this, maybe I'm just so impatient of me   But again thank you for the advice on posting here.

    This case is now solved I guess. Thank you all for your help and tips.

    Best regards,
    Robert!

     
    Rob Camick
    Rancher
    Posts: 3111
    26
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator

    Everything worked and the celleditors appeared in the previously empty cells. I wonder why this happened?


    Yes, it is the responsibility of the TableModel to invoke those methods. Application code should never invoke those methods.

    You originally added the editors to the TableColumnModel after you created the table (which is correct).

    The fireTableStructureChanged is how the TableModel tells the JTable that the structure has changed. For example the columns have changed.

    So, the JTable will recreate the TableColumnModel based on the current structure of the TableModel.

    So now you have a new TableColumnModel but no editors have been added to it.

    This is why you let the TableModel invoke the appropriate fireXXX() method.
     
    Robert Ingmarsson
    Ranch Hand
    Posts: 119
    2
    Netbeans IDE PHP Java
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator



    This is why you let the TableModel invoke the appropriate fireXXX() method.



    Mr. Camick. I don't quite understand. Was it wrong by me to delete the fireXXX() - methods or not ? Puzzled ...

    Regards,
    Robert!
     
    Rob Camick
    Rancher
    Posts: 3111
    26
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    It was correct to delete those two statements.

    Your custom application code in the ActionListener (or anywhere else) should NEVER invoke any of the fireXXX(...) methods.

    The DefaultTableModel WILL invoke a single fireXXX(...) method for you automatically depending on the change to the TableModel

    So, for example, the setRowCount(...) method will eventually invoke:


    Either of the above two fireXXX(...) methods will just tell the table the number of rows has changed, so the table can repaint itself to reflect this change.
     
    Robert Ingmarsson
    Ranch Hand
    Posts: 119
    2
    Netbeans IDE PHP Java
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    Thanks a lot! Now I get it!  

    Best wishes,
    Robert!
     
    Eat that pie! EAT IT! Now read this tiny ad. READ IT!
    Sauce Labs - World's Largest Continuous Testing Cloud for Websites and Mobile Apps
    https://coderanch.com/t/722574/Sauce-Labs-World-Largest-Continuous
    • Post Reply Bookmark Topic Watch Topic
    • New Topic
    Boost this thread!