Search code examples
javaswingpngjbuttonimageicon

Adding a Png-file to a JButton


mainpanel.setLayout(new GridLayout(25,25,1,1));
JButton buttons[][] = new JButton[25][25];
ImageIcon image = new ImageIcon("wall_down_right_player.png");
for(int i=0; i<25; i++){
    for(int j=0; j<25; j++){
        JButton button = new JButton(image);
        buttons[i][j]= button;
        mainpanel.add(buttons[i][j]);
    }   
}

I was wondering why this is not working maybe someone can help me :D


Solution

  • Do it as follows:

    mainpanel.setLayout(new GridLayout(25,25,1,1));
    JButton buttons[][] = new JButton[25][25];
    Image image = ImageIO.read(getClass().getResource("wall_down_right_player.png"));
    for(int i=0; i<25; i++){
        for(int j=0; j<25; j++){
            JButton button = new JButton();
            button.setIcon(new ImageIcon(image));
            buttons[i][j]= button;
            mainpanel.add(buttons[i][j]);
        }   
    }
    

    Update:

    I suggest you create a folder say, resources and put your image there. Then, you change the code as follows:

    Image image = ImageIO.read(getClass().getResource("resources/wall_down_right_player.png"));`