当前位置: 首页 > article >正文

【Vaadin flow 实战】第5讲-使用常用UI组件绘制页面元素

vaadin flow官方提供的UI组件文档地址是

https://vaadin.com/docs/latest/components

这里,我简单实战了官方提供的一些免费的UI组件,使用案例如下:

Accordion 手风琴

Accordion 手风琴效果组件

在这里插入图片描述

Accordion 手风琴-测试案例代码

@Slf4j
@PageTitle("HelpViewPage")
@Route(value = "helpView",layout = MainLayout.class)
@Menu(order = 5, icon = LineAwesomeIconUrl.FILE)
public class HelpView extends VerticalLayout{
    public HelpView() {
        Span s1 = new Span("手风琴");
        Accordion accordion = displayAccordion();
        add(s1,accordion);
    }
    private Accordion displayAccordion(){
        Accordion accordion = new Accordion();
        Span name = new Span("Sophia Williams");
        Span email = new Span("sophia.williams@company.com");
        Span phone = new Span("(501) 555-9128");
        VerticalLayout accordionItemLayout = new VerticalLayout(name,
                email, phone);
        accordionItemLayout.setSpacing(false);
        accordionItemLayout.setPadding(false);
        accordion.add("Personal information", accordionItemLayout);
        Span name2 = new Span("4027 Amber Lake Canyon");
        Span email2 = new Span("72333-5884 Cozy Nook");
        Span phone2 = new Span("Arkansas");
        VerticalLayout accordionItemLayout2 = new VerticalLayout(name2, email2, phone2);
        accordionItemLayout2.setSpacing(false);
        accordionItemLayout2.setPadding(false);
        accordion.add("Billing Address", accordionItemLayout2);
        return accordion;
    }
}

Avatar 头像

Avatar 头像

在这里插入图片描述

Avatar 头像-测试案例代码

@Slf4j
@PageTitle("HelpViewPage")
@Route(value = "helpView",layout = MainLayout.class)
@Menu(order = 5, icon = LineAwesomeIconUrl.FILE)
public class HelpView extends VerticalLayout{
    public HelpView() {
        Span s2 = new Span("Avatar 头像");
        Avatar avatarBasic = new Avatar();
        Avatar avatarName = new Avatar("TEST");

        AvatarGroup avatarGroup = new AvatarGroup();
        for (Country country : getCountries()) {
            String name = country.getName();
            AvatarGroup.AvatarGroupItem avatar = new AvatarGroup.AvatarGroupItem(name);
            avatarGroup.add(avatar);
        }

        Avatar userAvatar = new Avatar();
        userAvatar.setImage("https://images.unsplash.com/photo-1519681393784-d120267933ba?ixid=MXwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHw%3D&ixlib=rb-1.2.1&auto=format&fit=crop&w=750&q=80");
        add(s2,avatarBasic, avatarName,avatarGroup,userAvatar);
    }
 
}

Badge 徽章

在这里插入图片描述
Badge 徽章-测试案例代码

@Slf4j
@PageTitle("HelpViewPage")
@Route(value = "helpView",layout = MainLayout.class)
@Menu(order = 5, icon = LineAwesomeIconUrl.FILE)
public class HelpView extends VerticalLayout{
    public HelpView() {
           Span s3 = new Span("Badge 徽章");
        Span pending = new Span("Pending");
        pending.getElement().getThemeList().add("badge");
        Span confirmed = new Span("Confirmed");
        confirmed.getElement().getThemeList().add("badge success");
        Span denied = new Span("Denied");
        denied.getElement().getThemeList().add("badge error");
        Span onHold = new Span("On hold");
        onHold.getElement().getThemeList().add("badge contrast");
        HorizontalLayout hLayout = new HorizontalLayout(pending, confirmed, denied, onHold);

        // Icon before text
        Span pending1 = new Span(createIcon(VaadinIcon.CLOCK),
                new Span("Pending"));
        pending1.getElement().getThemeList().add("badge");
// Icon after text
        Span pending2 = new Span(new Span("Pending"),
                createIcon(VaadinIcon.CLOCK));
        pending2.getElement().getThemeList().add("badge");
        HorizontalLayout h2Layout = new HorizontalLayout(pending1, pending2);
        add(s3,hLayout,h2Layout);
    }
 
}

Button 按钮

在这里插入图片描述
Button 按钮-测试案例代码

@Slf4j
@PageTitle("HelpViewPage")
@Route(value = "helpView",layout = MainLayout.class)
@Menu(order = 5, icon = LineAwesomeIconUrl.FILE)
public class HelpView extends VerticalLayout{
    public HelpView() {
       Span s4 = new Span("Button");

        Button primaryButton = new Button("Primary");
        primaryButton.addThemeVariants(ButtonVariant.LUMO_PRIMARY);
        Button secondaryButton = new Button("Secondary");
        Button tertiaryButton = new Button("Tertiary");
        tertiaryButton.addThemeVariants(ButtonVariant.LUMO_TERTIARY);
        HorizontalLayout h3Layout = new HorizontalLayout(primaryButton, secondaryButton,tertiaryButton);

        Button primaryButton2 = new Button("Primary");
        primaryButton2.addThemeVariants(ButtonVariant.LUMO_PRIMARY, ButtonVariant.LUMO_ERROR);
        Button secondaryButton2 = new Button("Secondary");
        secondaryButton2.addThemeVariants(ButtonVariant.LUMO_ERROR);
        Button tertiaryButton2 = new Button("Tertiary");
        tertiaryButton2.addThemeVariants(ButtonVariant.LUMO_TERTIARY, ButtonVariant.LUMO_ERROR);
        HorizontalLayout h4Layout = new HorizontalLayout(primaryButton2, secondaryButton2,tertiaryButton2);

        Button primaryButton3 = new Button("Primary");
        primaryButton3.addThemeVariants(ButtonVariant.LUMO_PRIMARY,
                ButtonVariant.LUMO_WARNING);
        Button secondaryButton3 = new Button("Secondary");
        secondaryButton3.addThemeVariants(ButtonVariant.LUMO_WARNING);
        Button tertiaryButton3 = new Button("Tertiary");
        tertiaryButton3.addThemeVariants(ButtonVariant.LUMO_TERTIARY,
                ButtonVariant.LUMO_WARNING);
        HorizontalLayout h5Layout = new HorizontalLayout(primaryButton3, secondaryButton3,tertiaryButton3);

        Button largeButton = new Button("Large");
        largeButton.addThemeVariants(ButtonVariant.LUMO_LARGE);
        Button normalButton = new Button("Normal");
        Button smallButton = new Button("Small");
        smallButton.addThemeVariants(ButtonVariant.LUMO_SMALL);
        HorizontalLayout h6Layout = new HorizontalLayout(largeButton, normalButton,smallButton);

        add(s4,h3Layout,h4Layout,h5Layout,h6Layout);
    }
 
}

CheckboxGroup 多选框

在这里插入图片描述
CheckboxGroup 多选框-测试案例代码

@Slf4j
@PageTitle("HelpViewPage")
@Route(value = "helpView",layout = MainLayout.class)
@Menu(order = 5, icon = LineAwesomeIconUrl.FILE)
public class HelpView extends VerticalLayout{
    public HelpView() {
        Span s5 = new Span("CheckboxGroup-demo");
        CheckboxGroup<String> checkboxGroup = new CheckboxGroup<>();
        checkboxGroup.setLabel("Export data");
        checkboxGroup.setItems("Order ID", "Product name", "Customer",
                "Status");
        checkboxGroup.select("Order ID", "Customer");
        checkboxGroup.addThemeVariants(CheckboxGroupVariant.LUMO_VERTICAL);
        // 添加值改变事件监听器
        checkboxGroup.addValueChangeListener(event -> {
            // 处理选择的值
            Set<String> selectedValues = event.getValue();
            // 这里可以添加逻辑,比如更新 UI 或处理数据
            log.info("选中的checkbox:{}",selectedValues.toString());
        });
       
        add(s5,checkboxGroup);
    }
 
}

ComboBox 组合框(下拉框)

在这里插入图片描述
ComboBox 组合框-测试案例代码

@Slf4j
@PageTitle("HelpViewPage")
@Route(value = "helpView",layout = MainLayout.class)
@Menu(order = 5, icon = LineAwesomeIconUrl.FILE)
public class HelpView extends VerticalLayout{
    public HelpView() {
        Span s6 = new Span("ComboBox");
        ComboBox<Country> countryComboBox = new ComboBox<>("Select Country");
        countryComboBox.setItems(getCountries()); // 设置 ComboBox 的项
        countryComboBox.setItemLabelGenerator(Country::getName); // 用于前端显示的标签
        // 监听选项变化
        countryComboBox.addValueChangeListener(event -> {
            Country selectedCountry = event.getValue();
            if (selectedCountry != null) {
                Long selectedId = selectedCountry.getId(); // 获取 ID
                // 在这里可以处理 ID,如存储到数据库等
                log.info("Selected country id: {}", selectedId);
                Notification.show("选中了"+selectedCountry.getName());
            }
        });
        
        add(s6,countryComboBox);
    }
 
}

ConfirmDialog 对话框

在这里插入图片描述在这里插入图片描述
在这里插入图片描述
ConfirmDialog 对话框-测试案例代码

@Slf4j
@PageTitle("HelpViewPage")
@Route(value = "helpView",layout = MainLayout.class)
@Menu(order = 5, icon = LineAwesomeIconUrl.FILE)
public class HelpView extends VerticalLayout{
    public HelpView() {
        Span s7 = new Span("ConfirmDialog");
        //demo1 删除确认
        Button deleteButton = new Button("删除项");
        // 添加按钮点击事件
        deleteButton.addClickListener(event -> {
            // 创建确认对话框
            ConfirmDialog dialog = new ConfirmDialog();
            dialog.setHeader("确认");
            dialog.setText("您确定要删除该项吗?");

            // 设置确认按钮的事件
            dialog.setCancelable(true);
            dialog.setConfirmText("确认");
            dialog.setConfirmButtonTheme("error primary");
            dialog.setCancelText("取消");
            dialog.addConfirmListener(confirmEvent -> {
                // 处理确认事件
                log.info("确认删除");
                Notification.show("项已删除!");

            });
            dialog.addCancelListener(cancelEvent -> {
                // 处理取消事件
                log.info("操作已取消");
                Notification.show("操作已取消!");

            });

            // 显示对话框
            dialog.open();
        });

        //demo2 使用建议
        Button recommendButton = new Button("提示");
        recommendButton.addClickListener(event -> {
            ConfirmDialog dialog = new ConfirmDialog();
            dialog.setHeader("导出失败");
            dialog.setText(new Html(
                    "<p>导出报告Q4时出错。请重试,如果问题仍然存在,请联系 <a href=\"mailto:support@company.com\">support@company.com</a></p>"));
            dialog.setConfirmText("我知道了");
            dialog.addConfirmListener(confirmEvent -> {
                // 处理确认事件
                log.info("我知道了");
                Notification.show("我知道了!");
            });
            // 显示对话框
            dialog.open();
        });

        //demo3 拒绝按钮
        Button rejectButton = new Button("拒绝保存");
        rejectButton.addClickListener(event -> {
            ConfirmDialog dialog = new ConfirmDialog();
            dialog.setHeader("未保存的更改");
            dialog.setText(
                    "您想在导航离开之前放弃或保存更改吗");

            dialog.setCancelable(true);
            dialog.setCancelText("取消");
            dialog.addCancelListener(cancelEvent -> {
                // 处理取消事件
                log.info("操作已取消");
                Notification.show("操作已取消!");
            });
            dialog.setRejectable(true);
            dialog.setRejectText("丢弃变更");
            dialog.setConfirmText("保存变更");
            // 显示对话框
            dialog.open();
        });
        
        add(s7,deleteButton,recommendButton,rejectButton);
    }
 
}

DatePicker 日期选择

在这里插入图片描述
DatePicker 日期选择-测试案例代码

@Slf4j
@PageTitle("HelpViewPage")
@Route(value = "helpView",layout = MainLayout.class)
@Menu(order = 5, icon = LineAwesomeIconUrl.FILE)
public class HelpView extends VerticalLayout{
    public HelpView() {
        Span s8 = new Span("DatePicker");
        DatePicker datePicker = new DatePicker("选择日期");
        datePicker.setLabel("选择一个日期");
        // 设置日期格式
        datePicker.setI18n(new DatePicker.DatePickerI18n().setCancel("取消")
                .setToday("今天")
                .setMonthNames(List.of("一月", "二月", "三月", "四月", "五月", "六月",
                        "七月", "八月", "九月", "十月", "十一月", "十二月")));
        // 添加监听器以捕获日期选择事件
        datePicker.addValueChangeListener(event -> {
            // 获取选择的日期
            LocalDate date = event.getValue();
            log.info("选择的日期:{}",date.toString());
        });
      
        add(s8,datePicker);
    }
 
}

DateTimePicker 日期时间选择

在这里插入图片描述
DateTimePicker 日期时间选择-测试案例代码

@Slf4j
@PageTitle("HelpViewPage")
@Route(value = "helpView",layout = MainLayout.class)
@Menu(order = 5, icon = LineAwesomeIconUrl.FILE)
public class HelpView extends VerticalLayout{
    public HelpView() {
        Span s9 = new Span("DateTimePicker");
        DateTimePicker dateTimePicker = new DateTimePicker("选择日期和时间");
        // 可以设置默认值
        dateTimePicker.setValue(LocalDateTime.now());
        // 你可以为选择事件添加监听器
        dateTimePicker.addValueChangeListener(event -> {
            LocalDateTime selectedDateTime = event.getValue();
            System.out.println("选择的日期时间: " + selectedDateTime);
        });
       
        add(s9,dateTimePicker);
    }
 
}

TimePicker 时间选择

在这里插入图片描述
TimePicker 时间选择-测试案例代码

@Slf4j
@PageTitle("HelpViewPage")
@Route(value = "helpView",layout = MainLayout.class)
@Menu(order = 5, icon = LineAwesomeIconUrl.FILE)
public class HelpView extends VerticalLayout{
    public HelpView() {
       Span s010 = new Span("TimePicker");
        TimePicker timePicker = new TimePicker();
        timePicker.setLabel("Meeting time");
        timePicker.setStep(Duration.ofMinutes(30));
        timePicker.setValue(LocalTime.of(12, 30));
        
        add(s010,timePicker);
    }
 
}

Dialog 弹窗

在这里插入图片描述

在这里插入图片描述

在这里插入图片描述

Dialog 弹窗-测试案例代码

@Slf4j
@PageTitle("HelpViewPage")
@Route(value = "helpView",layout = MainLayout.class)
@Menu(order = 5, icon = LineAwesomeIconUrl.FILE)
public class HelpView extends VerticalLayout{
    public HelpView() {
       Span s10 = new Span("Dialog");
        Button showDialogButton = new Button("new弹窗");
        showDialogButton.addClickListener(event -> {
            Dialog dialog = new Dialog();
            dialog.setWidth("368px");
            dialog.setHeaderTitle("New employee");
            TextField tf1 = new TextField("First Name");
            tf1.setWidth("276px");
            TextField tf2 = new TextField("Last Name");
            tf2.setWidth("276px");
            VerticalLayout layout = new VerticalLayout();
            layout.add(tf1,tf2);
            dialog.add(layout);
            Button saveButton = new Button("Save",e->{

                String value = tf1.getValue();
                if (StringUtils.isEmpty(value)) {
                    Notification.show("First Name 不能为空!");
                }else {
                    s10.setText(value);
                    // 关闭对话框
                    dialog.close();
                }
            });
            saveButton.addThemeVariants(ButtonVariant.LUMO_PRIMARY);
            Button cancelButton = new Button("Cancel", e -> dialog.close());
            dialog.getFooter().add(cancelButton);
            dialog.getFooter().add(saveButton);
            // 显示对话框
            dialog.open();
        });

        Button openDialogButton = new Button("view弹窗", event -> openDialog());
        add(s10,showDialogButton,openDialogButton);
    }
 
    private void openDialog() {
        Dialog dialog = new Dialog();
        dialog.setWidth("388px"); // 设置弹窗宽度

        // 创建输入框
        TextField nameField = new TextField("Name", "Enter your name");
        nameField.setWidth("300px");
        nameField.setValue("test");
        nameField.setReadOnly(true);
        TextField emailField = new TextField("Email", "Enter your email");
        emailField.setWidth("300px");
        emailField.setValue("efdxuwef@163.com");
        emailField.setReadOnly(true);

        TextField addressField = new TextField("Address", "Enter your address");
        addressField.setWidth("300px");
        addressField.setValue("4188 Crystal Orchard, Mousie, USA");
        addressField.setReadOnly(true);



        VerticalLayout layout = new VerticalLayout();
        layout.add(nameField);
        layout.add(emailField);
        layout.add(addressField);

        // 添加输入框到对话框
        dialog.add(layout);

        dialog.setHeaderTitle("User details");

        Button closeButton = new Button(new Icon("lumo", "cross"),
                (e) -> dialog.close());
        closeButton.addThemeVariants(ButtonVariant.LUMO_TERTIARY);
        dialog.getHeader().add(closeButton);


        dialog.open();
    }
}

Input 各种输入窗

在这里插入图片描述
Input 各种输入窗-测试案例代码,需要在自定义css文件里配置css ,然后在Java中声明使用的组件css

.password-strength-week{
    color: red;
}

.password-strength-moderate{
    color: yellowgreen;
}


.password-strength-strong{
    color: darkgreen;
}
@Slf4j
@PageTitle("HelpViewPage")
@Route(value = "helpView",layout = MainLayout.class)
@Menu(order = 5, icon = LineAwesomeIconUrl.FILE)
public class HelpView extends VerticalLayout{
    public HelpView() {
         Span s11 = new Span("各种输入窗");
        EmailField validEmailField = new EmailField();
        validEmailField.setLabel("Email address");
        validEmailField.getElement().setAttribute("name", "email");
        validEmailField.setValue("julia@email.com");
        validEmailField.setErrorMessage("Enter a valid email address");
        validEmailField.setPrefixComponent(VaadinIcon.ENVELOPE.create());
        validEmailField.setClearButtonVisible(true);

        NumberField dollarField = new NumberField();
        dollarField.setLabel("Balance");
        dollarField.setValue(200.0);
        Div dollarPrefix = new Div();
        dollarPrefix.setText("$");
        dollarField.setPrefixComponent(dollarPrefix);
        dollarField.setClearButtonVisible(true);

        IntegerField integerField = new IntegerField();
        integerField.setLabel("Quantity");
        integerField.setHelperText("Max 10 items");
        integerField.setRequiredIndicatorVisible(true);
        integerField.setMin(1);
        integerField.setMax(10);
        integerField.setValue(2);
        integerField.setStepButtonsVisible(true);

        integerField.setI18n(new IntegerField.IntegerFieldI18n()
                .setRequiredErrorMessage("Field is required")
                .setBadInputErrorMessage("Invalid number format")
                .setMinErrorMessage("Quantity must be at least 1")
                .setMaxErrorMessage("Maximum 10 items available"));

        BigDecimalField bigDecimalField = new BigDecimalField();
        bigDecimalField.setLabel("Result");
        bigDecimalField.setWidth("240px");
        bigDecimalField.setValue(new BigDecimal("948205817.472950487"));


        IntegerField xField = new IntegerField();
        xField.setLabel("X");
        xField.setValue(-1284);


        NumberField numberField = new NumberField();
        numberField.setLabel("Duration (hours)");
        numberField.setStep(0.5);
        numberField.setValue(12.5);
        numberField.setStepButtonsVisible(true);
        numberField.setI18n(new NumberField.NumberFieldI18n()
                .setBadInputErrorMessage("Invalid number format")
                .setStepErrorMessage("Duration must be a multiple of 0.5"));

        PasswordField passwordField1 = new PasswordField();
        passwordField1.setLabel("Password");
        passwordField1.setValue("Ex@mplePassw0rd");
        passwordField1.setClearButtonVisible(true);
        passwordField1.setPrefixComponent(VaadinIcon.LOCK.create());


        HorizontalLayout layout = new HorizontalLayout();
//        layout.setPadding(true);
        layout.add(validEmailField);
        layout.add(dollarField);
        layout.add(integerField);
        layout.add(bigDecimalField);
        layout.add(xField);
        layout.add(numberField);
        layout.add(passwordField1);


        PasswordField passwordField = new PasswordField();
        passwordField.setLabel("Password2");

        Icon checkIcon = VaadinIcon.CHECK.create();
        checkIcon.setVisible(false);
        checkIcon.getStyle().set("color", "var(--lumo-success-color)");
        passwordField.setSuffixComponent(checkIcon);

        Div passwordStrength = new Div();
        Span passwordStrengthText = new Span("week");
        passwordStrengthText.setClassName("password-strength-week");
        passwordStrength.add(new Text("Password strength: "),
                passwordStrengthText);
        passwordField.setHelperComponent(passwordStrength);
        passwordField.setClearButtonVisible(false);


        passwordField.setValueChangeMode(ValueChangeMode.EAGER); //设置实时监听
        passwordField.addValueChangeListener(event -> {
            String value = event.getValue();
            log.info("ValueChangeListener value: {}" , value);

            if (value.length() <= 3) {
                checkIcon.setVisible(false);
                passwordStrengthText.setText("week");
                passwordStrengthText.setClassName("password-strength-week"); //使用了外部自定义CSS
            }
            if (value.length() >3 && value.length() <= 6) {
                checkIcon.setVisible(false);
                passwordStrengthText.setText("moderate");
                passwordStrengthText.setClassName("password-strength-moderate"); //使用了外部自定义CSS
            }
            if (value.length() >6 && value.length() <= 9) {
                passwordStrengthText.setText("strong");
                passwordStrengthText.setClassName("password-strength-strong"); //使用了外部自定义CSS
                checkIcon.setVisible(true);
            }
        });

        TextField textField = new TextField();
        textField.setLabel("Street Address");
        textField.setValue("Ruukinkatu 2");
        textField.setClearButtonVisible(true);
        textField.setPrefixComponent(VaadinIcon.MAP_MARKER.create());


        TextField phoneField = new TextField("Phone number");
        phoneField.setRequiredIndicatorVisible(true);
        phoneField.setPattern(
                "^[+]?[\\(]?[0-9]{3}[\\)]?[\\-]?[0-9]{3}[\\-]?[0-9]{4,6}$");
        phoneField.setAllowedCharPattern("[0-9()+-]");
        phoneField.setMinLength(5);
        phoneField.setMaxLength(18);
        phoneField.setHelperText("Format: +(123)456-7890");
        phoneField.setI18n(new TextField.TextFieldI18n()
                .setRequiredErrorMessage("Field is required")
                .setMinLengthErrorMessage("Minimum length is 5 characters")
                .setMaxLengthErrorMessage("Maximum length is 18 characters")
                .setPatternErrorMessage("Invalid phone number format"));


        TextArea textArea = new TextArea();
        textArea.setLabel("Comment");
        textArea.setMaxLength(150);
        textArea.setValueChangeMode(ValueChangeMode.EAGER);
        textArea.addValueChangeListener(e -> {
            e.getSource()
                    .setHelperText(e.getValue().length() + "/" + 150);
        });
        textArea.setValue("Great job. This is excellent!");


        TextField findField = new TextField();
        findField.setPlaceholder("Search");
        findField.setPrefixComponent(new Icon("lumo", "search"));
        findField.setTooltipText("Wrap in “quotes” for exact phrase");

        add(s11,layout,passwordField,textField,phoneField,textArea,findField);
    }
 
}

TabSheet 选项卡

在这里插入图片描述
TabSheet 选项卡-测试代码案例

@Slf4j
@PageTitle("HelpViewPage")
@Route(value = "helpView",layout = MainLayout.class)
@Menu(order = 5, icon = LineAwesomeIconUrl.FILE)
public class HelpView extends VerticalLayout{
    public HelpView() {
        TabSheet tabSheet = new TabSheet();
        tabSheet.add("Dashboard",
                new Div(new Text("This is the Dashboard tab content")));
        tabSheet.add("Payment",
                new Div(new Text("This is the Payment tab content")));
        tabSheet.add("Shipping",
                new Div(new Text("This is the Shipping tab content")));
        add(tabSheet);
    }
}

RadioButtonGroup 单选按钮组

在这里插入图片描述

RadioButtonGroup 单选按钮组-测试代码案例

@Slf4j
@PageTitle("HelpViewPage")
@Route(value = "helpView",layout = MainLayout.class)
@Menu(order = 5, icon = LineAwesomeIconUrl.FILE)
public class HelpView extends VerticalLayout{
    public HelpView() {
        RadioButtonGroup<String> radioGroup = new RadioButtonGroup<>();
        radioGroup.addThemeVariants(RadioGroupVariant.LUMO_VERTICAL);
        radioGroup.setLabel("Travel class");
        radioGroup.setItems("Economy", "Business", "First Class");
        radioGroup.addValueChangeListener(event -> {
            String value = event.getValue();
            log.info("RadioButtonGroup ValueChangeListener value: {}" , value);
        });
        
        add(radioGroup);
}
}

ProgressBar 进度条

在这里插入图片描述
ProgressBar 进度条-测试代码案例

@Slf4j
@PageTitle("HelpViewPage")
@Route(value = "helpView",layout = MainLayout.class)
@Menu(order = 5, icon = LineAwesomeIconUrl.FILE)
public class HelpView extends VerticalLayout{
    public HelpView() {
ProgressBar progressBar = new ProgressBar();
        progressBar.setValue(0.5);

        ProgressBar progressBar2 = new ProgressBar();
        progressBar2.setIndeterminate(true);

        // Contrast
        ProgressBar progressBarContrast = new ProgressBar();
        progressBarContrast.addThemeVariants(ProgressBarVariant.LUMO_CONTRAST);
        progressBarContrast.setValue(0.5);

// Success
        ProgressBar progressBarSuccess = new ProgressBar();
        progressBarSuccess.addThemeVariants(ProgressBarVariant.LUMO_SUCCESS);
        progressBarSuccess.setValue(0.75);

// Error
        ProgressBar progressBarError = new ProgressBar();
        progressBarError.addThemeVariants(ProgressBarVariant.LUMO_ERROR);
        progressBarError.setValue(0.2);

        add(progressBar,progressBar2,progressBarContrast,progressBarSuccess,progressBarError);

ProgressBar progressBarExport = new ProgressBar();
        progressBarExport.setIndeterminate(true);
        // Associates the labels with the bar programmatically, for screen
// readers:
        progressBarExport.getElement().setAttribute("aria-labelledby", "pblbl");
        progressBarExport.getElement().setAttribute("aria-describedby", "sublbl");

        NativeLabel progressBarLabel = new NativeLabel("Generating report...");
        progressBarLabel.setId("pblbl");
        progressBarLabel.addClassName(LumoUtility.TextColor.SECONDARY);

        Span progressBarSubLabel = new Span("Process can take upwards of 10 minutes");
        progressBarSubLabel.setId("sublbl");
        progressBarSubLabel.addClassNames(LumoUtility.TextColor.SECONDARY, LumoUtility.FontSize.XSMALL);

        add(progressBarLabel, progressBarExport, progressBarSubLabel);
        }
  }

MultiSelectComboBox 多选下拉框

在这里插入图片描述

MultiSelectComboBox 多选下拉框-测试代码案例

@Slf4j
@PageTitle("HelpViewPage")
@Route(value = "helpView",layout = MainLayout.class)
@Menu(order = 5, icon = LineAwesomeIconUrl.FILE)
public class HelpView extends VerticalLayout{
    public HelpView() {
        Span s16 = new Span("MultiSelectComboBox demo");
        MultiSelectComboBox<Country> comboBox = new MultiSelectComboBox<>(
                "Countries");
        comboBox.setItems(getCountries());
        comboBox.setItemLabelGenerator(Country::getName);
        comboBox.addValueChangeListener(event -> {
            Set<Country> countrySet =  event.getValue();
            log.info("countrySet: {}", countrySet);
        });
 
        add(s16,comboBox);
}
}

MessageInput 消息输入框

在这里插入图片描述
在这里插入图片描述
MessageInput 消息输入框-测试代码案例

@Slf4j
@PageTitle("HelpViewPage")
@Route(value = "helpView",layout = MainLayout.class)
@Menu(order = 5, icon = LineAwesomeIconUrl.FILE)
public class HelpView extends VerticalLayout{
    public HelpView() {
MessageInput input = new MessageInput();
        input.addSubmitListener(submitEvent -> {
            Notification.show("Message received: " + submitEvent.getValue(),
                    3000, Notification.Position.MIDDLE);
        });
        add(input);
 }}

Notification 通知

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

Notification 通知–测试代码案例

Span s18 = new Span("Notification demo");
        Button toast1 = new Button("toast1", event -> {
            // When creating a notification using the `show` static method,
// the duration is 5-sec by default.
            Notification.show("Financial report generated");
        });

        Button toast2 = new Button("toast2", event -> {
            Notification notification = Notification.show("Application submitted!");
            notification.addThemeVariants(NotificationVariant.LUMO_SUCCESS);
        });

        Button toast3 = new Button("toast3",evt -> {
            Notification notification = new Notification();
            notification.addThemeVariants(NotificationVariant.LUMO_WARNING);
            Div text = new Div(new Text(
                    "Your session will expire in 5 minutes due to inactivity."),
                    new HtmlComponent("br"),
                    new Text("Close this warning to continue working."));
            Button closeButton = new Button(new Icon("lumo", "cross"));
            closeButton.addThemeVariants(ButtonVariant.LUMO_TERTIARY_INLINE);
            closeButton.setAriaLabel("Close");
            closeButton.addClickListener(event -> {
                notification.close();
            });
            HorizontalLayout layoutH = new HorizontalLayout(text, closeButton);
            layoutH.setAlignItems(Alignment.CENTER);
            notification.add(layoutH);
            notification.open();
        });

        Button toast4 = new Button("toast4",evt -> {
            Notification notification = new Notification();
            notification.addThemeVariants(NotificationVariant.LUMO_ERROR);
            Div text = new Div(new Text("Failed to generate report"));
            Button closeButton = new Button(new Icon("lumo", "cross"));
            closeButton.addThemeVariants(ButtonVariant.LUMO_TERTIARY_INLINE);
            closeButton.setAriaLabel("Close");
            closeButton.addClickListener(event -> {
                notification.close();
            });
            HorizontalLayout layoutH = new HorizontalLayout(text, closeButton);
            layoutH.setAlignItems(Alignment.CENTER);
            notification.add(layoutH);
            notification.open();
        });
       
        add(s18,toast1,toast2,toast3,toast4);

MultiSelectListBox 列表框

在这里插入图片描述
MultiSelectListBox 列表框-测试代码案例

//列表框允许用户从可滚动的项目列表中选择一个或多个值
        Span s19 = new Span("MultiSelectListBox demo");
        MultiSelectListBox<Country> listBox = new MultiSelectListBox<>();
        listBox.setItems(getCountries());
        listBox.select(getCountries().get(0), getCountries().get(3));
        listBox.setHeight("200px");
        listBox.setClassName("lstbox"); //这里使用了自定义CSS文件中的CSS类名
        listBox.setTooltipText("this is a listbox");
        // 设置展示给用户的名称
        listBox.setItemLabelGenerator(Country::getName);
        // 添加一个值改变监听器
        listBox.addValueChangeListener(event -> {
            String selectedCountries = event.getValue().stream()
                    .map(Country::getName)
                    .reduce((a, b) -> a + ", " + b)
                    .orElse("No countries selected");
            Notification.show(selectedCountries);
        });
        add(s19,listBox);

对应的自定义CSS配置
在这里插入图片描述

绘制自定义卡片

在这里插入图片描述
测试代码案例, 需要在自定义css文件里配置css ,然后在Java中声明使用的组件css

.card {
    transition: transform 0.2s;
}

.card:hover {
    transform: scale(1.05);
}
 Div card = new Div();
        card.setClassName("card"); //使用的自定义css
        card.getElement().getStyle().set("border", "1px solid #ccc");
        card.getElement().getStyle().set("border-radius", "5px");
        card.getElement().getStyle().set("padding", "16px");
        card.getElement().getStyle().set("width", "300px");
        card.getElement().getStyle().set("box-shadow", "0 4px 8px rgba(0,0,0,0.1)");

        // 添加标题
        H3 title = new H3("Card Title");
        card.add(title);

        // 添加图片
//        Image image = new Image("https://via.placeholder.com/300", "Placeholder image");
        Image image = new Image("https://images.unsplash.com/photo-1512273222628-4daea6e55abb?ixid=MXwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHw%3D&ixlib=rb-1.2.1&auto=format&fit=crop&w=750&q=80", "Placeholder image");
        image.setWidth("300px");
        card.add(image);
        // 添加按钮
        Button button = new Button("Click me");
        card.add(button);
        add(card);

FormLayout 表单布局

在这里插入图片描述
测试代码案例

Span fSpan = new Span("FormLayout demo");
        TextField firstName = new TextField("First name");
        TextField lastName = new TextField("Last name");
        TextField username = new TextField("Username");
        PasswordField password = new PasswordField("Password");
        PasswordField confirmPassword = new PasswordField("Confirm password");
        FormLayout formLayout = new FormLayout();
        formLayout.add(firstName, lastName, username, password, confirmPassword);
        formLayout.setResponsiveSteps(
                // Use one column by default
                new FormLayout.ResponsiveStep("0", 1),
                // Use two columns, if layout's width exceeds 500px
                new FormLayout.ResponsiveStep("500px", 2));
// Stretch the username field over 2 columns
        formLayout.setColspan(username, 2);
        
        add(fSpan,formLayout);

Upload 文件上传组件

在这里插入图片描述
测试代码案例

Span sSpan = new Span("Upload demo");
        MultiFileMemoryBuffer buffer = new MultiFileMemoryBuffer();
        Upload upload = new Upload(buffer);
        //限制上传文件格式
        //  upload.setAcceptedFileTypes("application/pdf", ".pdf");
        //默认情况下,“上传”不限制可以上传的文件数量。但是,您可以设置文件计数限制
        upload.setMaxFiles(3);
        //设置最大字节数来限制文件大小。但默认情况下,没有限制
        // 10MB
        int maxFileSizeInBytes = 10 * 1024 * 1024;
        upload.setMaxFileSize(maxFileSizeInBytes);
        upload.addSucceededListener(event -> {
            String fileName = event.getFileName();
            log.info("fileName:{}", fileName);
            String mainName = FileNameUtil.mainName(fileName);
            log.info("file mainName:{}", mainName);
            String extName = FileNameUtil.extName(fileName);
            log.info("file extName:{}", extName);
            InputStream in = buffer.getInputStream(fileName);
            // Do something with the file data
            // processFile(inputStream, fileName);
            BufferedOutputStream out = FileUtil.getOutputStream("/Users/xxx/Documents/"+fileName);
            long copySize = IoUtil.copy(in, out, IoUtil.DEFAULT_BUFFER_SIZE);
            System.err.println(copySize);
            IoUtil.closeIfPosible(in);
            IoUtil.closeIfPosible(out);
        });
        upload.addFileRejectedListener(event -> {
            String errorMessage = event.getErrorMessage();
            Notification notification = Notification.show(errorMessage, 5000,
                    Notification.Position.MIDDLE);
            notification.addThemeVariants(NotificationVariant.LUMO_ERROR);
        });

        
        add(sSpan,upload);

Image 图片展示组件

在这里插入图片描述
测试代码案例

//        Image imageTest = new Image("images/empty-plant.png", "My Alt Image");
        Image imageTest = new Image("https://images.unsplash.com/photo-1519681393784-d120267933ba?ixid=MXwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHw%3D&ixlib=rb-1.2.1&auto=format&fit=crop&w=750&q=80", "My Alt Image");
        SvgIcon svgIcon = new SvgIcon();
        svgIcon.setSrc("icons/hellokitty_1.svg");
        SvgIcon svgIcon2 = new SvgIcon();
        svgIcon2.setSrc("icons/hellokitty.svg");

        SvgIcon svgIcon3 = new SvgIcon();
        svgIcon3.setSrc("icons/hello.svg");

        add(imageTest,svgIcon,svgIcon2,svgIcon3);

http://www.kler.cn/a/528746.html

相关文章:

  • 数据密码解锁之DeepSeek 和其他 AI 大模型对比的神秘面纱
  • (leetcode 213 打家劫舍ii)
  • 新能源算力战争:为什么AI大模型需要绿色数据中心?
  • 单细胞分析基础-第一节 数据质控、降维聚类
  • llama.cpp LLM_CHAT_TEMPLATE_DEEPSEEK_3
  • C#,入门教程(12)——数组及数组使用的基础知识
  • TOF技术原理和静噪对策
  • std::call_once的原理及使用
  • fpga系列 HDL:XILINX Vivado ILA FPGA 在线逻辑分析
  • CF 581A.Vasya the Hipster(Java实现)
  • XML DOM - 访问节点
  • Java线程认识和Object的一些方法ObjectMonitor
  • 基于 STM32 的智能电梯控制系统
  • SZU大学物理2实验报告|超声探伤实验
  • GPG格式介绍:什么是GPG?如何加密和解密?
  • C++哈希(链地址法)(二)详解
  • AI智能化模型助力太阳能光伏板自动巡检运维,基于YOLOv5全系列【n/s/m/l/x】参数模型开发构建无人机航拍场景下太阳能光伏板污损缺陷智能检测识别系统
  • K8S ReplicaSet 控制器
  • Electricity Market Optimization 探索系列(一)
  • 【SQL】SQL注入知识总结
  • 【Java异步编程】CompletableFuture实现:异步任务的合并执行
  • 跨平台的客户端gui到底是选“原生”还是web
  • Vue.js组件开发-实现全屏幻灯片左右切换特效
  • C# 语言基础全面解析
  • 网站快速收录:利用网站导航优化用户体验
  • Pandas基础07(Csv/Excel/Mysql数据的存储与读取)