Soma de campos Inteiros de tabelas diferentes

5 respostas
Tati_Meneghello

Olá galera, Bom eu estou com problema na hora de salvar um estoque.

criei um formulario produto contendo as informações como nome,tamanho etc.
e no Formulario estoque eu fiz uma combo box puxando oas valores do nome …

dai fiz um campo para a quantidade assim queria somar para criar um estoque.

como posso fazer isso?

5 Respostas

jLady

Bom… explique um pouco melhor isso que voce está fazendo…
Se puder, coloque um pedaço do código…

Fica melhor pra poder te ajudar…

Tati_Meneghello

//botão de add itens da tela estoque
private void btAddActionPerformed(java.awt.event.ActionEvent evt) {

Produto prod = new Produto();
    prod = conProd.carregar(Long.parseLong(String.valueOf(cProduto.getSelectedIndex())));
    prod.setEstoque(prod.getEstoque() + Integer.parseInt(fQuantidade.getText()));
    conProd.salvar(prod);
   

}

// aqui declarei 0 ao estoque da tela produto

objeto.setEstoque(0);
    controle.salvar(objeto);

//entidade produto
@Column
private Integer estoque;

public Integer getEstoque() {
    return estoque;
}

public void setEstoque(Integer estoque) {
    this.estoque = estoque;
}

isso não està dando certo como eu posso somar o campo estoque da tela produto que é 0 com a da tela estoque que é um resultado qualquer para o estoque a ser possuido

josemanzoli

Ficou meio complicado entender o que você realmente quer fazer com o estoque.

Mas acredito que você esteja com um errinho básico no modelo.

Seus estoque deve aumentar ou diminuir conforme você compra ou vende produtos.
Algumas pessoas fazem com entidades separadas e outras usam a entidade produto como estoque.
Pelo que vi seus produtos tem a quantidade em estoque na entidade produto, você até fez o correto ao salvar o produto adicionando a quantidade selecionada, mas:
E se o produto já existir?
Porque você está setando 0 no estoque do produto?

Botão de add na tela estoque? Você não pode adicionar estoque e sim fazer uma compra/venda onde a compra/venda soma/subtrai a quantidade comprada/vendida do estoque que fica na sua entidade produtos.

Conseguiu entender?

Tati_Meneghello
private void montaCombo() {

lproduto = conProd.listaTodos();

cProduto.removeAllItems();

cTamanho.removeAllItems();

CLargura.removeAllItems();

cEspessura.removeAllItems();
for (Iterator<Produto> it = lproduto.iterator(); it.hasNext();) {
        Produto produto = it.next();
        cProduto.addItem(produto.getNomeProd());
        cTamanho.addItem(produto.getTamanho());
        CLargura.addItem(produto.getLargura());
        cEspessura.addItem(produto.getEspessura());
    }
}


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

    jLabel1 = new javax.swing.JLabel();
    jLabel2 = new javax.swing.JLabel();
    jLabel3 = new javax.swing.JLabel();
    jLabel4 = new javax.swing.JLabel();
    jLabel5 = new javax.swing.JLabel();
    jLabel6 = new javax.swing.JLabel();
    btAdd = new javax.swing.JButton();
    cProduto = new javax.swing.JComboBox();
    cTamanho = new javax.swing.JComboBox();
    CLargura = new javax.swing.JComboBox();
    cEspessura = new javax.swing.JComboBox();
    fQuantidade = new javax.swing.JTextField();
    jButton1 = new javax.swing.JButton();

    setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);

    jLabel1.setFont(new java.awt.Font("Comic Sans MS", 1, 24));
    jLabel1.setText("Estoque");

    jLabel2.setText("Produto:");

    jLabel3.setText("Tamanho:");

    jLabel4.setText("Largura:");

    jLabel5.setText("Espessura:");

    jLabel6.setText("Quantidade:");

    btAdd.setText("Adcionar");
    btAdd.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            btAddActionPerformed(evt);
        }
    });

    fQuantidade.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            fQuantidadeActionPerformed(evt);
        }
    });

    jButton1.setText("Sair");
    jButton1.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            jButton1ActionPerformed(evt);
        }
    });

    javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
    getContentPane().setLayout(layout);
    layout.setHorizontalGroup(
        layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGroup(layout.createSequentialGroup()
            .addGap(77, 77, 77)
            .addComponent(btAdd)
            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 99, Short.MAX_VALUE)
            .addComponent(jButton1)
            .addGap(98, 98, 98))
        .addGroup(layout.createSequentialGroup()
            .addGap(44, 44, 44)
            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                .addComponent(jLabel3)
                .addComponent(jLabel2)
                .addComponent(jLabel4)
                .addComponent(jLabel5))
            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(layout.createSequentialGroup()
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addGroup(layout.createSequentialGroup()
                            .addGap(77, 77, 77)
                            .addComponent(jLabel1))
                        .addGroup(layout.createSequentialGroup()
                            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                .addComponent(cTamanho, 0, 185, Short.MAX_VALUE)
                                .addComponent(cProduto, 0, 185, Short.MAX_VALUE)
                                .addComponent(cEspessura, 0, 185, Short.MAX_VALUE)
                                .addComponent(CLargura, 0, 185, Short.MAX_VALUE))))
                    .addGap(138, 138, 138))
                .addGroup(layout.createSequentialGroup()
                    .addGap(16, 16, 16)
                    .addComponent(jLabel6)
                    .addGap(18, 18, 18)
                    .addComponent(fQuantidade, javax.swing.GroupLayout.PREFERRED_SIZE, 64, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addContainerGap())))
    );

    layout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {btAdd, jButton1});

    layout.setVerticalGroup(
        layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGroup(layout.createSequentialGroup()
            .addGap(20, 20, 20)
            .addComponent(jLabel1)
            .addGap(18, 18, 18)
            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                .addComponent(jLabel2)
                .addComponent(cProduto, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                .addComponent(jLabel3)
                .addComponent(cTamanho, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                .addComponent(cEspessura, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addComponent(jLabel4))
            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                .addComponent(CLargura, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addComponent(jLabel5))
            .addGap(27, 27, 27)
            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                .addComponent(fQuantidade, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addComponent(jLabel6))
            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 32, Short.MAX_VALUE)
            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                .addComponent(btAdd)
                .addComponent(jButton1))
            .addGap(23, 23, 23))
    );

    layout.linkSize(javax.swing.SwingConstants.VERTICAL, new java.awt.Component[] {btAdd, jButton1});

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

private void btAddActionPerformed(java.awt.event.ActionEvent evt) {                                      


    Produto prod = new Produto();
    prod = conProd.carregar(Long.parseLong(String.valueOf(cProduto.getSelectedIndex())));
    prod.setEstoque(prod.getEstoque() + Integer.parseInt(fQuantidade.getText()));
    conProd.salvar(prod);
   

}

essa eh minha tela de estoque

eu qro somar esse valor com o que jah vai esta armazenado

e tb diminuir qndo fizer uma venda

josemanzoli
private void btAddActionPerformed(java.awt.event.ActionEvent evt) {

Produto prod = new Produto();
prod = conProd.carregar(Long.parseLong(String.valueOf(cProduto.getSelectedIndex())));
prod.setEstoque(prod.getEstoque() + Integer.parseInt(fQuantidade.getText()));
conProd.salvar(prod);//aqui você está usando update ou insert?
}

Você já está somando o valor, o seu método

conProd.carregar(Long.parseLong(String.valueOf(cProduto.getSelectedIndex())));

já está carregando o produto previamente cadastrado e você está somando no método

prod.setEstoque(prod.getEstoque() + Integer.parseInt(fQuantidade.getText()));

Não sei se esse setEstoque está funcionando mas se funcionar está tudo certo, analise se na hora de salvar você está atualizando o objeto já existente ou criando um novo.

Criado 28 de outubro de 2010
Ultima resposta 28 de out. de 2010
Respostas 5
Participantes 3