Search code examples
javaswingloopsjbuttonsubclassing

Set properties of multiple different JButtons in a loop


String[] objectName = {  //these are all names for JButtons
            "firstBtn",
            "secondBtn",
            "thirdBtn",
            "coin1",
            "coin5",
            "coin25",
            "coin100"
    };    

for (int k=0;k<objectName.length;k++){
    objectName[o].setOpaque(false);
    objectName[o].setContentAreaFilled(false);
    objectName[o].setBorderPainted(false);
}

I was trying to shorten code in this way because i thought it would be easier. However it does not work. Is there a way to make this code work or do i have to write the same thing again and again for each JButton


Solution

  • you could subclass JButton and do the following,

    public class MyButton extends JButton{
        public MyButton(){
            setOpaque(false);
            setContentAreaFilled(false);
            setBorderPainted(false);
        }
    }
    

    and then create instances,

    JButton firstBtn = new MyButton();
    .
    .