简体   繁体   English

AbstractTableModel和单元格编辑器

[英]AbstractTableModel and cell editor

The example i have found: http://www.java2s.com/Code/Java/Swing-Components/ButtonTableExample.htm show how to create a JTable with specified column (button). 我找到的示例: http//www.java2s.com/Code/Java/Swing-Components/ButtonTableExample.htm显示如何使用指定的列(按钮)创建JTable。 It works properly, but the my problem is, that i need to use AbstractTableModel instead of DefaultTableModel (as at the example shows). 它工作正常,但我的问题是,我需要使用AbstractTableModel而不是DefaultTableModel(如示例所示)。

So i created my own TableModel, which extends AbstractTableModel: 所以我创建了自己的TableModel,它扩展了AbstractTableModel:

public class TableModel extends AbstractTableModel { //..
}

and replaced: 并替换:

 DefaultTableModel dm = new DefaultTableModel();
dm.setDataVector(new Object[][] { { "button 1", "foo" },
    { "button 2", "bar" } }, new Object[] { "Button", "String" });

JTable table = new JTable(dm);

for: 对于:

JTable table = new JTable(new TableModel());

And then nothing happens, when i will click button at some row. 然后没有任何反应,当我点击某一行按钮时。 Any suggestions? 有什么建议么?

Make sure you override AbstractTableModel.isCellEditable method to return true for the column with the button otherwise the editor will not be triggered. 确保重写AbstractTableModel.isCellEditable方法以使用按钮为列返回true ,否则将不会触发编辑器。 This method by default returns false . 默认情况下,此方法返回false

Also, make sure you override getColumnName() to return proper name since the sample that you linked tries to find a column with name "Button" to setup the editor. 此外,请确保覆盖getColumnName()以返回正确的名称,因为您链接的示例尝试查找名为“Button”的列来设置编辑器。

You may find a Table Button Column implementation by @camickr useful. 你可能会发现@camickr对Table Button Column的实现非常有用。

This demo model works OK with the editor and the renderer from the linked sample: 此演示模型可以与链接样本中的编辑器和渲染器一起使用:

public class DemoTableModel extends AbstractTableModel {
    @Override
    public boolean isCellEditable(int rowIndex, int columnIndex) {
        return (columnIndex == 0);
    }

    @Override
    public int getRowCount() {
        return 2;
    }

    @Override
    public int getColumnCount() {
        return 2;
    }

    @Override
    public String getColumnName(int columnIndex) {
        switch (columnIndex) {
        case 0:
            return "Button";
        case 1:
            return "Value";
        }
        return null;
    }

    @Override
    public Object getValueAt(int rowIndex, int columnIndex) {
        switch (columnIndex) {
        case 0:
            return "Button";
        case 1:
            return "Value";
        }
        return null;
    }
}

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

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