是否可以将 JButton 包含在 JTable 中?
我有一个 JTable 来存储数据库查询的结果,到目前为止一切顺利。 我想要的是每个表中的最后一列有一个可单击的 JButton,它将打开该行中表示的对象的编辑屏幕,这意味着该按钮需要从它的表中了解表中第一列的详细信息自己的行(来自数据库的 ID)。
有什么建议吗? 我已经尝试过仅添加 JButtons,但当我尝试运行它时它们变成了文本。
I have a JTable that stores the results of a database query, so far so good. What I want is for the last column in each table to have a clickible JButton that will open the edit screen for the object represented in that row, and that means the button will need to know the details of the first column in the table from its own row (the ID from the database).
Any advice? I already tried just adding JButtons but they turned into Text when I tried to run it.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
与上面的教程相反,有一种方法可以做到这一点,无需复杂的定位数学、自定义鼠标侦听器和自定义表格模型。 相反,可以使用遵循此处描述的模式的单个简单自定义类来完成:
http://web.archive.org/web/20100623105810/http://ivolo.mit。 edu/post/A-Simple-Pattern-for-Embedding-Components-into-a-Swing-JTable.aspx
Contrary to the tutorial above, there is a way to do this without a complicated positioning math, custom mouse listeners, and custom table models. Instead, it can be done with a single simple custom class following the pattern described here:
http://web.archive.org/web/20100623105810/http://ivolo.mit.edu/post/A-Simple-Pattern-for-Embedding-Components-into-a-Swing-JTable.aspx
您可能还会发现我关于类似主题的教程(在本例中使用 JPanel)也很有帮助:JTable 中带有 JButton 的自定义 JPanel 单元
You may also find my tutorial on a similar subject (in this case, using a JPanel) helpful as well: Custom JPanel cell with JButtons in JTable
看一下 Sun 对
JTable
组件的介绍,特别是有关 编辑器和渲染器。 它讨论了替代CellRenderers
和
CellEditors
。 您需要做的是创建(或借用)一个ButtonCellRenderer
和一个ButtonCellEditor
,然后将它们应用到JTable
。 链接文章中的示例应该为您提供所需的所有信息。Take a look at Sun's introduction to the
JTable
component, specifically, the section about Editors and Renderers. It discusses the use of alternativeCellRenderers
, andCellEditors
. What you'd need to do is create (or borrow) aButtonCellRenderer
and aButtonCellEditor
and then apply them to the column in question in yourJTable
. The examples found in the linked articles should give you all the information you need.