简体   繁体   中英

how to change label color on click?

if I try to to run the for loop till 10 it is keep printing the same label 10 times. and if I change till function.size and it will print number of function times. color is changing only inside the same labels, not effecting the other labels. I have variables are string that I am printing on label,how should I assign the string to ArryList? final List labels = new ArrayList();

                for(int k = 0; k <=1; k++) {
                     final Label label = new Label(FDTO.getFunctionName());

                   // final  Label functionLabel = new Label(FDTO.getFunctionName());
                    label.addClickHandler(new ClickHandler() {     

                    public void onClick(ClickEvent event) {

                         for(Label otherLabel  : labels)
                             otherLabel.getElement().getStyle().setColor("black");
                        // functionLabel.getElement().getStyle().setColor("red");
                        label.getElement().getStyle().setColor("red");
                        checkChild(FDTO.getFunctionCode(), functions, qaDTO, val);
                    }
                });

                    labels.add(label);


                    childPanel.add(label);
        }

In your ClickHandler you just need to set all other labels` color back to default (black?).

otherLabel.getElement().getStyle().setColor("black");

If there are many other labels you should consider keeping them in a List . Please, try this little example:

final List<Label> labels = new ArrayList<Label>();

for(int i = 0; i < 10; i++) {
    final Label label = new Label("Hello " + i);
    label.addClickHandler(new ClickHandler() {
        @Override
        public void onClick(ClickEvent event) {
            // change all labels color back to default
            for(Label otherLabel : labels)
                otherLabel.getElement().getStyle().setColor("black");

            // change current label color 
            label.getElement().getStyle().setColor("red");
        }
    });

    // add to list
    labels.add(label);

    RootPanel.get().add(label);
}

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