Search code examples
javaswinglayout-managergrid-layout

GridLayout - JButtons, array and images?


I would like to make a 9x9 array, and upload the array with JButtons, which is an icon. I don't really understand why isn't it working... I hope you can help, thank you!

    BWbutton buttons[][] = new BWbutton[9][9];

    JPanel p1 = new JPanel();
    p1.setBackground(Color.white);
    p1.setPreferredSize(new Dimension(500,500));
    p1.setLayout(new GridLayout(9,9,40,40));


   for(int i=0; i<9; i++){
        for(int j=0; j<9; j++){
            buttons[i][j]=new BWbutton();
            p1.add(buttons[i][j]);
    }   
    }

BWbutton.java:

import javax.swing.*;

public class BWbutton extends JButton{

        public BWbutton(){
            ImageIcon icon = new ImageIcon("image.png");
            JButton bt1 = new JButton(icon);
        }

}

Solution

  • You extend the JButton class, but then in your code you create a new JButton:

    ImageIcon icon = new ImageIcon("image.png");
    JButton bt1 = new JButton(icon);
    

    This means you have two buttons:

    1. the class itself which you add to the GUI without an Icon and
    2. the button that you create but never use.

    Don't create a new JButton. Instead all you need is:

    ImageIcon icon = new ImageIcon("image.png");
    //JButton bt1 = new JButton(icon);
    setIcon( icon );
    

    Better yet don't even create a BWbutton class because you are not adding any new functionality to the button.

    Instead in your looping code just create a button and set the Icon:

    //buttons[i][j]=new BWbutton();
    JButton button =  new JButton( new ImageIcon("image.png") );
    buttons[i][j]= button;
    

    Even better is to just create the image icon once outside your loop, then you can share the Icon on all the buttons.