简体   繁体   中英

JAVA GWT change widget color on click

I have a custom class which extends Composite which extends widget. I have added a domHandler to handle ClickEvents. Currently I am setting the color to blue on click. The widget belongs to a panel which contains many of this same time of widget (TripEventItem). I want the color to change back to black text when a different widget is clicked on. Any idea how to do this?

final TripEventItem item = new TripEventItem(results.get(i), tripNumber);
        tripNumber++;
        item.addDomHandler(new ClickHandler() {
            @Override
            public void onClick(ClickEvent event) {
                finalResults.get(item.getTripId() - 1);
                List<LocationEvent> events = item.getTripEvent();
                listener.displayResults(new ArrayList(events));
                item.getElement().getStyle().setColor("blue");
            }
        }, ClickEvent.getType());

When an item is clicked, in your handler you can't know the state of the other items. You can keep all the items in a list. Then iterate this list and place your dom handlers. You onClick must iterate this list and restore the color. Then for the current item you apply the changes caused by the click event.

A rough example would be something like this

final List<TripEventItem> items = new ArrayList<>();
for(int i = 0; i < results.size(); i++) {       
    final TripEventItem item = new TripEventItem(results.get(i), tripNumber);
    items.add(item);
}

for(int i = 0; i < items.size(); i++) {
    final TripEventItem item = items.get(i);
    item.addDomHandler(new ClickHandler() {
        @Override
        public void onClick(ClickEvent event) {
            for(int i = 0; i < items.size(); i++) {
                TripEventItem otherItem = items.get(i);
                restore(otherItem);
            }

            item.getElement().getStyle().setColor("blue");
        }
    }, ClickEvent.getType());
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM