How to change a specific Button's background color programmatically?

Viewed 158

I have managed to figure out the basics of the Theme editor and set the basic values for the Components I am interested in.

I am using ComponentSelector Components across the application, so I am able to choose any Component easily.

Now, I want to change the background color of specific Buttons in run time. What would be the best way to do so?

1 Answers

First of all, for a new app, you should use the theme.css file instead of the Theme editor.

Said that, changing the background color of specific Buttons in run time using the ComponentSelector can be done in the following way.

Assume to have a theme.css containing:

#Constants {
    includeNativeBool: true;
}

Button {
    margin: 0.5mm;
    padding: 0.5mm;
    color: white;
    border: none;
}

Button-Red {
    cn1-derive: Button;
    background-color: red;
}

Button-Green {
    cn1-derive: Button;
    background-color: green;
}

Case of only one Button (note that I use the .asComponent() method to select only one Component, even if it's not necessary in this case):

Form hi = new Form("Hi World", BoxLayout.y());
Button myBtn = new Button("My fun button", "Button-Red");
hi.add(FlowLayout.encloseCenter(myBtn));
hi.show();

UITimer.timer(2000, false, hi, () -> {
    // this code changes the color of the button after two second
    ComponentSelector.$("Button-Red").asComponent().setUIID("Button-Green");
    hi.revalidate();
});

Case of multiple Buttons:

Form hi = new Form("Hi World", BoxLayout.y());
Button myBtn1 = new Button("My fun button 1", "Button-Red");
Button myBtn2 = new Button("My fun button 2", "Button-Red");
hi.add(FlowLayout.encloseCenter(myBtn1));
hi.add(FlowLayout.encloseCenter(myBtn2));
hi.show();

UITimer.timer(2000, false, hi, () -> {
    // this code changes the color of the buttons after two second
    ComponentSelector.$("Button-Red").setUIID("Button-Green");
    hi.revalidate();
});

Of course you can use different ways to select the components you are interested to, according to the documentation: https://www.codenameone.com/javadoc/com/codename1/ui/ComponentSelector.html

Related