Specify a background image via CSS in Vaadin 14 programmatically with Java

Bas*_*que 2 css background-image vaadin vaadin-flow

In Vaadin 14, we can set some CSS values programmatically in our Java code.

We can call getElement, then getStyle, and set the name of the CSS property along with a value.

For example, here we set the background color to green.

public class MainView extends VerticalLayout
{
    public MainView ( )
    {
        this.getElement().getStyle().set( "background-color" , "Green" );
Run Code Online (Sandbox Code Playgroud)

How do we do this for a CSS property like background-image that takes an argument of the CSS function named url?

Hard-coding the CSS path does not work.

public class MainView extends VerticalLayout
{
    public MainView ( )
    {
        this.getElement().getStyle().set( "background-image" , "cat.jpg" );
Run Code Online (Sandbox Code Playgroud)

? In Vaadin Flow, how to do we use Java to get CSS to find an image such as "cat.jpg"?

Furthermore, what should be the relative or absolute path to that image file be? I understand that the usual place for static images in Vaadin web app is in the src/main/resources folder.

ana*_*smi 5

如果是“普通Java Servlet”(非Spring,非CDI)Vaadin项目,则该文件应位于/src/main/webapp

如果是春季: /src/main/resources/META-INF/resources/img

摘自此处的官方文档:资源备忘单

并且,正如@symlink在注释中注意到的那样,您应该使用url('filename')语法在css中引用图像:CSS background-image属性

举例来说,如果我有一个文件名为cat.jpg/src/main/webapp/images,那么这台就getElement().getStyle().set("background-image","url('images/cat.jpg')");


下面是另一个例子,与图片文件cat.jpgsrc/main/webapp没有在嵌套images文件夹中。这是一个Vaadin 14.0.10 Web应用程序,使用“ 使用Vaadin启动新项目”页面Plain Java Servlet上的技术堆栈选项。

项目文件夹src / main / webapp中的“ cat.jpg”文件的屏幕截图。

以下是使用此图像作为背景的整个视图的源代码。

注意构造函数的第一行,我们将其"url('cat.jpg')"作为参数传递。了解我们如何在文件名周围使用单引号将其嵌入Java字符串而不进行转义。幸运的是,CSS规范允许使用单引号(')或双引号(“)-对于Vaadin程序员而言,将CSS嵌入Java代码中非常方便。

package work.basil.example;

import com.vaadin.flow.component.button.Button;
import com.vaadin.flow.component.notification.Notification;
import com.vaadin.flow.component.orderedlayout.VerticalLayout;
import com.vaadin.flow.router.Route;
import com.vaadin.flow.server.PWA;

/**
 * The main view contains a button and a click listener.
 */
@Route ( "" )
@PWA ( name = "Project Base for Vaadin", shortName = "Project Base" )
public class MainView extends VerticalLayout
{
    public MainView ( )
    {
        this.getElement().getStyle().set( "background-image" , "url('cat.jpg')" );

        Button button = new Button( "Click me" , event -> Notification.show( "Clicked!" ) );
        add( button );
    }
}
Run Code Online (Sandbox Code Playgroud)

以及此网络应用程序的屏幕截图。由于图像的高度短,图像被裁剪VerticalLayout。布局很短,因为它只包含一个按钮,其标签Click me的左侧边缘上的蓝色文本隐约可见。裁剪后的猫咪的脸在页面上重复,这是CSS的默认设置。

Vaadin 14.0.10 Web应用程序的屏幕截图,背景中使用了猫图片