简体   繁体   English

将JButton添加到JTable单元格

[英]Add a JButton to a JTable cell

I have a JTable with a model created like this : 我有一个JTable ,其模型创建如下:

DefaultTableModel model = new DefaultTableModel(new Object[][] {},new String[] {"Col1", "Col2", "Col3", "Col4", "Col5", "Col6", "Col7", "Col8"}) {
@Override
public Class<?> getColumnClass(int column) {
switch (column) {
case 0: return ImageIcon.class;
case 7: return JButton.class;
default: return String.class;
}
}
};
table = new JTable(model);

But when I use the addRow method, My ImageIcon appears properly but not the JButton . 但是,当我使用addRow方法时,My ImageIcon正确显示,但JButton不会。 In fact, I get something like javax.Swing.JButt... instead of the JButton ! 实际上,我得到的东西类似于javax.Swing.JButt...而不是JButton

When you are adding a new row, it is being populated correctly. 当您添加新行时,它是正确填充的。 (You can see the ImageIcon ). (您可以看到ImageIcon )。 So, the JButton object is also being inserted correctly. 因此, JButton对象也可以正确插入。

The only difference here, JTable does not know how to display it or handle events on it. 这里唯一的区别是, JTable不知道如何显示它或处理事件。

That is why JTable calls toString() method on JButton and displays the text (as you mentioned). 这就是JTableJButton上调用toString()方法并显示文本(如您所述)的原因。

javax.swing.JButt...... javax.swing.JButt ......


To overcome this problem, we need to supply two additional objects to the JTable . 为了克服这个问题,我们需要向JTable提供两个额外的对象。

  1. TableCellEditor to handle events. TableCellEditor处理事件。
  2. TableCellRenderer to handle painting. TableCellRenderer处理绘画。

You can find additional information about implementation details here : How to use custom JTable cell editor and cell renderer 您可以在此处找到有关实现细节的其他信息: 如何使用自定义JTable单元格编辑器和单元格渲染器

Hope this helps. 希望这可以帮助。
Good luck. 祝好运。


Edit in response to the comment. 根据评论进行编辑。

table.getColumnModel().getColumn(7).setCellRenderer(new MyCellRenderer());
// Put painting logic in MyCellRenderer class.

This way you can assign different renderer objects to different columns. 这样,您可以将不同的渲染器对象分配给不同的列。

The problem is that JTable doesn't support a button renderer or editor. 问题是JTable不支持按钮渲染器或编辑器。 You can overcome it using a custom cell editor, ButtonColumn : http://tips4java.wordpress.com/2009/07/12/table-button-column/ 您可以使用自定义单元格编辑器ButtonColumn克服它: http : //tips4java.wordpress.com/2009/07/12/table-button-column/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM