How to Get the value of a multiplication?

Asked

Viewed 48 times

-1

System made in Vaadin + Java + Springboot + Maven + Mysql

I have a sales system, where the user chooses the product he wants to buy in a Combobox, sets the amount he wants to buy (Numberfield), when selecting the product the field Unit Value(Textfield) is filled automatically with the value saved in MYSQL.

Problem: How do I, when the user sets the amount(Numberfield) automatically multiply Unit Value(Textfield) and the value of this multiplication appears in the Total Item Value field(Numberfield)?

inserir a descrição da imagem aqui

See in the image below I bought 2 motherboards, but the total item value is 0

How to Get the Right Result?

I tried with this code:

txtQuantidade.setHasControls(true);
txtQuantidade.setValue(null);
txtQuantidade.setMin(1);
        
txtQuantidade.addValueChangeListener(event -> {        
    String valorUnitario = txtValorUnitario.getValue().replace(".", ",");
    Number number = 0;
    try {
        number = NumberFormat.getInstance().parse(valorUnitario);
    } catch (ParseException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }
    
    float valorUnitarioFloat = Float.parseFloat(String.valueOf(number));

    txtValorTotalItem.setValue(valorUnitarioFloat * txtQuantidade.getValue());
});

but with this code I only got this error:

java.text.ParseException: Unparseable number: "R$ 549,90"
  at java.base/java.text.NumberFormat.parse(NumberFormat.java:434)
  at br.com.fjsistemas.cadastros.view.VendaView.lambda$13(VendaView.java:265)
  at com.vaadin.flow.component.internal.AbstractFieldSupport.lambda$addValueChangeListener$828eca10$1(AbstractFieldSupport.java:96)
  at com.vaadin.flow.component.ComponentEventBus.fireEventForListener(ComponentEventBus.java:205)
  at com.vaadin.flow.component.ComponentEventBus.fireEvent(ComponentEventBus.java:194)
  at com.vaadin.flow.component.Component.fireEvent(Component.java:359)
  at com.vaadin.flow.component.ComponentUtil.fireEvent(ComponentUtil.java:386)
  at com.vaadin.flow.component.internal.AbstractFieldSupport.setValue(AbstractFieldSupport.java:207)
  at com.vaadin.flow.component.internal.AbstractFieldSupport.setModelValue(AbstractFieldSupport.java:167)
  at com.vaadin.flow.component.AbstractField.setModelValue(AbstractField.java:225)
  at com.vaadin.flow.component.AbstractSinglePropertyField.handlePropertyChange(AbstractSinglePropertyField.java:352)
  at com.vaadin.flow.component.AbstractSinglePropertyField.access$200(AbstractSinglePropertyField.java:48)
  at com.vaadin.flow.component.AbstractSinglePropertyField$1.propertyChange(AbstractSinglePropertyField.java:325)
  at com.vaadin.flow.internal.nodefeature.ElementPropertyMap.lambda$fireEvent$2(ElementPropertyMap.java:454)
  at java.base/java.util.ArrayList.forEach(ArrayList.java:1507)
  at com.vaadin.flow.internal.nodefeature.ElementPropertyMap.fireEvent(ElementPropertyMap.java:454)
  at com.vaadin.flow.internal.nodefeature.ElementPropertyMap.access$100(ElementPropertyMap.java:48)
  at com.vaadin.flow.internal.nodefeature.ElementPropertyMap$PutResult.run(ElementPropertyMap.java:166)
  at com.vaadin.flow.server.communication.ServerRpcHandler.runMapSyncTask(ServerRpcHandler.java:395)
  at com.vaadin.flow.server.communication.ServerRpcHandler.lambda$handleInvocations$0(ServerRpcHandler.java:389)
  at java.base/java.util.ArrayList.forEach(ArrayList.java:1507)
  at com.vaadin.flow.server.communication.ServerRpcHandler.handleInvocations(ServerRpcHandler.java:389)
  at com.vaadin.flow.server.communication.ServerRpcHandler.handleRpc(ServerRpcHandler.java:317)
  at com.vaadin.flow.server.communication.UidlRequestHandler.synchronizedHandleRequest(UidlRequestHandler.java:89)
  at com.vaadin.flow.server.SynchronizedRequestHandler.handleRequest(SynchronizedRequestHandler.java:40)
  at com.vaadin.flow.server.VaadinService.handleRequest(VaadinService.java:1547)
  at com.vaadin.flow.server.VaadinServlet.service(VaadinServlet.java:247)
  at com.vaadin.flow.spring.SpringServlet.service(SpringServlet.java:111)
  at javax.servlet.http.HttpServlet.service(HttpServlet.java:733)
  at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:231)
  at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
  at org.apache.catalina.core.ApplicationDispatcher.invoke(ApplicationDispatcher.java:712)
  at org.apache.catalina.core.ApplicationDispatcher.processRequest(ApplicationDispatcher.java:459)
  at org.apache.catalina.core.ApplicationDispatcher.doForward(ApplicationDispatcher.java:352)
  at org.apache.catalina.core.ApplicationDispatcher.forward(ApplicationDispatcher.java:312)
  at org.springframework.web.servlet.mvc.ServletForwardingController.handleRequestInternal(ServletForwardingController.java:141)
  at org.springframework.web.servlet.mvc.AbstractController.handleRequest(AbstractController.java:177)
  at org.springframework.web.servlet.mvc.SimpleControllerHandlerAdapter.handle(SimpleControllerHandlerAdapter.java:52)
  at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:1060)
  at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:962)
  at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:1006)
  at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:909)
  at javax.servlet.http.HttpServlet.service(HttpServlet.java:652)
  at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:883)
  at javax.servlet.http.HttpServlet.service(HttpServlet.java:733)
  at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:231)
  at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
  at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)
  at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
  at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
  at org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:100)
  at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119)
  at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
  at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
  at org.springframework.web.filter.FormContentFilter.doFilterInternal(FormContentFilter.java:93)
  at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119)
  at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
  at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
  at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:201)
  at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119)
  at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
  at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
  at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:202)
  at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:97)
  at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:542)
  at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:143)
  at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:92)
  at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:78)
  at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:343)
  at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:374)
  at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:65)
  at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:888)
  at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1597)
  at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
  at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1128)
  at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:628)
  at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
  at java.base/java.lang.Thread.run(Thread.java:830)

2 answers

0


resolved as follows:

package br.com.fjsistemas.cadastros.view;

import java.text.NumberFormat;
import java.text.ParseException;
import java.time.LocalDate;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;

import javax.annotation.PostConstruct;

import org.springframework.beans.factory.annotation.Autowired;
import org.vaadin.textfieldformatter.CustomStringBlockFormatter;

import com.vaadin.flow.component.Component;
import com.vaadin.flow.component.button.Button;
import com.vaadin.flow.component.button.ButtonVariant;
import com.vaadin.flow.component.combobox.ComboBox;
import com.vaadin.flow.component.datepicker.DatePicker;
import com.vaadin.flow.component.dialog.Dialog;
import com.vaadin.flow.component.formlayout.FormLayout;
import com.vaadin.flow.component.grid.Grid;
import com.vaadin.flow.component.grid.GridVariant;
import com.vaadin.flow.component.html.Div;
import com.vaadin.flow.component.html.Label;
import com.vaadin.flow.component.orderedlayout.HorizontalLayout;
import com.vaadin.flow.component.orderedlayout.VerticalLayout;
import com.vaadin.flow.component.tabs.Tab;
import com.vaadin.flow.component.tabs.Tabs;
import com.vaadin.flow.component.textfield.NumberField;
import com.vaadin.flow.component.textfield.TextField;
import com.vaadin.flow.data.binder.Binder;
import com.vaadin.flow.data.binder.PropertyId;
import com.vaadin.flow.data.renderer.NumberRenderer;
import com.vaadin.flow.router.PageTitle;
import com.vaadin.flow.router.Route;

import br.com.fjsistemas.backend.Cliente;
import br.com.fjsistemas.backend.Produto;
import br.com.fjsistemas.backend.Venda;
import br.com.fjsistemas.main.MainView;
import br.com.fjsistemas.repository.ClienteRepository;
import br.com.fjsistemas.repository.ProdutoRepository;
import br.com.fjsistemas.service.VendaService;

@Route(value = "venda-view", layout = MainView.class)
@PageTitle("Lançamento de Vendas")
public class VendaView extends VerticalLayout {

    private static final long serialVersionUID = 1L;

    private HorizontalLayout hltVenda = new HorizontalLayout();
    Grid<Venda> grdVenda = new Grid<>(Venda.class, false);

    private HorizontalLayout hltBarraBotoes = new HorizontalLayout();
    Button btnNovo = new Button("Novo");
    Button btnAlterar = new Button("Alterar");
    Button btnExcluir = new Button("Excluir");

    private Dialog dlgJanela = new Dialog();

    private FormLayout fltCamposVenda = new FormLayout();

    HorizontalLayout primeiraLinhaGuiaVenda = new HorizontalLayout();
    HorizontalLayout segundaLinhaGuiaVenda = new HorizontalLayout();
    HorizontalLayout terceiraLinhaGuiaVenda = new HorizontalLayout();
    HorizontalLayout quartaLinhaGuiaVenda = new HorizontalLayout();

    @PropertyId("data")
    private DatePicker txtDataVenda = new DatePicker("Data Venda");

    @PropertyId("nome")
    private ComboBox<Cliente> txtNomeCliente = new ComboBox<>();

    @PropertyId("telefone")
    private TextField txtTelefone = new TextField("Telefone");

    @PropertyId("celular")
    private TextField txtCelular = new TextField("Celular");

    @PropertyId("produtos")
    private ComboBox<Produto> txtProdutos = new ComboBox<>();

    @PropertyId("quantidade")
    private NumberField txtQuantidade = new NumberField("Quantidade");

    @PropertyId("unitario")
    private TextField txtValorUnitario = new TextField("Valor Unitário");

    @PropertyId("valorTotalItem")
    private TextField txtValorTotalItem = new TextField("Valor Total Item");

    @PropertyId("campoSomaValores")
    private NumberField campoSomaValores = new NumberField();

    private HorizontalLayout htlDlgBarraBotoes = new HorizontalLayout();
    private Button btnSalvar = new Button("Salvar");
    private Button btnFechar = new Button("Fechar");
    private Button btnAdicionarItem = new Button("Adicionar Item");

    @Autowired
    VendaService vendaService;

    @Autowired
    ClienteRepository clienteRepository;

    @Autowired
    ProdutoRepository produtoRepository;

    private List<Venda> listaVendas;
    private Venda venda;

    Binder<Venda> binderVenda = new Binder<>(Venda.class);

    public VendaView() {

    }

    @PostConstruct
    public void init() {
        configuraTela();

    }

    private void configuraTela() {

        setMargin(false);
        setPadding(false);

        configuraHltVenda();
        configuraFltBarraBotoes();
        configuraDlgJanela();
        populaGrdVenda();
        configuraBinder();

        add(hltVenda, hltBarraBotoes);
    }

    private void configuraFltBarraBotoes() {

        btnNovo.addThemeVariants(ButtonVariant.LUMO_PRIMARY);
        btnNovo.addClickListener(e -> {
            novoClick();
        });

        btnAlterar.addThemeVariants(ButtonVariant.LUMO_PRIMARY);
        btnAlterar.addClickListener(e -> {
            alterarClick();
        });

        btnExcluir.addThemeVariants(ButtonVariant.LUMO_PRIMARY);
        btnExcluir.addClickListener(e -> {
            excluirClick();
        });

        hltBarraBotoes.add(btnNovo, btnAlterar, btnExcluir);
    }

    private void excluirClick() {

        if (venda != null) {
            listaVendas.remove(venda);
            vendaService.delete(venda);
            atualizaGrdVenda();
        }
    }

    private void configuraHltVenda() {
        hltVenda.setWidthFull();
        configuraGrdVenda();
        hltVenda.add(grdVenda);
    }

    private void configuraGrdVenda() {
        grdVenda.setHeight("820px");
        grdVenda.setWidthFull();

        grdVenda.addColumn(Venda::getId).setHeader("ID:").setAutoWidth(true);

        grdVenda.addColumn(Venda::getDataVenda).setHeader("Data Venda:").setAutoWidth(true).setKey("dataVenda");

        grdVenda.addColumn(Venda::getNomeCliente).setHeader("Nome:").setAutoWidth(true).setKey("nome");

        grdVenda.addColumn(new NumberRenderer<>(Venda::getValorTotalVenda, "R$ %(,.2f", Locale.getDefault(), "R$ 0.00"))
                .setHeader("Valor Total:").setAutoWidth(true).setKey("valorTotalVenda");

        grdVenda.addThemeVariants(GridVariant.LUMO_COMPACT, GridVariant.LUMO_COLUMN_BORDERS);

        grdVenda.getColumns().forEach(col -> col.setAutoWidth(true).setSortable(true).setResizable(true));

        grdVenda.addItemClickListener(e -> {
            venda = e.getItem();
        });

    }

    private void configuraDlgJanela() {

        dlgJanela.setHeight("755px");
        dlgJanela.setWidth("860px");

        Tab vender = new Tab("Vendas");
        Div venderDiv = new Div();

        Tab entrega = new Tab("Entregas");
        Div entregaDiv = new Div();
        entregaDiv.setVisible(false);

        Tab financeiro = new Tab("Financeiro");
        Div financeiroDiv = new Div();
        financeiroDiv.setVisible(false);

//=====================================================================================================================

        txtNomeCliente.setWidth("390px");
        txtNomeCliente.setLabel("Nome Cliente");

        List<Cliente> listaDeClientes = clienteRepository.findAll();
        txtNomeCliente.setItemLabelGenerator(Cliente::getNome);
        txtNomeCliente.setItems(listaDeClientes);
        txtNomeCliente.addValueChangeListener(event -> {
            txtTelefone.setValue(event.getValue().getFone());
            txtCelular.setValue(event.getValue().getCelular());
        });

        new CustomStringBlockFormatter.Builder().blocks(0, 2, 4, 4).delimiters("(", ")", "-").numeric().build()
                .extend(txtTelefone);

        new CustomStringBlockFormatter.Builder().blocks(0, 2, 5, 4).delimiters("(", ")", "-").numeric().build()
                .extend(txtCelular);

//=====================================================================================================================

        txtProdutos.setWidth("370px");
        txtProdutos.setLabel("Produtos");
        List<Produto> listaDeProdutos = produtoRepository.findAll();
        txtProdutos.setItemLabelGenerator(Produto::getNome);
        txtProdutos.setItems(listaDeProdutos);
        txtProdutos.addValueChangeListener(event -> {

            NumberFormat formatter = NumberFormat.getCurrencyInstance(new Locale("pt", "BR"));
            try {

                txtValorUnitario.setValue(formatter.format(event.getValue().getValor()));

            } catch (Exception e) {
                e.printStackTrace();
            }

        });

//==========================================================================================================================

        txtQuantidade.setHasControls(true);
        txtQuantidade.setValue(null);
        txtQuantidade.setMin(1);

        txtQuantidade.addValueChangeListener(event -> {
              
            NumberFormat formatter = NumberFormat.getCurrencyInstance(new Locale("pt", "BR"));
            double valorTotal = 0;
            try {
                valorTotal = formatter.parse(txtValorUnitario.getValue()).doubleValue() * txtQuantidade.getValue();
            } catch (ParseException e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
            } txtValorTotalItem.setValue(formatter.format(valorTotal));
        });

//==========================================================================================================================

        Label text = new Label("Valor Total da Compra");
        text.getElement().getStyle().set("fontWeight", "bold");
        text.getStyle().set("margin-top", "25em");
        text.getStyle().set("margin-left", "24em");
        text.getStyle().set("text-align", "center");
        campoSomaValores.getStyle().set("margin-top", "25em");
        campoSomaValores.setWidth("30em");

        segundaLinhaGuiaVenda.add(txtNomeCliente, txtTelefone, txtCelular);
        terceiraLinhaGuiaVenda.add(txtProdutos, txtQuantidade, txtValorUnitario, txtValorTotalItem);
        quartaLinhaGuiaVenda.add(text, campoSomaValores);

        fltCamposVenda.add(venderDiv, entregaDiv, financeiroDiv);
        venderDiv.add(txtDataVenda, segundaLinhaGuiaVenda, terceiraLinhaGuiaVenda, quartaLinhaGuiaVenda);
        vender.add(venderDiv);

        LocalDate now = LocalDate.now();
        txtDataVenda.setValue(now);

        Map<Tab, Component> tabsToPages = new HashMap<>();
        tabsToPages.put(vender, venderDiv);
        tabsToPages.put(entrega, entregaDiv);
        tabsToPages.put(financeiro, financeiroDiv);
        Tabs tabs = new Tabs(vender, entrega, financeiro);
        Div pages = new Div(venderDiv, entregaDiv, financeiroDiv);

        tabs.addSelectedChangeListener(event -> {
            tabsToPages.values().forEach(page -> page.setVisible(false));
            Component selectedPage = tabsToPages.get(tabs.getSelectedTab());
            selectedPage.setVisible(true);
        });

        dlgJanela.add(tabs, pages);

        btnSalvar.addThemeVariants(ButtonVariant.LUMO_PRIMARY);
        btnSalvar.getStyle().set("margin-top", "-3em");
        btnSalvar.getStyle().set("margin-left", "0em");
        btnSalvar.addClickListener(e -> {
            salvarClick();
        });

        btnFechar.addThemeVariants(ButtonVariant.LUMO_PRIMARY);
        btnFechar.getStyle().set("margin-top", "-3em");
        btnFechar.addClickListener(e -> {
            dlgJanela.close();
        });

        btnAdicionarItem.addThemeVariants(ButtonVariant.LUMO_PRIMARY);
        btnAdicionarItem.getStyle().set("margin-top", "-3em");
        btnAdicionarItem.addClickListener(e -> {

        });

        htlDlgBarraBotoes.add(btnSalvar, btnFechar, btnAdicionarItem);

        dlgJanela.add(fltCamposVenda, htlDlgBarraBotoes);
    }

    private void salvarClick() {

        venda = binderVenda.getBean();

        boolean adicionarLista = venda.getId() == null ? true : false;

        vendaService.create(venda);

        if (adicionarLista) {
            listaVendas.add(venda);
        }
        atualizaGrdVenda();
        novaVenda();
        txtNomeCliente.focus();

        binderVenda.setBean(venda);

        if (adicionarLista) {
            dlgJanela.close();
        }
    }

    private void populaGrdVenda() {

        listaVendas = vendaService.read();
        atualizaGrdVenda();
    }

    private void atualizaGrdVenda() {
        grdVenda.setItems(listaVendas);
    }

    private void configuraBinder() {

        binderVenda.bindInstanceFields(this);

    }

    private void novoClick() {

        novaVenda();
        binderVenda.setBean(venda);

        dlgJanela.open();
        txtNomeCliente.focus();
    }

    private void alterarClick() {

        if (venda != null) {
            binderVenda.setBean(venda);

            dlgJanela.open();

        }
    }

    private void novaVenda() {
        venda = new Venda();
        venda.setNomeCliente(" ");
        dlgJanela.close();

    }
}

0

The value you have is "R$ 549,90" it is not possible to convert this String to a numerical value, first you must leave only the numbers inside the String. Obs leave the string with the . to convert its value.

When you have your double value you will be able to do your calculation.

String txtValorUnitario = "R$ 549.90";
String valorUnitario2 = txtValorUnitario.replace("R$ ", "");
double meuValorNumerico = Double.parseDouble(valorUnitario2);
  • Glauber, obg for his reply, but I managed to solve with the code that is above his answer...vlw friend

Browser other questions tagged

You are not signed in. Login or sign up in order to post.