Search code examples
javaarraysjlabelimageicon

Array of JLabel ImageIcon


I am attempting to create a game of Sudoku. I am wanting to use the JSwing API. So, I am using an array of JLabels to display the grid. I have a picture drawn of a 3x3 grid, and I would like to display that in a 3x3 grid. My problem is it will not display the image. Can someone help me resolve the problem?

My Current Code looks like this, split into two class.

Main.class

package com.brendenbunker;

import javax.swing.*;
import java.awt.*;

public class Main{

    FileMaker fileMaker;

    void init() {
        fileMaker = new FileMaker();
    }

    public static void main(String args[]){
        ScreenGenerator gui = new ScreenGenerator();
        gui.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);


        Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
        double width = gui.gridPic.getIconWidth();
        double height = gui.gridPic.getIconHeight();
        int h = (int) height*4;
        int w = (int) width*3;

        gui.setSize(w,h);
        gui.setTitle("Suduko");
        gui.setVisible(true);
    }

}

ScreenGenerator.class

package com.brendenbunker;

import javax.swing.*;
import java.awt.*;

public class ScreenGenerator extends JFrame{

    //Intro Components
    //JLabel temp;
    JLabel[] gridLabel;
    ImageIcon gridPic;
    //intro Vars


    public ScreenGenerator() {

        setLayout(new FlowLayout());

        gridPic = new ImageIcon(getClass().getResource("/Grid_Unified.png"));
        gridLabel = new JLabel[8];

        for (int i=0; i>=9; i++) {
            gridLabel[i] = new JLabel("Hello");
        }

        for (int i=0; i>=9; i++) {
            gridLabel[i].setIcon(gridPic);
            add(gridLabel[i]);
        }

    }
}

All helped Appericiated


Solution

  • change you for loop, it will not enter into loop as per your condition.

    change loop to this..

        for (int i=0; i<8; i++) {
            gridLabel[i] = new JLabel("Hello");
        }
    
        for (int i=0; i<8; i++) {
            gridLabel[i].setIcon(gridPic);
            add(gridLabel[i]);
        }
    

    it will work..