开发者

Get row by index from JTable

How to get row with index i froj JTable ? I looked at member functions but there is nothing like 开发者_如何学运维getRowAt . Can anybody help ?


There is no "row" object for a table, so nothing you could get with a getRow method.

You can ask getValueAt() to get the individual values, use it for each column and you have your complete row.


AFAIK, there is no such method. Write something like that:

public String[] getRowAt(int row) {
     String[] result = new String[colNumber];

     for (int i = 0; i < colNumber; i++) {
         result[i] = table.getModel().getValueAt(row, col);
     }

     return result;
}

P.S - Use table.getValueAt() if you want to respect a rearranged by the user column order.


I recommend to create a TableModel based on a list of POJOs.

It's then easy to add a method like:

   MyPojo getData(int index);

Have a look at this sample I wrote some time ago for a starting point: http://puces-samples.svn.sourceforge.net/viewvc/puces-samples/tags/sessionstate-1.0/sessionstate-suite/sessionstate-sample/src/blogspot/puce/sessionstate/sample/ParticipantTableModel.java?revision=13&view=markup


Try something like this

private void getIndexRow(){
    int i;
    int row = 0;
    int column = 0;
    i=Integer.parseInt(myTable.getValueAt(row,column).toString());
}


Another way of doing it is using the table model's getDataVector() method.

DefaultTableModel tm = (DefaultTableModel) table.getModel();
Vector<Object> rowData = tm.getDataVector().elementAt(rowIndex);


 private void jTable1MousePressed(java.awt.event.MouseEvent evt) {                                     

    int selectedRow;

    ListSelectionModel rowSM = jTable1.getSelectionModel();

      rowSM.addListSelectionListener(new ListSelectionListener()
      {
        @Override
        public void valueChanged(ListSelectionEvent e) 
        {
            ListSelectionModel lsm = (ListSelectionModel) e.getSource();

            selectedRow = lsm.getMinSelectionIndex();

            int numCols = jTable1.getColumnCount();

            model = (DefaultTableModel) jTable1.getModel();

            System.out.print(" \n row " + selectedRow + ":");

            for (int j = 0; j < numCols; j++) 
            {
                System.out.print(" " + model.getValueAt(selectedRow, j));
            }

        }
    });
}

Using this you can get value of whole row where u click on particular row.


This function is working well for me.

private Object[] getRowAt(int row, DefaultTableModel model) {
    Object[] result = new Object[model.getColumnCount()];

     for (int i = 0; i < model.getColumnCount(); i++) {
         result[i] = model.getValueAt(row, i);
     }

     return result;
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜