pras
pras

Reputation: 115

Load png as sprite java

First, I'm sorry for my bad English. I know that my question is similar, maybe same as other people's, many poeple's question out there on internet.but I've tried many of them, but sill dont work. The simple is i dont know my fault.

here's the cronology :

I have 5 class, they're Game.java, Player.java, Menu.java, System.java, and Control.java. the Control class is a KeyListener class, so thats for controlling from keyboard. System class is the main class, to show the JFrame. Menu class is for menu, which show background and button. It has extends JPanel. Player class, of course for Player statistic. Game.java, is the heart of my project, because it control the gameplay.

So, how I load my player's png. My structure is System call Menu, then Menu call Game(new game button), so then Game call Player class. But as I click new game button or press enter, there's nothing happen, the others is fine(loading background, exit button).

System.java

public class System extends JFrame{
private final int lebar=954;
private final int tinggi=540;

private static boolean[] kibod = new boolean[525];

public System(){
    this.setTitle("Unknown man Unkown power");
    this.setSize(new Dimension(lebar,tinggi));
    this.setFocusable(true);
    this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    this.setResizable(false);
    this.setContentPane(new Menu());
    this.addKeyListener(new Control());
    this.setVisible(true);

}

public static void main(String[] args) {
    SwingUtilities.invokeLater(new Runnable() {

        @Override
        public void run() {
            // TODO Auto-generated method stub
            new Sistem();
        }
    });
}

}

Menu.java

public class Menu extends JPanel{
 private int l=954;
private int t=540;

JButton menu1=new JButton("MULAI BARU");
JButton menu2=new JButton("KELUARRR");

public Menu(){
    this.add(menu1);
    this.add(menu2);

    menu1.addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent arg0) {
            new Game();
        }
    });
    menu2.addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent arg0) {
            // TODO Auto-generated method stub
            System.exit(0);
        }
    });

}
}

Player.java

public class Player extends JPanel{
private int posx=System.WIDTH/3;
private int posy=System.HEIGHT/3;

private BufferedImage im;
private Graphics gr;

public void loadl() {
    try {
        im=ImageIO.read(new File("res/glakon2.png"));
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

}
public void paint(Graphics g) {
    gr=g;
    g.drawImage(im, posx, posy, System.WIDTH/3, System.HEIGHT/3, this);
}
public Player(){
    loadl();
}
}

Game.java

public class Game{

public Game() {

    new Player();
}
}

Game class is still empty, as for I just want to test it showing or not. I've tried loading png with

URL u=this.getClass().getResource("res/glakon2.png");
im=ImageIO.read(u);

or

im=ImageIO.read(new File("res/glakon2.png"));

My png are a spritesheet png, contains only 2 image. So how I load it? Thank you for attention and help.

Sorry, I've edited Game.java to match the question, the real things is its Gameplay.java.

Upvotes: 2

Views: 3266

Answers (1)

Paul Samsotha
Paul Samsotha

Reputation: 209102

When I use the below setup it works fine

new ImageIcon(TestIMage.class.getResource("/res/stackoverflow5.png"));

enter image description here

package stackoverflow;

import javax.swing.*;

public class TestIMage {

    public TestIMage() {
        ImageIcon icon = new ImageIcon(TestIMage.class.getResource("/res/stackoverflow5.png"));
        JLabel label = new JLabel(icon);

        JFrame frame = new JFrame();
        frame.add(label);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setLocationByPlatform(true);
        frame.pack();
        frame.setVisible(true);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                new TestIMage();
            }
        });
    }
}

enter image description here


EDIT

Also I think a problem you are facing is not having a preffered sise of the panel. You should @Override the getPreferredSize() of the panel. Something like this.

    @Override
    public Dimension getPreferredSize() {
        return new Dimension(DIM_W, DIM_H);
    }

Also you should override the paintComponent method and calling super.paintComponent, instead of paint, like this

   @Override
    public void paintComponent(Graphics g) {
        super.paintComponent(g);
        gr = g;
        g.drawImage(im, 0, 0, DIM_W, DIM_W, this);
    }

Run this test. I used your Player class

import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.*;

public class TestIMage {

    public TestIMage() {

        JFrame frame = new JFrame();
        frame.add(new Player());
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setLocationByPlatform(true);
        frame.pack();
        frame.setVisible(true);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                new TestIMage();
            }
        });
    }

    private class Player extends JPanel {

        private  int DIM_W;
        private  int DIM_H;

        private BufferedImage im;
        private Graphics gr;

        public void loadl() {
            try {
                im = ImageIO.read(TestIMage.class.getResource("/res/stackoverflow5.png"));
                DIM_W = im.getWidth();
                DIM_H = im.getHeight();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }

        @Override
        public Dimension getPreferredSize() {
            return new Dimension(DIM_W, DIM_H);
        }

        @Override
        public void paintComponent(Graphics g) {
            super.paintComponent(g);
            gr = g;
            g.drawImage(im, 0, 0, DIM_W, DIM_W, this);
        }

        public Player() {
            loadl();
        }
    }
}

UPDATE

Also you need to make sure you add the Player to a top level container like a JDialog. Currently in your Game class, all you do is create in instance of the Player class, but you never add the Player to a container. If you want to use a JDialog you can do that with your Game class

class Game extends JDialog {
    public Game(JFrame frame, boolean modal) {
        super(frame, modal);
        setLayout(new BorderLayout());
        add(new Player());

        pack();
        setVisible(true);
    }
}

The in your actionPerformed you can do this

menu1.addActionListener(new ActionListener() {

    @Override
    public void actionPerformed(ActionEvent arg0) {
        new Game(System.this, true);
    }
});

UPDATE 2

":) it works, I've make test class, and call it through System class, but if I call it from Game class, it won't appear. And about JDialog, is it create another JFrame? I think its simple with only one JFrame(its declared in System class)"

I'm not sure about the flow of your program. I don't know what you attempting to do with Game class. If you want the Player to be in the main frame, then you have to .add if the the frame. You can't do that with Game class because a Game class is not a component. You can use a CardLayout though, if you want to show the Player screen when a button is pressed.

Here's an example

import java.awt.CardLayout;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.*;

public class TestIMage {
    private Player player = new Player();
    private JPanel introPanel = new JPanel();
    private CardLayout cardLayout = new CardLayout();
    private JButton button = new JButton("View Player");
    private JPanel mainPanel = new JPanel(cardLayout);

    public TestIMage() {
        introPanel.setPreferredSize(player.getPreferredSize());
        introPanel.setLayout(new GridBagLayout());
        introPanel.add(button);

        mainPanel.add(introPanel, "introPanel");
        mainPanel.add(player, "playerPanel");

        button.addActionListener(new ActionListener(){
            @Override
            public void actionPerformed(ActionEvent e) {
                cardLayout.show(mainPanel, "playerPanel");
            }
        });

        JFrame frame = new JFrame();
        frame.add(mainPanel);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setLocationByPlatform(true);
        frame.pack();
        frame.setVisible(true);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                new TestIMage();
            }
        });
    }

    private class Player extends JPanel {


        private  int DIM_W;
        private  int DIM_H;

        private BufferedImage im;
        private Graphics gr;

        public void loadl() {
            try {
                im = ImageIO.read(TestIMage.class.getResource("/res/stackoverflow5.png"));
                DIM_W = im.getWidth();
                DIM_H = im.getHeight();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }

        @Override
        public Dimension getPreferredSize() {
            return new Dimension(DIM_W, DIM_H);
        }

        @Override
        public void paintComponent(Graphics g) {
            super.paintComponent(g);
            gr = g;
            g.drawImage(im, 0, 0, DIM_W, DIM_W, this);
        }

        public Player() {
            loadl();
        }
    }
}

enter image description here

Upvotes: 3

Related Questions