How to load my image

Hi, I need some help, why is it my code will exit directly? it will not show the frame,can you help me please how to fix this.

Thank you in advance.

here is my code


import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;



public class Mygame extends JFrame{
    private Image ship;
    private Boolean running;
    private Mypanel mypanel;
    private boolean up =false;
    private boolean down = false;
    private boolean right =false;
    private boolean left = false;
    private int posX = 10;
    private int posY = 100;

    public Mygame(){
        setTitle("Demo Game");

        mypanel = new Mypanel();
        getContentPane().add(mypanel);

    }

    class Mypanel extends JPanel {

          public Mypanel(){

              ship = Toolkit.getDefaultToolkit().getImage(getClass().getResource("images/spaceship.png"));

              getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke(KeyEvent.VK_UP,0),
                      "arrowUP");
              getActionMap().put("arrowUP",
                      arrowUP);


              getInputMap().put(KeyStroke.getKeyStroke(KeyEvent.VK_RIGHT,0),
                      "arrowRight");
              getActionMap().put("arrowRight",
                      arrowRight);


              getInputMap().put(KeyStroke.getKeyStroke(KeyEvent.VK_LEFT,0),
                      "arrowLeft");
              getActionMap().put("arrowLeft",
                      arrowLeft);


              getInputMap().put(KeyStroke.getKeyStroke(KeyEvent.VK_DOWN,0),
                      "arrowDown");
              getActionMap().put("arrowDown",
                      arrowDown);






          }


        Action arrowUP = new AbstractAction() {
            public void actionPerformed(ActionEvent e) {
                up=true;
                repaint();


            }
        };



        Action arrowDown = new AbstractAction() {
            public void actionPerformed(ActionEvent e) {

                down = true;
                repaint();


            }
        };

        Action arrowRight = new AbstractAction() {
            public void actionPerformed(ActionEvent e) {

            }
        };

        Action arrowLeft = new AbstractAction() {
            public void actionPerformed(ActionEvent e) {

            }
        };


        public void paintComponent(Graphics g){
            super.paintComponent(g);
            Graphics2D g2d = (Graphics2D) g;
            g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
                    RenderingHints.VALUE_ANTIALIAS_ON);



            if(up==true){
               posX+=5;
            }

            if(left=true){
                posY-=5;
            }
        }



    } //End of Class Mypanel


        public void addNotify(){

        }

        public void startGame(){

        }

        public void stopRun(){
            running = false;
        }

        public void run(){
            running = true;

            while(running==true){

                    repaint();


                try {
                    Thread.sleep(5);
                }
                catch(InterruptedException ex){}

            }

            System.exit(0);
        }



    public static void main(String []a){
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                 Mygame mygame = new Mygame();

                 mygame.setDefaultCloseOperation(DISPOSE_ON_CLOSE);
                 mygame.setVisible(true);
                 mygame.pack();

            }
        });
    }
}



it does not seem like you have a jframe to put the panel on. a jpanel is like a layer that goes ontop of a jframe while the jframe is the actual window that pops up. just read up on jframes and jpanels. btw just extending jframe wont work

Hi, can i ask why you said that just extending JFrame wont work? why?

Hi my frame is now loading but the image of my ship won’t display,how can i display the image ?

Thank you in advance


import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;



public class Mygame extends JFrame{
    private Image ship;
    private Boolean running;
    private Mypanel mypanel;
    private boolean up =false;
    private boolean down = false;
    private boolean right =false;
    private boolean left = false;
    private int posX = 10;
    private int posY = 10;

    public Mygame(){
        setTitle("Demo Game");

        mypanel = new Mypanel();

        add(mypanel);

    }

    class Mypanel extends JPanel {

          public Mypanel(){

             ship = Toolkit.getDefaultToolkit().getImage(getClass().getResource("images/spaceship.png"));

              getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke(KeyEvent.VK_UP,0),
                      "arrowUP");
              getActionMap().put("arrowUP",
                      arrowUP);


              getInputMap().put(KeyStroke.getKeyStroke(KeyEvent.VK_RIGHT,0),
                      "arrowRight");
              getActionMap().put("arrowRight",
                      arrowRight);


              getInputMap().put(KeyStroke.getKeyStroke(KeyEvent.VK_LEFT,0),
                      "arrowLeft");
              getActionMap().put("arrowLeft",
                      arrowLeft);


              getInputMap().put(KeyStroke.getKeyStroke(KeyEvent.VK_DOWN,0),
                      "arrowDown");
              getActionMap().put("arrowDown",
                      arrowDown);






          }


        Action arrowUP = new AbstractAction() {
            public void actionPerformed(ActionEvent e) {
                up=true;
                repaint();


            }
        };



        Action arrowDown = new AbstractAction() {
            public void actionPerformed(ActionEvent e) {

                down = true;
                repaint();


            }
        };

        Action arrowRight = new AbstractAction() {
            public void actionPerformed(ActionEvent e) {

            }
        };

        Action arrowLeft = new AbstractAction() {
            public void actionPerformed(ActionEvent e) {

            }
        };


        public void paintComponent(Graphics g){
            super.paintComponent(g);
            Graphics2D g2d = (Graphics2D) g;
            g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
                    RenderingHints.VALUE_ANTIALIAS_ON);

           g2d.drawImage(ship,posX,posY,5,5,this);

            if(up==true){
               posX+=5;
            }

            if(left=true){
                posY-=5;
            }
        }

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

    } //End of Class Mypanel





    public static void main(String []a){
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                 Mygame mygame = new Mygame();

                 mygame.setDefaultCloseOperation(DISPOSE_ON_CLOSE);
                 mygame.pack();
                 mygame.setVisible(true);


            }
        });
    }
}



His code works just fine (besides not opening), although it might not be the optimal way.

You’re overriding addNotfiy() (which is kind of an important method, check the java docs) and having it to do nothing. This should fix it:


public void addNotify() {
   super.addNotify();
}

Hi thank you for the spot, ahm okay i will update my code…can you please help me why my image ship is not displaying ?

I think it might have to do with the way you’re loading your image. Using ImageIO instead of the Toolkit’s getImage() fixed it for me. Try this instead:


try {
   ship = ImageIO.read(getClass().getResource("images/spaceship.png");
} catch(IOException exc) {
   exc.printStackTrace();
}

EDIT: Also there isn’t really a point in overriding a JFrame and a JPanel. You’re better off only overriding a JPanel and then adding it to a frame. Something like this:


JFrame frame = new JFrame("Title");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
MyPanel panel = new MyPanel();
panel.setPreferredSize(new Dimension(600,600));
frame.add(panel);
frame.pack();
frame.setVisible(true);

Hi, it’s working now, but the problem is my image is too small.because of this

g2d.drawImage(ship,posX,posY,5,5,this);

how can i get the default width and height of my image,…I am using this.getWidth(),this.getHeight()…but my image is very big. :emo:

Stop sending a width and height of 5 to the drawImage() method. You’re using drawImage(Image img, int x, int y, int width, int height, ImageObserver io) when all you really need is drawImage(Image img, int x, int y, ImageObserver io). Again, check the JavaDocs for stuff like this or when you aren’t sure how something works.

Thank you so much i got it now :slight_smile:

Hi, Can i ask last question, is this normal that when i move my image or pressing arrow up my image has a shadow something like the image is delaying to display when i pressing the arrow up.how can i run my image very smooth like no shadow.

I hope you understand what i mean.

Thank you in advance.

For smooth movement you should just use a Game Loop (take a look at this article about them) instead of only drawing when you receive user input. Just update the ship location when you get input and only draw in your game loop.

Hi, Thank you again :slight_smile:

Hi, I tried but i am confuse how to update my ship location when press the arrows key

I put this outside in Mypanel class ,but how can i draw the image,i am confuse…please help me…


 public void gameUpdate(){
       

           if(up==true){

           }


    }


    public void run() {
        Thread t = Thread.currentThread();
        while (t == gameloop) {
            try {
                Thread.sleep(5);
            }
            catch (InterruptedException e) {
                e.printStackTrace();
            }
            gameUpdate();
        }
    }


Hi, i think this is not correct…because my code is useless


 public void gameUpdate(){
       

           if(up==true){
                g2d.drawImage(ship, posX, posY, null);
           }


    }


    public void run() {
        Thread t = Thread.currentThread();
        while (t == gameloop) {
            try {
                Thread.sleep(5);
            }
            catch (InterruptedException e) {
                e.printStackTrace();
            }
            gameUpdate();
        }
    }


I have this code on top of it,and this is the reason why it moves…and my spaceship moves okay,but i want to use the gameloop what you have said and the link you provided but it seems like i am confuse of it…


 Action arrowUP = new AbstractAction() {
            public void actionPerformed(ActionEvent e) {
                up = true;
                posY-=5; // I just put this line here
                repaint();
            }
        };