0

I have fetched data from selected row of a table in swing now I need to set those data in different text fields.

I have added mouse listener.

m_tblHistory.addMouseListener(new MouseAdapter() {
        @Override
        public void mouseClicked(MouseEvent e) {
            onSelectedRow();
            super.mouseClicked(e);
        }
    });    

method onSelectedRow();

@SuppressWarnings({ "unchecked", "rawtypes" })
protected void onSelectedRow() {
    DefaultTableModel model = (DefaultTableModel) m_tblHistory.getModel();

    int intRow = m_tblHistory.getSelectedRow();
    int intColumn = m_tblHistory.getColumnCount();

    Vector vecRow = new Vector();
    for (int i = 0; i < intColumn; i++) {
        vecRow.add(model.getValueAt(intRow, i));
        System.out.println("aaaaa = " + m_tblHistory.getModel().getColumnName(i));
    }

    onSetData(vecRow);
}

Now in onSetData method I need to set data to different textfields. One way is I can hard code it to get data corresponding to individual id or is there any other way to do this or is there?

Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
Akshat
  • 3
  • 1
  • 1
  • 3

1 Answers1

0

I have added mouse listener.

MouseListener is not the right choice to listen to selection changes. You should attach a ListSelectionListener to the table's ListSelectionModel if you want to listen for rows selection changes:

JTable table = new JTable();
table.getSelectionModel().addListSelectionListener(new ListSelectionListener() {
     @Override
     public void valueChanged(ListSelectionEvent e) {
         // your code here
     }
 });

See more in Users Selections section of How to Use Tables tutorial.

One way is I can hard code it to get data corresponding to individual id or is there any other way to do this or is there?

Yes there is another better and more elegant way: implement your own TableModel. You can use AbstractTableModel as base. See Creating a Table Model

dic19
  • 17,821
  • 6
  • 40
  • 69
  • thanks, ListSelectionListener also worked, I am facing new problem after refreshing the table that is clearing the data and adding new rows, it throws ArrayIndexOutOfBound Exception. How to overcome this issue? PS : if I use MouseAdapter event this works perfectly. – Akshat Sep 23 '14 at 18:54
  • You are welcome :) It sounds like you are attempting to access an invalid row/column index in your code, for some reason. Please consider ask a new question with your code and most important the [full stack trace](http://stackoverflow.com/questions/3988788/what-is-a-stack-trace-and-how-can-i-use-it-to-debug-my-application-errors). @Akshat – dic19 Sep 23 '14 at 20:05