How to get data from a JTable for storage in a database?

2

I'm developing a project called Menu List with a MySQL database and in Java on NetBeans, with an added library of MySQL-Connector-Java. I want the names of the selected products, the quantity of products, and the total price of the Cardapio.java template to be stored and printed as text in a database by the Cadastro.java template, connecting with the Conexão.java and Teste.java templates %.

I have not yet solved two errors in Java.

Follow the full source code for Cardapio.java :

package br.com.cardapio.view;

/**
-- Autor: Gustavo Benedito Costa
-- Curso: Ciência da Computação
-- Disciplina: Análise de Programação Orientada a Objectos
-- Professor: Carlos Feichas
-- Ano: 2ºA
-- Semestre: 3º Semestre

***GEORGIANO*** — ***GEORGIAN*** — ***ქართული***
-- ავტორი: გუშტავუ ბენედიტუ კოსტა
-- კურსი: კომპიუტერული მეცნიერება
-- დისციპლინური: ორიენტირებული პროგრამირება ანალიზი ობიექტები
-- მასწავლებელი: კარლოს
-- წელი: მეორე წელს A
-- სემესტრი: მესამე სემესტრი
 **/

import java.awt.Color;
import java.awt.Font;
import java.sql.Array;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;
import javax.swing.JSpinner;
import javax.swing.table.DefaultTableModel;
import java.awt.event.ActionListener;
import java.sql.SQLException;
import java.awt.event.ActionEvent;
import br.com.control.Cadastro;

public class Cardápio extends javax.swing.JFrame {

    double valorTotal=0;    //valor dos pedidos
    DefaultTableModel tab1; // model da tabela Lanches
    DefaultTableModel tab2; //  model da tabela Lanches Selecionados

    public Cardápio() {
        initComponents();
        Tprodutos(); // inicializa a tabela Lanches
    }

    public void Tprodutos(){
        ArrayList<String> t = new ArrayList(); // lista dos produtos
        ArrayList<String> s = new ArrayList(); // lista dos preços

        t.add("X-salada");t.add("Mini pizza");t.add("Hamburguer");t.add("Suco de laranja"); t.add("Cappuccino"); // inserção de valores nas listas
        s.add("4.00");    s.add("3.25");       s.add("5.30");       s.add("5.00");          s.add("3.30"); //

        tab1=(DefaultTableModel) jTable1.getModel();    // model da tabela
        //tab1.setNumRows(0);               <-- limpa a tabela
        int b=t.size(); // numero de tuplas na tabela

        for(int i=0;i<b;i++)
        {               //ok
            String produto = t.get(i); // pegar o nome do produto
            String valor = s.get(i);   // pegar o valor do produto
            tab1.addRow(new String[]{produto,valor});    // inserção de valores na tabela
        }
    }

    public String[] pega_dadosT1() throws SQLException{
        String[] a=new String [2];  // armazenar resultado
        String produto = "";        
        String valor = "";
        int indiceLinha = jTable1.getSelectedRow();  // pegar o indice da linha selecionada        
        if(jTable1.getRowCount()>0){ // numero de linhas > 0
        if (indiceLinha!=-1)
        {
             a[0] = (String) jTable1.getValueAt(indiceLinha,0); //pegar valor(linha , primeira coluna)
             a[1] = (String) jTable1.getValueAt(indiceLinha,1); //pegar valor(linha , segunda coluna)
             //obs: o indice das colunas sempre começa no numero 0
        }
        else
        {
            JOptionPane.showMessageDialog(null,"Selecione um lanche da tabela Lanches!!!");// mensagem de erro
        }
        }else{JOptionPane.showMessageDialog(null,"Sem lanches Disponiveis!!!");}        // mensagem de erro
        return a; // retona vetor
    } 

    public void TprodutoSelecionado(String nomeP,String q,String v){
        double valor=Double.parseDouble(v); //conversão de String pra Double
        int quant=Integer.parseInt(q);  //conversão de String pra Inteiro

        valor=valor*quant;  // 

        tab2=(DefaultTableModel) jTable2.getModel(); // Model
        tab2.addRow(new String[]{nomeP,""+quant,""+valor}); // Add tuplas
        valorTotal=valorTotal+valor;    // Valor total dos pedidos
        jLValorTotal.setText(""+valorTotal); // inserindo valor no label(Valor Total: )
    }

    public void Tdelet_prodSelec(){                
        int indiceLinha = jTable2.getSelectedRow();  
        double valorProd=0;
        if(jTable2.getRowCount()>0){
            if (indiceLinha!=-1)
            {
                valorProd= Double.parseDouble(""+jTable2.getValueAt(indiceLinha, 2));
                           //converter        // converter e pela valor
                valorTotal=valorTotal-valorProd; // atualizar valor total
                jLValorTotal.setText(""+valorTotal); // atualizar label
                ((DefaultTableModel) jTable2.getModel()).removeRow(indiceLinha); // remover da tabela
            }
            else{
            JOptionPane.showMessageDialog(null,"Selecione um lanche da tabela dos lanches selecionados!");//
            }
        }else{
            JOptionPane.showMessageDialog(null,"Tabela Lanches selecionados está vazia");// 
        }
    }    

    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">                          
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        jScrollPane1 = new javax.swing.JScrollPane();
        jTable1 = new javax.swing.JTable();
        jScrollPane2 = new javax.swing.JScrollPane();
        jTable2 = new javax.swing.JTable();
        JBAdicionar = new javax.swing.JButton();
        jBDelete = new javax.swing.JButton();
        jLabel1 = new javax.swing.JLabel();
        jLValorTotal = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        jLabel4 = new javax.swing.JLabel();
        Confirmacao = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setResizable(false);

        jPanel1.setBackground(new java.awt.Color(224, 237, 235));
        jPanel1.setMaximumSize(new java.awt.Dimension(550, 300));
        jPanel1.setMinimumSize(new java.awt.Dimension(550, 300));
        jPanel1.setPreferredSize(new java.awt.Dimension(551, 300));
        jPanel1.setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());

        jTable1.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N
        jTable1.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "Produtos", "Valor"
            }
        ) {
            boolean[] canEdit = new boolean [] {
                false, false
            };

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        jTable1.setSelectionBackground(new java.awt.Color(0, 153, 153));
        jScrollPane1.setViewportView(jTable1);
        if (jTable1.getColumnModel().getColumnCount() > 0) {
            jTable1.getColumnModel().getColumn(0).setResizable(false);
            jTable1.getColumnModel().getColumn(1).setMinWidth(50);
            jTable1.getColumnModel().getColumn(1).setPreferredWidth(50);
            jTable1.getColumnModel().getColumn(1).setMaxWidth(50);
        }

        jPanel1.add(jScrollPane1, new org.netbeans.lib.awtextra.AbsoluteConstraints(10, 40, 230, 124));

        jTable2.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N
        jTable2.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "Produtos", "Q", "Valor"
            }
        ) {
            boolean[] canEdit = new boolean [] {
                false, false, false
            };

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        jTable2.setSelectionBackground(new java.awt.Color(0, 153, 153));
        jScrollPane2.setViewportView(jTable2);
        if (jTable2.getColumnModel().getColumnCount() > 0) {
            jTable2.getColumnModel().getColumn(0).setResizable(false);
            jTable2.getColumnModel().getColumn(1).setMinWidth(30);
            jTable2.getColumnModel().getColumn(1).setPreferredWidth(30);
            jTable2.getColumnModel().getColumn(1).setMaxWidth(30);
            jTable2.getColumnModel().getColumn(2).setMinWidth(50);
            jTable2.getColumnModel().getColumn(2).setPreferredWidth(50);
            jTable2.getColumnModel().getColumn(2).setMaxWidth(50);
        }

        jPanel1.add(jScrollPane2, new org.netbeans.lib.awtextra.AbsoluteConstraints(410, 40, 230, 124));

        JBAdicionar.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N
        JBAdicionar.setText("Adicionar");
        JBAdicionar.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        JBAdicionar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                JBAdicionarActionPerformed(evt);
            }
        });
        jPanel1.add(JBAdicionar, new org.netbeans.lib.awtextra.AbsoluteConstraints(270, 70, 101, 30));

        jBDelete.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N
        jBDelete.setText("Deletar");
        jBDelete.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        jBDelete.setMaximumSize(new java.awt.Dimension(101, 29));
        jBDelete.setMinimumSize(new java.awt.Dimension(101, 29));
        jBDelete.setPreferredSize(new java.awt.Dimension(101, 29));
        jBDelete.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jBDeleteActionPerformed(evt);
            }
        });
        jPanel1.add(jBDelete, new org.netbeans.lib.awtextra.AbsoluteConstraints(270, 110, 101, 30));

        jLabel1.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N
        jLabel1.setText("Valor Total:");
        jPanel1.add(jLabel1, new org.netbeans.lib.awtextra.AbsoluteConstraints(510, 170, -1, -1));

        jLValorTotal.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N
        jLValorTotal.setText("0.0");
        jPanel1.add(jLValorTotal, new org.netbeans.lib.awtextra.AbsoluteConstraints(590, 170, 50, -1));

        jLabel3.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N
        jLabel3.setForeground(new java.awt.Color(67, 159, 137));
        jLabel3.setText("Lanches:");
        jPanel1.add(jLabel3, new org.netbeans.lib.awtextra.AbsoluteConstraints(10, 20, -1, -1));

        jLabel4.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N
        jLabel4.setForeground(new java.awt.Color(67, 159, 137));
        jLabel4.setText("Lanches selecionados:");
        jPanel1.add(jLabel4, new org.netbeans.lib.awtextra.AbsoluteConstraints(410, 20, -1, -1));

        Confirmacao.setBackground(new java.awt.Color(132, 196, 196));
        Confirmacao.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N
        Confirmacao.setText("Confirmar");
        Confirmacao.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        Confirmacao.setMaximumSize(new java.awt.Dimension(101, 30));
        Confirmacao.setMinimumSize(new java.awt.Dimension(101, 30));
        Confirmacao.setPreferredSize(new java.awt.Dimension(101, 30));
        Confirmacao.setSize(new java.awt.Dimension(101, 30));
        Confirmacao.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                ConfirmacaoActionPerformed(evt);
            }
        });
        jPanel1.add(Confirmacao, new org.netbeans.lib.awtextra.AbsoluteConstraints(270, 210, 101, 30));

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, 650, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(0, 0, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, 265, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(0, 0, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>                        

    private void JBAdicionarActionPerformed(java.awt.event.ActionEvent evt) {                                            
        try {
            String prod[]=pega_dadosT1(); // "pega_dadosT1"
            String nome=prod[0];
            String valor=prod[1];
            String quant;

            if (nome!=null){ // 
                JSpinner spinner = new JSpinner(); // cria um spinner 
                spinner.setValue(1); // inicializar com 1
                JOptionPane.showMessageDialog(null, spinner, "Quantidade/Porção", WIDTH);// adionando o spinner a mensagem
                //obs: não consegui add o spinner ao ...showInputDialog.. fica 2 campos na tela, ou seja, não tem botão cancelar
                quant=""+spinner.getValue(); //            
                TprodutoSelecionado(nome,quant,valor);//
            }
        } catch (SQLException ex) {
            Logger.getLogger(Cardápio.class.getName()).log(Level.SEVERE, null, ex);
        }

    }                                           

    private void jBDeleteActionPerformed(java.awt.event.ActionEvent evt) {                                         
        Tdelet_prodSelec();//
    }                                        

    private void ConfirmacaoActionPerformed(java.awt.event.ActionEvent evt) {                                            
        Confirmacao.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent arg0) {
                try {

                                    // jTable é incompatível com o método getText

                    Cadastro.cadastrar(tab2.getText(), jLValorTotal.getText());
                    tab2.setText("");
                    jLValorTotal.setText("");
                    System.out.println("Cadastrado");
                } catch (SQLException e) {
                    System.out.println("Deu erro");
                }
            }
        });
    }                                           

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {

        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new Cardápio().setVisible(true);
            }
        });
    }

    /**
     *
     */

    // Variables declaration - do not modify                     
    private javax.swing.JButton Confirmacao;
    private javax.swing.JButton JBAdicionar;
    private javax.swing.JButton jBDelete;
    private javax.swing.JLabel jLValorTotal;
    private javax.swing.JLabel jLabel1;
    public javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JTable jTable1;
    private javax.swing.JTable jTable2;
    // End of variables declaration                   
}

In part: where you have two errors in this file Cardapio.java :

private void ConfirmacaoActionPerformed(java.awt.event.ActionEvent evt) {                                            
        Confirmacao.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent arg0) {
                try {

  // jTable2 ou tab2 são incompatíveis com o método getText

                    Cadastro.cadastrar(tab2.getText(), jLValorTotal.getText());
                    tab2.setText("");
                    jLValorTotal.setText("");
                    System.out.println("Cadastrado");
                } catch (SQLException e) {
                    System.out.println("Deu erro");
                }
            }
        });
    }

I use tab2 (variable of the table component) or jTable2 (variable of the JTable component) to get the name of the products of the Selected Snacks to store them in a database and print them.

Thefollowingerrors:

InafileCadastro.java:

packagebr.com.control;importjava.sql.Connection;importjava.sql.PreparedStatement;importjava.sql.SQLException;importbr.com.cardapio.view.Conexao;publicclassCadastro{publicstaticvoidcadastrar(Stringprodutos,Stringquantidade,Stringprestacao)throwsSQLException{ConexaoclasseConexao=newConexao();Connectionc=classeConexao.getConnection();PreparedStatementstmt;Stringquery="insert into cadastrofiscal values (?,?,?)";
        stmt = c.prepareStatement(query);
        stmt.setString(1, produtos);
        stmt.setString(2, quantidade);
                stmt.setString(3, prestacao);
        System.out.println(query);
        stmt.executeUpdate();


    }
}

In the file Conexao.java :

package br.com.cardapio.view;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

public class Conexao {

    Connection con = null;
    private static Conexao instance = null;

    public Conexao() {
        inicio();
    }

    public void inicio() {
        try {
            Class.forName("com.mysql.jdbc.Driver");
            System.out.println("Driver Carregado");
        } catch (ClassNotFoundException e) {
            System.out.println("O driver do Mysql n�o p�de ser carregado!");
        }
    }

    public static Conexao getInstance() {
        if (instance == null) {
            instance = new Conexao();
        }
        return instance;
    }

    public Connection getConnection() {
        try {
            if ((con == null) || (con.isClosed())) {
                con = DriverManager.getConnection("jdbc:mysql://localhost/agenda", "root", "");
                System.out.println("Conex�o Estabelecida");
            }
        } catch (SQLException e) {
            System.out.println(e.getMessage());
        }
        return con;
    }

    public void destroy() {
        try {
            con.close();
        } catch (SQLException e) {
            System.out.println(e.getMessage());
        }
    }


}

In the file Teste.java :

package br.com.cardapio.view;

import java.sql.Connection;

public class Teste {
    public static void main (String [] args){
        Conexao c = new Conexao();
        Connection con = c.getConnection();

    }
}

In an SQL file:

CREATE DATABASE cardapiofiscal;
USE cardapiofiscal;

SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
SET time_zone = "+00:00";

CREATE TABLE 'cadastrofiscal' (
  'produtos' TEXT COLLATE utf8_bin NOT NULL,
  'quantidade' INT(2) NOT NULL,
  'prestacao' INT(5) NOT NULL
);

insert into cadastrofiscal values ('X-salada, Suco de Laranja','2', '9.00');

select * from cadastrofiscal;

Now, I just want tab2 or jTable2 (table or JTable) to be taken as text by getText to store them in the database. But these are incompatible with getText because it looks like they are not String (s). So I have to find the methods of these variables of these components.

    
asked by anonymous 07.06.2016 / 15:40

1 answer

3

The DefaultTableModel class > does not have the getText() method. To retrieve selected rows and columns, you must use the getValueAt​(int row, int column) ", passing the row and column number of JTable you want to retrieve the data.

It's always a good idea to use Bean to save the data before exiting by passing them between methods, makes it easier to understand and maintain your code.

Ex:

public class Produto {

    private String nome;
    private double valor;
    private int quantidade;

    public int getNome() {
        return nome;
    }

    public void setNome(String nome) {
        this.nome = nome;
    }

    public double getValor() {
        return valor;
    }

    public void setValor(double valor) {
        this.valor = valor;
    }

    public int getQuantidade() {
        return quantidade;
    }

    public void setQuantidade(int quantidade) {
        this.quantidade = quantidade;
    }
}

Hence, one product per line would be popular before going through the registration. You can go through a list of product pro registration too:

    ArrayList<Produto> produtos = new ArrayList<>();
    int totalRows = suaJtable.getRowCount();

    for (int i = 0; i < totalRows; i++) {
        Produto p = new Produto();
        p.setNome((String) suaJTable.getModel().getValueAt(i, 0));
        p.setValor((double) suaJTable.getModel().getValueAt(i, 2));
        p.setQuantidade((int) suaJTable.getModel().getValueAt(i, 3));

        produtos.add(p);
    }

Then just pass produtos to your registration method, and make a loop by scrolling through the list to get the products and insert in the table, something like this:

for(Produto p : produtos){
    Cadastro.cadastrar(p.getNome(), p.getQuantidade(), p.getValor());
}

Implemented in your code, it would look something like this:

private void ConfirmacaoActionPerformed(java.awt.event.ActionEvent evt) {                                            
        Confirmacao.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent arg0) {
                try {

                    ArrayList<Produto> produtos = new ArrayList<>();
                    int totalRows = suaJtable.getRowCount();

                    for (int i = 0; i < totalRows; i++) {
                        Produto p = new Produto();
                        p.setNome((String) suaJTable.getModel().getValueAt(i, 0));
                        p.setValor((double) suaJTable.getModel().getValueAt(i, 2));
                        p.setQuantidade((int) suaJTable.getModel().getValueAt(i, 3));

                        produtos.add(p);
                        }

                       //...

                    for(Produto p : produtos){
                        Cadastro.cadastrar(p.getNome(), p.getQuantidade(), p.getValor());
                    }

                    jLValorTotal.setText("");
                    System.out.println("Cadastrado");
                } catch (SQLException e) {
                    System.out.println("Deu erro");
                }
            }
        });
    }

It may even be more interesting to create your own model , it will be less complicated since popular your table, until you update and capture data from it.

    
07.06.2016 / 18:00