This week's book giveaway is in the OO, Patterns, UML and Refactoring forum. We're giving away four copies of Refactoring for Software Design Smells: Managing Technical Debt and have Girish Suryanarayana, Ganesh Samarthyam & Tushar Sharma on-line! See this thread for details.
As the title says, I am trying to populate a JComboBox from a database table. I've read suggestions that I should implement my own ComboBoxModel. So far I have successfully done this. However, once the JComboBox is created the contents are static.
Now I want to modify my ComboBoxModel to respond dynamically to changes in the underlying table. What is a good way to go about this? Are there any design patterns that might apply (besides the obvious MVC that I'm already using).
Ultimately, the JComboBox will appear in a window that appears only when the user clicks on a menu item. The window includes other controls to enter data that will ultimately end up in a database table. My idea is to use JComboBox for any foreign keys in the table. This way the user sees a textual representation of the data rather than just the ID number that is really being used in the underlying table.
At the moment, I am using JOptionPane to display the window (using a JPanel as the "message"). One idea I have is to query the database each time the window opens. I see two problems here:
1) There is a performance hit since the user will most likely open the same window multiple times without changing the table that the foreign key refers to.
2) I'm not sure how to detect when JOptionPane displays the window since I don't think it's possible to register a WindowListener with it.
Does anyone have any suggestions what I can do here? Please let me know if I need to post any code or additional information about the design of my project.
Thanks for the suggestion. I am familiar with the Observer pattern. It is very similar (if not identical) to the Listeners that AWT uses for event handling. I think I can see how to implement the Observer interface in my DatabaseComboBoxModel. However, I'm still not sure how to implement the Observerable interface. How will the class that implements Observable be able to tell if the underlying table has changed? I have some budding ideas here, but I'm uncertain if I want to go in that direction since it seems like it will become overly complicated rather quickly.
I think for now, I'm going to have the ComboBox update its content every time it is displayed. I know this isn't the most efficient way to go, so if I have time later I'll look at the Observer pattern in more detail.