There is a table displaying data from the database. The user selects any line, one, in the JTable and the data in this line is alternately displayed on the screen (using System.out.println() ). Tell me, please, how can this be implemented?

DataBaseTableModel:

 public class DataBaseTableModel extends AbstractTableModel { Connection connection; Statement statement; ResultSet resultSet; ResultSetMetaData metaData; String[] columnNames = {}; Vector rows = new Vector(); public DataBaseTableModel(String url, String driverName, String user, String passwd) { try { Class.forName ("oracle.jdbc.OracleDriver"); System.out.println("Opening db connection"); connection = DriverManager.getConnection( url, user, passwd); statement = connection.createStatement(); }catch (ClassNotFoundException ex) { System.err.println("Cannot find the database driver classes."); System.err.println(ex); } catch (SQLException ex) { System.err.println("Cannot connect to this database."); System.err.println(ex); } } @Override public int getRowCount() { return rows.size(); } @Override public int getColumnCount() { return columnNames.length; } @Override public String getColumnName(int column) { if (columnNames[column] != null) { return columnNames[column]; } else { return ""; } } @Override public Object getValueAt(int aRow, int aColumn) { Vector row = (Vector)rows.elementAt(aRow); return row.elementAt(aColumn); } public void close() throws SQLException { System.out.println("Closing db connection"); resultSet.close(); statement.close(); connection.close(); } @Override public boolean isCellEditable(int row, int column) { try { return metaData.isWritable(column+1); } catch (SQLException e) { return false; } } @Override public Class getColumnClass(int column) { int type; try { type = metaData.getColumnType(column+1); } catch (SQLException e) { return super.getColumnClass(column); } switch(type) { case Types.CHAR: case Types.VARCHAR: case Types.LONGVARCHAR: return String.class; case Types.BIT: return Boolean.class; case Types.TINYINT: case Types.SMALLINT: case Types.INTEGER: return Integer.class; case Types.BIGINT: return Long.class; case Types.FLOAT: case Types.DOUBLE: return Double.class; case Types.DATE: return java.sql.Date.class; default: return Object.class; } } public String dbRepresentation(int column, Object value) { int type; if (value == null) { return "null"; } try { type = metaData.getColumnType(column+1); } catch (SQLException e) { return value.toString(); } switch(type) { case Types.INTEGER: case Types.DOUBLE: case Types.FLOAT: return value.toString(); case Types.BIT: return ((Boolean)value) ? "1" : "0"; case Types.DATE: return value.toString(); default: return "\""+value.toString()+"\""; } } @Override public void setValueAt(Object value, int row, int column) { try { String tableName = metaData.getTableName(column+1); if (tableName == null) { System.out.println("Table name returned null."); } String columnName = getColumnName(column); String query = "update "+tableName+ " set "+columnName+" = "+dbRepresentation(column, value)+ " where "; for(int col = 0; col < getColumnCount(); col++) { String colName = getColumnName(col); if (colName.equals("")) { continue; } if (col != 0) { query = query + " and "; } query = query + colName +" = "+ dbRepresentation(col, getValueAt(row, col)); } System.out.println(query); System.out.println("Not sending update to database"); statement.executeQuery(query); } catch (SQLException e) { System.err.println("Update failed"); } Vector dataRow = (Vector)rows.elementAt(row); dataRow.setElementAt(value, column); } public void executeUpdate(String query) { if (connection == null || statement == null) { System.err.println("There is no database to execute the query."); return; } try { resultSet = statement.executeQuery(query); metaData = resultSet.getMetaData(); int numberOfColumns = metaData.getColumnCount(); columnNames = new String[numberOfColumns]; for(int column = 0; column < numberOfColumns; column++) { columnNames[column] = metaData.getColumnLabel(column+1); } rows = new Vector(); while (resultSet.next()) { Vector newRow = new Vector(); for (int i = 1; i <= getColumnCount(); i++) { newRow.addElement(resultSet.getObject(i)); } rows.addElement(newRow); } fireTableChanged(null); } catch (SQLException ex) { System.err.println(ex); } }} 

JRanel with a table in the frame:

 dbtm = new DataBaseTableModel( "jdbc:oracle:thin:@//" + host + ":" + port + "/" + serviceName + "", "oracle.jdbc.OracleDriver", user, passwd); dbTablePanel = new JPanel(new GridBagLayout()); dbTable = new JTable(dbtm); dbTableScrollPane = new JScrollPane(dbTable, ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS, ScrollPaneConstants.HORIZONTAL_SCROLLBAR_ALWAYS); dbTable.setAutoResizeMode(JTable.AUTO_RESIZE_OFF); dbTableScrollPane.setPreferredSize(new Dimension(420, 200)); dbtm.executeUpdate(DEFAULT_QUERY); dbTable.getTableHeader().setReorderingAllowed(false);//запрещает перемещать столбцы dbTable.addMouseListener(new MouseAdapter() { @Override public void mouseClicked(MouseEvent e) { if (e.getClickCount() == 2) {//двойной шелчок int row = dbTable.rowAtPoint(e.getPoint()); //путь попроще без selectionMode if (row > -1) { int realRow = dbTable.convertRowIndexToModel(row); System.out.println(realRow);//номер строки из модели данных //здесь должна быть выборка объекта из модели по номеру строки и его отображение } } } }); dbTablePanel.add(dbTableScrollPane, new GridBagConstraints(0, 0, 3, 1, 2, 1, GridBagConstraints.NORTH, GridBagConstraints.BOTH, new Insets(1, 1, 1, 1), 0, 0)); 

    2 answers 2

    First, you must have a model in which the getValueAt method is redefined . Therefore, you need to catch the selection action and find the index of the selected row. You set the selection model with setSelectionMode . Constants here . With getSelectedRows () you get the indices of the selected rows. Next, convert them to the original (if there is sorting) using convertRowIndexToView . I do not recommend catching multiple sampling actions, you will get confused immediately. But you can quite easily catch clicking on the left mouse button:

     table.addMouseListener(new MouseAdapter() { @Override public void mouseClicked(MouseEvent e) { if (e.getClickCount() == 2) //двойной шелчок { int row = table.rowAtPoint(e.getPoint()); //путь попроще без selectionMode if (row > -1) { int realRow = table.convertRowIndexToModel(row)); //номер строки из модели данных //здесь должна быть выборка объекта из модели по номеру строки и его отображение } } } }); 
    • @LEQADA Question changed, added its code - Alexandr Semenets
    • @ Sasha Semenets, this answer is not mine. But what he did not solve the problem? - LEQADA
    • decided, thank you very much) - Alexandr Semenets
    • @LEQADA, and how can the received data from a string be moved to another class and assigned for example JTextField? - Alexandr Semenets
    • @SashaSemenets, in another class, make a String variable and send the value to the setter. And then output to JTextField - LEQADA

    I decided everything like this:

     if(currentQuery == "SELECT deptno id_подразделения, dname имя_подразделения, loc местоположение FROM SCOTT.DEPT ORDER BY deptno"){ dbTable.addMouseListener(new MouseAdapter() { @Override public void mouseClicked(MouseEvent e) { if (e.getClickCount() == 1) {//одинарный шелчок int row = dbTable.rowAtPoint(e.getPoint()); int column = dbTable.columnAtPoint(e.getPoint()); //путь попроще без selectionMode if (row > -1) { int realRow = dbTable.convertRowIndexToModel(row); int realColumn = dbTable.convertColumnIndexToModel(column); System.out.println("[" + realRow + "],[" + realColumn + "]"); Object varDeptno = dbtm.getValueAt(realRow, 0); Object varDname = dbtm.getValueAt(realRow, 1); Object varLoc = dbtm.getValueAt(realRow, 2); System.out.println(varDeptno); System.out.println(varDname); System.out.println(varLoc); //номер строки из модели данных //здесь должна быть выборка объекта из модели по номеру строки и его отображение } } } }); } else if(currentQuery == "SELECT EMPNO ID_СОТРУДНИКА, ENAME ФАМИЛИЯ, JOB ДОЛЖНОСТЬ, MGR ID_РУКОВОДИТЕЛЯ, HIREDATE ДАТА_ПРИЕМА_НА_РАБОТУ, SAL ЗАРПЛАТА, COMM КОМИСИОННЫЕ," + " DEPTNO НОМЕР_ПОДРАЗДЕЛЕНИЯ FROM SCOTT.EMP ORDER BY EMPNO"){ dbTable.addMouseListener(new MouseAdapter() { @Override public void mouseClicked(MouseEvent e) { if (e.getClickCount() == 1) {//одинарный шелчок int row = dbTable.rowAtPoint(e.getPoint()); int column = dbTable.columnAtPoint(e.getPoint()); //путь попроще без selectionMode if (row > -1) { int realRow = dbTable.convertRowIndexToModel(row); int realColumn = dbTable.convertColumnIndexToModel(column); System.out.println("[" + realRow + "],[" + realColumn + "]"); Object varEmpno = dbtm.getValueAt(realRow, 0); Object varEname = dbtm.getValueAt(realRow, 1); Object varJob = dbtm.getValueAt(realRow, 2); Object varMgr = dbtm.getValueAt(realRow, 3); Object varHiredate = dbtm.getValueAt(realRow, 4); Object varSal = dbtm.getValueAt(realRow, 5); Object varComm = dbtm.getValueAt(realRow, 6); Object varDeptno = dbtm.getValueAt(realRow, 7); System.out.println(varEmpno); System.out.println(varEname); System.out.println(varJob); System.out.println(varMgr); System.out.println(varHiredate); System.out.println(varSal); System.out.println(varComm); System.out.println(varDeptno); //номер строки из модели данных //здесь должна быть выборка объекта из модели по номеру строки и его отображение } } } }); } else if (currentQuery == "SELECT GRADE НОМЕР_РАЗРЯДА, LOSAL НИЖНЯЯ_ГРАНИЦА_ОКЛАДА," + " HISAL ВЕРХНЯЯ_ГРАНИЦА_ОКЛАДА FROM SCOTT.SALGRADE ORDER BY GRADE") { dbTable.addMouseListener(new MouseAdapter() { @Override public void mouseClicked(MouseEvent e) { if (e.getClickCount() == 1) {//одинарный шелчок int row = dbTable.rowAtPoint(e.getPoint()); int column = dbTable.columnAtPoint(e.getPoint()); //путь попроще без selectionMode if (row > -1) { int realRow = dbTable.convertRowIndexToModel(row); int realColumn = dbTable.convertColumnIndexToModel(column); System.out.println("[" + realRow + "],[" + realColumn + "]"); Object varGrade = dbtm.getValueAt(realRow, 0); Object varLosal = dbtm.getValueAt(realRow, 1); Object varHisal = dbtm.getValueAt(realRow, 2); System.out.println(varGrade); System.out.println(varLosal); System.out.println(varHisal); //номер строки из модели данных //здесь должна быть выборка объекта из модели по номеру строки и его отображение } } } }); } else { dbTable.addMouseListener(new MouseAdapter() { @Override public void mouseClicked(MouseEvent e) { if (e.getClickCount() == 1) {//одинарный шелчок int row = dbTable.rowAtPoint(e.getPoint()); int column = dbTable.columnAtPoint(e.getPoint()); //путь попроще без selectionMode if (row > -1) { int realRow = dbTable.convertRowIndexToModel(row); int realColumn = dbTable.convertColumnIndexToModel(column); System.out.println("[" + realRow + "],[" + realColumn + "]"); Object varDeptno = dbtm.getValueAt(realRow, 0); Object varDname = dbtm.getValueAt(realRow, 1); Object varLoc = dbtm.getValueAt(realRow, 2); System.out.println(varDeptno); System.out.println(varDname); System.out.println(varLoc); //номер строки из модели данных //здесь должна быть выборка объекта из модели по номеру строки и его отображение } } } }); }