JComboBox 帮助从数据库中删除数据
我在数据库 employee
中有一个表,由两列 ID 和 NameLastName 组成。
我到达将第二列中的数据添加到 JComboBox,就像下面的快照中一样!
现在如何从数据库中删除 JComboBox 中选定的员工?
我想添加名称类似于 I122-Name
的 ID 并使用 split 方法提取 ID,但我不想显示 ID。
有什么方法可以将 JComboBox 中的每个名称与包含员工 ID 的隐藏值关联起来吗?
I have a table in database employee
composed by two columns ID and NameLastName.
I arrived to add data in the second column to a JComboBox like in the snapshot down!
Now how can I do to delete the selected employee in the JComboBox from DB?
I thought to add the ID with name like this I122-Name
and use split method to extract the ID but I don't want to show the ID.
Is there any way to associate with each name in the JComboBox a hidden value that contains the employee ID?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您可以尝试这样做:
创建一个包含字段名称和 id 的 Employee 类,然后创建一个实现
ListCellRenderer
并扩展JLabel
的类。将此类作为渲染器添加到 JComboBox。现在您可以在 JLabel 中将名称设置为文本。现在,当您访问comboBox的元素时,它会返回您JLabel,您可以从您在JLabel中设置的位置获取名称作为可见值和id作为隐藏值。JComboBox 的方法
getSelectedItem()
返回一个对象,该对象可以转换为放置在组合框中的任何对象。要获取用于渲染项目的组件,请调用 getRenderer()。注意:- 您可以使用 JLabel 以外的其他组件。
演示:-
现在,您想要将项目添加到组合框的地方,请使用
combo.addItem(empObject);
。它将在组合框中显示员工的姓名,当您执行 getSelectedItem() 时,它将返回员工对象,您将获得属于该 emp 对象的姓名和 ID。You can try this:
Make an Employee class with field name and id then make a class which implements
ListCellRenderer
and extendsJLabel
. Add this class as a Renderer to your JComboBox. Now you can set Name as a text in JLabel.Now when ever you access comboBox's element it will return you JLabel and you can get name as visible value and id as hidden value from where you have set in JLabel.JComboBox's method
getSelectedItem()
returns an Object that can be cast to whatever Object was placed in the combobox. To get the component used to render the items, callgetRenderer()
.Note:- You can use other component then JLabel.
A demo:-
Now where you want to add item to comboBox use
combo.addItem(empObject);
. It will display name of employee in comboBox and when you dogetSelectedItem()
it will return you the employee object and you will get name and id both belongs to that emp object.这个问题已经收到了 2 个很好的答案,但我想添加第三个答案,如果只是为了解决是否显示 ID 的问题(这不是问题的一部分,但应该是)。
屏幕截图
您要解雇哪个约翰·史密斯?
SackEmployee.java
> 输入/输出
This question has already received 2 good answers, but I wanted to add this 3rd one if only to address the question of whether to show the ID (which was not part of the question, but should have been).
Screen Shot
Which John Smith are you going to fire?
SackEmployee.java
E.G. I/O
这是删除数据库中整行的简单代码。
here is simple code that will delete entire row in database.