将数据库列绑定到java jComboBox和JList
好吧,假设我有一个包含两列的数据库表 - 一列“姓名”,另一列“年龄”,表中有 40 多个姓名及其各自的年龄。我希望这些名称在 jList/jComboBox 中列出,并且我还希望能够单击 jList/jComboBox 中的名称并将其各自的年龄显示在(例如)文本框中。我是否必须通过简单地编写一个代码来解决这个问题,该代码从表中选择所有名称并填充 jList/jComboBox,然后编写另一个代码来获取所选名称,将其放入 sql 语句中,找到匹配的年龄并将其发送到文本框,或者是否有某种 VB 式的列到组合框/列表绑定,我可以利用它来解决这个问题?
Ok, say I have a database table with two columns - one "Name", the other "Age", and there are over 40 names and their respective ages in the table. I want these names to be listed out in a jList/jComboBox, and also I want to be able to click on a name in the jList/jComboBox and have its respective age appear in - say - a text box. Do I have to go about this by simply writing a code that selects all the names from the table and populates the jList/jComboBox and then another code that takes the selected name, puts it in an sql statement, finds the matching age and sends it to a text box, OR is there some kind of a VB-esque column-to-comboBox/List-binding that I can utilise to go about this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
对于仅 40 个姓名-年龄组合,我只需查询数据库一次,并将此信息存储在
Map
中。然后,您可以在选择名称时查询地图,并更新年龄文本字段。这比每次更改选择时运行 SQL 查询要快得多。For only 40 name-age combinations, I would just query the database once, and store this information in a
Map
. Then you can just query the map when a name is selected, and update the age textfield. This will go a lot faster then running SQL queries each time the selection has been changed.您必须为摆动元素设置模型,并根据一处的更改将数据更新到其他实现侦听器。
看看这个
在 swing 中绑定组合框
You have to set Model for your swing elements and for updating data based on changes at one place to other implement Listeners.
Have a look at this
Binding comboboxes in swing
创建一个存储名称和年龄值的自定义对象,并将该对象添加到组合框。然后,当您选择一个项目时,您可以访问这两个值。
例如: 如何使用 Map 元素作为 JComboBox 的文本
Create a custom object that stores both the name and age values and add this object to the combobox. Then when you select an item you have access to both values.
For example: How to use Map element as text of a JComboBox