vaadin 14 ContextMenu

final Button button = new Button(“/Setup.png”,“Setup”,false);
button.setWidth(“120px”);
final ContextMenu contextMenu = new ContextMenu();
contextMenu.setOpenOnClick(true);
contextMenu.getElement().getStyle().set(“text-align”, “center”);
contextMenu.setTarget(button);
Image options=new Image(“img/MenuIcons/SetupDesk.png”,“”);
options.setTitle(“Student”);
contextMenu.addItem(options,event →
test()
);
it is working fine .but image caption not setting ?what is the problem in this code???Give me any idea…

hi, it would be very helpful if you could describe what you are trying to do

i want to create button with contextMenu

Alright, here you go:

Button btn = new Button("Click me to open menu");
ContextMenu menu = new ContextMenu();
menu.addItem("Foo");
menu.setOpenOnClick(true);
menu.setTarget(btn);
add(btn);

i am adding this things not working

Image options=new Image(“img/MenuIcons/SetupDesk.png”,“”);
options.setTitle(“Student”);
contextMenu.addItem(options,event →
test()
);

any error in this code?

ok so what is it you are trying to do?

Add a menu item with an image instead of text?

i want to try like this

image.png

ok that helps a lot. And in what way is it not working? Are you getting an error, or is the image not showing?

image sowing but caption is missing?

Your code has never added a caption to the image.

options.setTitle(“Student”);

That’s a title - did you ever see a titel next to an image on any web page?

https://www.w3schools.com/tags/tag_img.asp

the method is perhaps unfortunately named after the html attribute that it creates, which is used for a tooltip.

If you’re using an IDE that shows you the documentation for methods, you would see that in the description
image.png

here is an example of how to create menu items with icons etc: https://vaadin.com/docs/latest/components/context-menu/#custom-items

(it’s a bit complicated because it demonstrates multiple things in the same example, but the important part is that you need to combine an image and a text element (e.g. a Span) in a container (e.g. HorizontalLayout) that you put into the menu item

so, something along the lines of:

Button btn = new Button("Click me to open menu");
btn.addThemeVariants(ButtonVariant.LUMO_PRIMARY);

HorizontalLayout itemLayout = new HorizontalLayout();
itemLayout.add(new Image("your-image-path-here", "text alternative for image"));
itemLayout.add(new Span("The caption for the item, next to image"));

ContextMenu menu = new ContextMenu();
menu.addItem(itemLayout);
menu.setOpenOnClick(true);
menu.setTarget(btn);
add(btn);