0

The user has chosen value of a field in a row,How i can get value of id field in row that chosen? For example,user select value of name field in row 2,I want understand the value of id field in row 2.How should write in TableModelListener?

public class Main {
    public static DefaultTableModel model;

    public static void main(String[] args) throws Exception {
        model = new DefaultTableModel();
        JFrame frame = new JFrame("Creating a Scrollable JTable!");
        JPanel panel = new JPanel();
        model.addColumn("id");
        model.addColumn("name");
        model.addColumn("family");
        Class.forName("oracle.jdbc.driver.OracleDriver");
        java.sql.Connection con = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe", "SYSTEM", "1234");
        PreparedStatement st = con.prepareStatement("select * from person");
        ResultSet r = st.executeQuery();
        while (r.next()) {
            model.addRow(new Object[]{r.getString("id"), r.getString("name"), r.getString("family")});
        }
        st.close();
        con.close();
        model.addTableModelListener(new TableModelListener() {
            public void tableChanged(TableModelEvent e) {
                System.out.println(model.getValueAt(e.getFirstRow(), e.getColumn()));
            }
        });
        JTable table = new JTable(model);
        frame.add(panel);
        panel.add(table);
        frame.setVisible(true);
    }
}
Cœur
  • 37,241
  • 25
  • 195
  • 267
HFDev
  • 131
  • 2
  • 4
  • 11

2 Answers2

2

Use ListSelectionListener rather than a TableModelListener:

    table.getSelectionModel().addListSelectionListener(new ListSelectionListener() {
        public void valueChanged(ListSelectionEvent e) {
            if (e.getValueIsAdjusting()) return;
            int selectedRow = table.convertRowIndexToModel(table.getSelectedRow());
            int selectedColumn = table.convertColumnIndexToModel(0);

            String selectedId = (String)model.getValueAt(selectedRow, selectedColumn);
            System.out.println(selectedId);
        }
    });
Reimeus
  • 158,255
  • 15
  • 216
  • 276
  • You should use JTable.convertRowIndexToModel() (and do the same for the column). Else, if the table is sorted or if the columns are rearranged, it won't lead to the correct value in the model. – JB Nizet Jul 28 '12 at 12:25
  • You picked the wrong one. `getSelectedRow()` returns a view index. You must convert this view index to a model index. Once you have the model index, you can ask the model for the row at this model index. The same goes for columns, of course, except the method is `convertColumnIndexToModel()` and not `convertRowIndexToModel()`. – JB Nizet Jul 28 '12 at 12:35
1

When id column index is 0 : System.out.println(model.getValueAt(e.getFirstRow(),0))

HFDev
  • 131
  • 2
  • 4
  • 11