如何在另一个 div 中分配一个 div

如何解决如何在另一个 div 中分配一个 div

大家早上好,我正在创建一个产品销售系统,这个话题会有点长,因为我想好好解释一下。

系统正在Vaadin + MySQL + SpringBoot + Maven开发

在主屏幕上,我们有一个带有“新建”、“更改”和“删除”按钮的网格:

enter image description here

点击新按钮时会打开一个窗口,开始“销售”产品:

enter image description here

这里的问题如下,当我点击“+ item”时出现以下情况:

enter image description here

问题:创建了一个滚动条(在窗口右侧),Save、Close 和 + Item 按钮向下移动(仅在滚动条向下滚动时出现)。每次我尝试添加产品(+ 项目)时,重复该过程,按钮被扔下。

所需的解决方案:我希望将按钮“冻结或固定”在窗口底部,并且通过添加产品甚至可以创建滚动条,但无需向下移动按钮

我想到了这样的事情:

enter image description here

接收产品的div2在任何情况下都不能侵入divs1和divs3(上下)

但我承认我无法创造这个……我尝试了很多方法,但都失败了

如果有人可以帮助我,我很感激

我的代码:

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();
    
    Tab vender = new Tab("Vendas");
    Div venderDiv = new Div();

    Tab entrega = new Tab("Entregas");
    Div entregaDiv = new Div();

    Tab financeiro = new Tab("Financeiro");
    Div financeiroDiv = new Div();

    @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("campoSomaValores")
    private TextField campoSomaValores = new TextField();

    private HorizontalLayout htlDlgBarraBotoes = new HorizontalLayout();
    private Button btnSalvar = new Button("Salvar");
    private Button btnFechar = new Button("Fechar");
    private Button btnAdicionarItem = new Button("+ 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");

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

        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,5,"-").numeric().build()
                .extend(txtCelular);

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

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

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

        segundaLinhaGuiaVenda.add(txtNomeCliente,txtTelefone,txtCelular);

        fltCamposVenda.add(venderDiv,entregaDiv,financeiroDiv);
        venderDiv.setHeight("120px");
        venderDiv.add(txtDataVenda,segundaLinhaGuiaVenda);
        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,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","30em");
        btnSalvar.getStyle().set("margin-left","0em");
        btnSalvar.addClickListener(e -> {
            salvarClick();
        });

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

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

        htlDlgBarraBotoes.add(btnSalvar,btnFechar,btnAdicionarItem,text,campoSomaValores);

        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 adicionaProduto() {

        ComboBox<Produto> txtProdutos = new ComboBox<>();

        NumberField txtQuantidade = new NumberField("Quantidade");

        TextField txtValorUnitario = new TextField("Valor Unitário");

        TextField txtValorTotalItem = new TextField("Valor Total Item");

        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));
            campoSomaValores.setValue(formatter.format(valorTotal));
        });

        HorizontalLayout linhaNova = new HorizontalLayout();
        
        linhaNova.add(txtProdutos,txtQuantidade,txtValorUnitario,txtValorTotalItem);
        

        venderDiv.add(linhaNova);

    }

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

    }
}

解决方法

您还可以使用百分比。所以代替

venderDiv.setHeight("120px");

使用百分比表示 div 高度

venderDiv.setHeight("30%");

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


使用本地python环境可以成功执行 import pandas as pd import matplotlib.pyplot as plt # 设置字体 plt.rcParams[&#39;font.sans-serif&#39;] = [&#39;SimHei&#39;] # 能正确显示负号 p
错误1:Request method ‘DELETE‘ not supported 错误还原:controller层有一个接口,访问该接口时报错:Request method ‘DELETE‘ not supported 错误原因:没有接收到前端传入的参数,修改为如下 参考 错误2:cannot r
错误1:启动docker镜像时报错:Error response from daemon: driver failed programming external connectivity on endpoint quirky_allen 解决方法:重启docker -&gt; systemctl r
错误1:private field ‘xxx‘ is never assigned 按Altʾnter快捷键,选择第2项 参考:https://blog.csdn.net/shi_hong_fei_hei/article/details/88814070 错误2:启动时报错,不能找到主启动类 #
报错如下,通过源不能下载,最后警告pip需升级版本 Requirement already satisfied: pip in c:\users\ychen\appdata\local\programs\python\python310\lib\site-packages (22.0.4) Coll
错误1:maven打包报错 错误还原:使用maven打包项目时报错如下 [ERROR] Failed to execute goal org.apache.maven.plugins:maven-resources-plugin:3.2.0:resources (default-resources)
错误1:服务调用时报错 服务消费者模块assess通过openFeign调用服务提供者模块hires 如下为服务提供者模块hires的控制层接口 @RestController @RequestMapping(&quot;/hires&quot;) public class FeignControl
错误1:运行项目后报如下错误 解决方案 报错2:Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.8.1:compile (default-compile) on project sb 解决方案:在pom.
参考 错误原因 过滤器或拦截器在生效时,redisTemplate还没有注入 解决方案:在注入容器时就生效 @Component //项目运行时就注入Spring容器 public class RedisBean { @Resource private RedisTemplate&lt;String
使用vite构建项目报错 C:\Users\ychen\work&gt;npm init @vitejs/app @vitejs/create-app is deprecated, use npm init vite instead C:\Users\ychen\AppData\Local\npm-
参考1 参考2 解决方案 # 点击安装源 协议选择 http:// 路径填写 mirrors.aliyun.com/centos/8.3.2011/BaseOS/x86_64/os URL类型 软件库URL 其他路径 # 版本 7 mirrors.aliyun.com/centos/7/os/x86
报错1 [root@slave1 data_mocker]# kafka-console-consumer.sh --bootstrap-server slave1:9092 --topic topic_db [2023-12-19 18:31:12,770] WARN [Consumer clie
错误1 # 重写数据 hive (edu)&gt; insert overwrite table dwd_trade_cart_add_inc &gt; select data.id, &gt; data.user_id, &gt; data.course_id, &gt; date_format(
错误1 hive (edu)&gt; insert into huanhuan values(1,&#39;haoge&#39;); Query ID = root_20240110071417_fe1517ad-3607-41f4-bdcf-d00b98ac443e Total jobs = 1
报错1:执行到如下就不执行了,没有显示Successfully registered new MBean. [root@slave1 bin]# /usr/local/software/flume-1.9.0/bin/flume-ng agent -n a1 -c /usr/local/softwa
虚拟及没有启动任何服务器查看jps会显示jps,如果没有显示任何东西 [root@slave2 ~]# jps 9647 Jps 解决方案 # 进入/tmp查看 [root@slave1 dfs]# cd /tmp [root@slave1 tmp]# ll 总用量 48 drwxr-xr-x. 2
报错1 hive&gt; show databases; OK Failed with exception java.io.IOException:java.lang.RuntimeException: Error in configuring object Time taken: 0.474 se
报错1 [root@localhost ~]# vim -bash: vim: 未找到命令 安装vim yum -y install vim* # 查看是否安装成功 [root@hadoop01 hadoop]# rpm -qa |grep vim vim-X11-7.4.629-8.el7_9.x
修改hadoop配置 vi /usr/local/software/hadoop-2.9.2/etc/hadoop/yarn-site.xml # 添加如下 &lt;configuration&gt; &lt;property&gt; &lt;name&gt;yarn.nodemanager.res