2
I’m developing a project called Menu List with a Mysql and Java database in Netbeans, with an added Mysql-Connector-Java library. I want the names of the selected products, the quantity of products and the total model price Cardapio.java
are stored and printed as text in a database by the template Cadastro.java
, connecting with the models Conexão.java
and Teste.java
.
I haven’t solved two errors in Java yet.
Follow the full source code of 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 the part: where there are 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 take the name of the products of the Selected Snacks to store them in a database and print them.
The following errors:
In an archive Cadastro.java
:
package br.com.control;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import br.com.cardapio.view.Conexao;
public class Cadastro {
public static void cadastrar(String produtos, String quantidade, String prestacao) throws SQLException{
Conexao classeConexao = new Conexao();
Connection c = classeConexao.getConnection();
PreparedStatement stmt;
String query = "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 archive 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 archive 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) are taken as text by getText
to store them in the database. But these are incompatible with the getText
because it seems that they are not String(s). Therefore, I have to find the methods of these variables of these components.
This feels like semantic error.
tab2
is a Jtable?– user28595
@diegofm No,
tab2
is a "table
" and is inside jTable2 which is a View image: http://i.imgur.com/Z3xcchf.png– Gustavo Reis Costa
I’ve never seen a "table" component in java. I only know Jtable. Add a [mcve] so you can better evaluate the problem.
– user28595
@diegofm I updated the question and completed, I don’t know if it got better.
– Gustavo Reis Costa
Actually tab2 and tab1 are models, not Tables, as you said.
– user28595
What is a model? You can do this to get product names to store them in a database?
– Gustavo Reis Costa
You want to get the data from the second table?
– user28595
Yes, exactly!
– Gustavo Reis Costa