[java] JFrame,JLabel and ImageIcon question.

Started by
1 comment, last by vrd 15 years, 3 months ago
hi,i am trying to make a 2D game,..currently i am in the initial stages and am just trying to create the basic environment in which the game will be played. i am having trouble loading images to a JLabel. here is the code on which i am working on:

public game()
    {
        super("game");
        setSize(500,500);
        setVisible(true);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        cont = getContentPane();
        cont.setLayout(null);
        cont.setBackground(Color.WHITE);

        for(int i =0;i<env.length;i++)
        {
            for(int j=0;j<env[0].length;j++)
            {
                JLabel lbl = null;
                if(env[j].equals("#"))
                {
                    lbl = new JLabel(new ImageIcon("images/test.png"));
                }
                if(env[j].equals("*"))
                {
                    lbl = new JLabel(new ImageIcon("images/test2.png"));
                }
                cont.add(lbl);
                lbl.setBounds(i*50,j*50,50,50);

            }
        }
        repaint();
        cont.validate();
        setContentPane(cont);

    }

public game() is the constructor of the game class. env is a 2D array in which "*" and "#" are present at random positions. now,..when i execute the program,..i get the JFrame with a White Background,..but i dont get the images test.png and test2.png anywhere. i believe there is some error in the folowing line:

lbl = new JLabel(new ImageIcon("images/test.png"));

Advertisement
I am sorry this probably isn't what you probably want.
I would suggest doing this, make a class that extends JFrame, and then make a class that extends JPanel. The Jpanel class you can do
this.add(JPanel Class); (Inside your JFrame class). <-- it could also be insert(); cannot remember.
This will make it so you have a frame that has a panel on top.
After that you can add JLabels and ImageIcons into the JPanel =).
it turns out that the extension of the images was .gif and i had written .png everywhere. images are loading file now. i feel like an idiot :(

This topic is closed to new replies.

Advertisement