且构网

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

Java获取JTable值(每行)

更新时间:2023-12-03 16:35:40

getValueAt将为您返回单元格的值(以行/列为单位).除非您的表模型支持它,否则没有简单的方法(超出您的工作范围)在单个请求中获取整行.

getValueAt will return you the value of the cell (at row/col). Unless you're table model supports it, there is no convenient way (beyond what you are doing) to get the whole row in a single request.

此外,请记住,如果表已排序或过滤,则模型索引将与视图不匹配,您需要先使用 convertColumnIndexToModel

Also, remember, if the table is sorted or filtered, the model indices will not match the view, you need to convert them first, using convertRowIndexToModel and convertColumnIndexToModel

更新

唯一的解决方法是使用的表模型具有getRow(或等效方法).不知道如何将数据存储在表模型中,几乎不可能给出准确的答案,但是一般的想法是...

The only way around it is if the table model you're using has a getRow (or equivalent) method. Without know how you are storing the data in the table model it's next to near impossible to give an accurate answer, but a general idea would be...

public class MyAwesomeTableModel extends AbstractTableModel {
    // All the usual stuff...

    public MyRowData getRowAt(int index) { ... }
}

现在,MyRowData是您创建的表数据的任何实现. (***是)单个Object,或者在DefaultTableModel对象数组的情况下.

Now, MyRowData is what ever implementation of the table data you've created. It could be (preferably) a single Object or in the case of the DefaultTableModel an array of objects.

class GetTableValue implements ActionListener{
    public void actionPerformed(ActionEvent e){
        AbstractButton button = (AbstractButton)e.getSource();
        if(e.getActionCommand().equals(button.getActionCommand)){

            int row = table.convertRowIndexToModel(table.getSelectedRow());
            MyAwesomeTableModel model = (MyAwesomeTableModel)table.getModel();

            MyRowData data = model.getRowAt(row);
            JOptionPane.showMessageDialog(null, data);
        }
    }
}

这一切都取决于您实现TableModel的方式以及实现行数据的方式,但这就是一般的原则

This is all dependent on how you've implemented your TableModel and how you've implemented your row data, but that's the general jist