Data extracted from selected line JTable



  • There is a table showing the OBD data. The user shall distinguish any line, one, in JTable and the data in this line shall be alternately placed on the screen (used with the help of System.out.println()) Can you tell me, please, how can this be realized?

    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 &lt; numberOfColumns; column++) {
            columnNames[column] = metaData.getColumnLabel(column+1);    
        }
    
        rows = new Vector();                                            
        while (resultSet.next()) {                                      
            Vector newRow = new Vector();                               
            for (int i = 1; i &lt;= getColumnCount(); i++) {       
            newRow.addElement(resultSet.getObject(i));      
            }                                                           
            rows.addElement(newRow);                            
        }
        fireTableChanged(null);                                        
    }
    catch (SQLException ex) {
        System.err.println(ex);
    }
    

    }}

    JRanel with the table in the frime:

    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 &gt; -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));
    



  • First, you have to have a model that redefines the method. https://docs.oracle.com/javase/6/docs/api/javax/swing/table/TableModel.html#getValueAt%28int,%20int%29 ♪ Consequently, you need to catch the release and find an index of the line. Set up a model of choice with help. https://docs.oracle.com/javase/6/docs/api/javax/swing/JTable.html#setSelectionMode%28int%29 ♪ Constants https://docs.oracle.com/javase/6/docs/api/constant-values.html#javax.swing.ListSelectionModel.SINGLE_SELECTION ♪ Help https://docs.oracle.com/javase/6/docs/api/javax/swing/JTable.html#getSelectedRows%28%29 You're getting indexes of the lines. Then you turn them into reference (if there is a sorting) with help. https://docs.oracle.com/javase/6/docs/api/javax/swing/JTable.html#convertRowIndexToView%28int%29 ♪ I don't recommend taking the multiple sample, you'll get confused. But it's quite easy to get the pressure on the left button of mice:

    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)); //номер строки из модели данных
                //здесь должна быть выборка объекта из модели по номеру строки и его отображение
    
        }
    }
    

    }
    });




Suggested Topics

  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2