Search code examples
javacssvaadinvaadin7

Vaadin: Using an image as a button


I wanted to use a image as a button. I got it working, but it is not very well made, please take a look at the screenshot. As you can see the Button itself is a lot bigger than the image, but I wanted it to be as big as the image:

enter image description here

The actual Button is bigger than the Image. The goal here is that there is nothing but the image to click. How can I achieve this? Here is the code ofthe button on the screenshot:

 Button testButton = new Button();
 String basepath = VaadinService.getCurrent().getBaseDirectory().getAbsolutePath();
 testButton.setIcon(new FileResource(new File(basepath + "/VAADIN/themes/mytheme/img/Button.png")));
 loginForm.addComponent(testButton);

I know that

testButton.setStyleName(BaseTheme.BUTTON_LINK)

makes the button invisible, but unfortunately that does not adjust the size of the button, just the visbility..


Solution

  • You can simply add a click listner to an image instead of using a button.

    Image image = new Image(null, new ClassResource("/images/button-img.jpg");
    image.addClickListener(e -> System.out.println("click"));
    image.addStyleName("my-img-button");
    

    And add this css, I use the @Stylesheet annotation to add in CSS.

    .my-img-button {
    cursor: pointer;
    }