java 如何将 jcheckbox 放入表格单元格?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2439875/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
how to put jcheckbox to table cell?
提问by joseph
I cannot put jChceckBox to jTable cell. More likely I can put checkBox to table, but when I run module with that table, the cell where should be checkBox shows text "true" or "false". The behaviors of that cell are the same like checkbox, but it shows text value instead of checkbox.
我不能将 jChceckBox 放到 jTable 单元格中。更有可能我可以将 checkBox 放到表格中,但是当我使用该表格运行模块时,应该是 checkBox 的单元格显示文本“true”或“false”。该单元格的行为与复选框相同,但它显示文本值而不是复选框。
Here is the code.
这是代码。
DefaultTableModel dm = new DefaultTableModel();
dm.setDataVector(new Object[][]{{"dd", "Edit", "Delete"},
{"dd","Edit", "Delete"}},
new Object[]{"Include","Component", "Ekvi"});
jTable1 = new javax.swing.JTable();
jTable1.setModel(dm);
JCheckBox chBox=new JCheckBox();
jTable1.getColumn("Include").setCellEditor(new DefaultCellEditor(chBox));
jScrollPane1.setViewportView(jTable1);
采纳答案by Hyman
The cell editor defines how the data inside your table behave according to editing its value, what you need is the right TableCellRendererto properly display the checkbox inside the cell:
单元格编辑器根据编辑其值定义表格中的数据的行为方式,您需要的是TableCellRenderer正确显示单元格内的复选框的权利:
final JCheckBox checkBox = new JCheckBox();
jTable1.getColumn("Include").setCellRenderer(new DefaultTableCellRenderer() {
public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column)
{
check.setSelected(((Boolean)value).booleanValue()) ;
return check;
}
});
回答by camickr
Read the JTable API and follow the link to the Swing tutorial on "How to Use Table" for a working example.
阅读 JTable API 并按照有关“如何使用表”的 Swing 教程的链接获取工作示例。
Basically you store Boolean values in the TableModel, then you override the getColumnClass() method to return the class of each colulmn and the table will choose the appriate renderer and editor.
基本上,您将布尔值存储在 TableModel 中,然后您覆盖 getColumnClass() 方法以返回每个列的类,并且表将选择适当的渲染器和编辑器。

