You doubt when creating a java component in netbeans

0

I have been programming for a short time and I am learning. My doubt is that I want to create a component (Bean) in netbeans that when I insert it in a Frame the button that I insert, I change the color of the button every time I press it.

I've done this but I do not know if I'm on the right track because when I insert the component (the button) into a jframe, it does not do anything.

import java.beans.*;
import java.io.Serializable;
import javax.swing.JButton;

public class LblBotonColores extends JButton implements Serializable {
    private boolean cambioColor;

    public boolean getCambioColor() {
        return cambioColor;
    }

    public void setCambioColor(boolean cambioColor) {
        this.cambioColor = cambioColor;
    }

    public LblBotonColores() {

        JButton miBoton = new JButton("Hola Mundo");

        if(getCambioColor()){

            miBoton.setBackground(Color.RED);
        }else{
            miBoton.setBackground(Color.BLUE);
        } 
    }

}

Thank you very much.

    
asked by Antonio 25.10.2018 в 19:38
source

1 answer

1

I did a tutorial on how to achieve what what do you want since there are many steps.

The essential problem that I see in your code is that it does not do what you had thought because there is no data that allows you to know the current state.

A good technique to avoid this kind of problem is to first do what you call the data model, that is, first to detect what subjects we have, in our case it is about knowing if the color is blue and if we should change it.

We add the variables to the class

private boolean changeColor;

private boolean azul = true;

public boolean getCambioColor() {
    return cambioColor;
}

public void setCambioColor(boolean cambioColor) {
    this.cambioColor = cambioColor;
}

And in our constructor we make sure that there is an initial state

 setBackground(Color.blue);

In the method to change the color we simply put our condition so that it activates if we want it to have the ability to change color and change to the opposite color based on the other variable

  if (cambioColor) {
        if (azul) {
            setBackground(Color.red);
            azul = !azul;
        } else {
            setBackground(Color.blue);
            azul = !azul;
        }
    }

Well ... we have finished, the result is a button that you can use in your palette of netbeans components, if you want to change it from the properties palette you must setter and getter the configurable variables, so blue It does not come out as you can see.

After running the example, you will see that it shows you your button and that it has the behavior you were looking for

    
answered by 15.12.2018 / 02:16
source