如果设置了Leadcomponent方法,则所有btns都返回相同的名称,但是我为每个按钮设置了不同的名称。如果我注释掉Leadcomponent行,它可以正常工作。会发生什么事?我将setName设置为所有按钮,以便可以应用动作侦听器并根据返回的名称打开不同的表单。
我的代码:
BorderLayout gl1 = new BorderLayout();
Container middleContainer = new Container(gl1);
parentContiner.addComponent(middleContainer);
GridLayout gl2 = new GridLayout(counter / 3 + 1, 3);
gl2.setAutoFit(true);
Container gridContainer = new Container(gl2);
parentContiner.addComponent(gridContainer);
for (HashMap<String, Object> entry : homeStorage) {
if (!"".equals(entry.get("img").toString())) {
counter++;
Button homeButton = new Button();
id = entry.get("id").toString();
imageUrl = entry.get("img").toString();
title = entry.get("name").toString();
homePlaceholder = homePlaceholder.scaled(screenWidth / 3 - 17, screenWidth / 3 - 17);
encodedHomePlaceholder = EncodedImage.createFromImage(homePlaceholder, true);
Image btnIcon = URLImage.createToStorage(encodedHomePlaceholder, "home_" + title + imageUrl, allUrl.globalHomeImageUrl + imageUrl, URLImage.RESIZE_SCALE_TO_FILL);
homeButton.setIcon(btnIcon);
***//set the name of button to id***
homeButton.setName(id);
TextArea buttonTitle = new TextArea(properCase(title));
buttonTitle.setEditable(false);
buttonTitle.setGrowByContent(true);
buttonTitle.setGrowLimit(2);
buttonTitle.setScrollVisible(false);
Container containerBtnTitle = new Container(new FlowLayout(Label.RIGHT, Label.BOTTOM));
containerBtnTitle.add(buttonTitle);
gridContainer.add(LayeredLayout.encloseIn(homeButton, containerBtnTitle));
**//if i remove this line(setLeadcomponent) it works (ie returns different name as set above, otherwise all the button returns the same name (ie last id)**
gridContainer.setLeadComponent(homeButton);
gridContainer.revalidate();
}
homeButton.addActionListener((e) -> {
if (homeButton.getName().equals("3")) {
showForm("YoutubeVideos", null);
} else if (homeButton.getName().equals("17")) {
showForm("k2Gallery", null);
} else if (homeButton.getName().equals("15")) {
showForm("EmergencyCategory", null);
} else if (homeButton.getName().equals("2")) {
showForm("PartyClicks", null);
} else if (homeButton.getName().equals("1")) {
showForm("WhereTheParty", null);
} else if (homeButton.getName().equals("5")) {
showForm("CocktailRecipies", null);
}
});
}
最佳答案
每个容器只能包含1个铅组分。
您正在创建一些homeButton,但是您有1个gridContainer。