且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

需要在JTable中动态添加JCheckBox

更新时间:2023-12-03 17:40:46

感谢您的编辑,但您仍可能想向我们展示更多内容,并告诉我们您当前代码引起的错误.

Thank you for your edits, but you still might want to show us more and tell us what errors your current code is causing.

关于"CheckBoxRenderer"类,您不需要它.请阅读JTable教程,您可以在此处找到.在那里,您将需要做的就是重写表模型的getColumnClass方法,为感兴趣的列返回Boolean.class,以使其显示复选框.

Regarding your "CheckBoxRenderer" class, you don't need this. Please read the JTable tutorial which you can find here. There you will see that all you need to do is override your table model's getColumnClass method to return Boolean.class for the column of interest for it to display checkboxes.

好运.

编辑1
行渲染器"又是什么,它有什么作用?要将信息添加到您的JTable中,您必须在其模型中添加行,而我看不到您的代码会这样做.看看DefaultTableModel API,您将在其中看到addRow(...)方法,这可能会对您有很大帮助.或者使用您的数据数组创建一个新的DefaultTableModel对象.实际上,这样做可能更好,因为您可以重写其getColumnClass()方法以为需要放置复选框的列返回Boolean.

Edit 1
Also what is with "row renderer", and what purpose does it serve? To add information to your JTable, you must add rows to its model, and I don't see your code doing that. Have a look at the DefaultTableModel API where you'll see the addRow(...) method which may help you a great deal. Either that or create a new DefaultTableModel object with your data arrays. In fact, this is probably better since you can then override its getColumnClass() method to return Boolean for the column that needs to dislay check boxes.

编辑2
另外,由于您将其声明为一维数组并将其初始化为二维数组,因此无法编译.

Edit 2
Also this won't compile since you're declaring it as a one dimensional array and initializing it as a 2-dimensional array.:

Object [] data = new Object[][]

考虑执行以下操作:

  • 创建一个二维对象数组,并保存模型的数据.数组的第一个索引是JTable中显示的行数,第二个索引是列数.
  • 使用布尔值填充每个列的位置.
  • 创建一个新的DefaultTableModel对象,该对象将覆盖getColumnClass(...),并使该对象返回Boolean.class,该列用于保存布尔值并需要显示复选框.
  • 为它提供一个构造函数,该构造函数允许您传递2D对象数组,也可以为列标题传递一个String数组.构造函数的第一行应该是对超级构造函数的调用,您将需要将数组参数传递给该调用.
  • 在procTableCk对象上调用setModel,并传入刚刚创建的模型.