Java-Gaming.org    
Featured games (91)
games approved by the League of Dukes
Games in Showcase (578)
games submitted by our members
Games in WIP (499)
games currently in development
News: Read the Java Gaming Resources, or peek at the official Java tutorials
 
    Home     Help   Search   Login   Register   
Pages: [1]
  ignore  |  Print  
  How to load my image  (Read 669 times)
0 Members and 1 Guest are viewing this topic.
Offline Xuang Zang

Senior Newbie





« Posted 2013-06-10 19:36:38 »

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

1  
2  
3  
4  
5  
6  
7  
8  
9  
10  
11  
12  
13  
14  
15  
16  
17  
18  
19  
20  
21  
22  
23  
24  
25  
26  
27  
28  
29  
30  
31  
32  
33  
34  
35  
36  
37  
38  
39  
40  
41  
42  
43  
44  
45  
46  
47  
48  
49  
50  
51  
52  
53  
54  
55  
56  
57  
58  
59  
60  
61  
62  
63  
64  
65  
66  
67  
68  
69  
70  
71  
72  
73  
74  
75  
76  
77  
78  
79  
80  
81  
82  
83  
84  
85  
86  
87  
88  
89  
90  
91  
92  
93  
94  
95  
96  
97  
98  
99  
100  
101  
102  
103  
104  
105  
106  
107  
108  
109  
110  
111  
112  
113  
114  
115  
116  
117  
118  
119  
120  
121  
122  
123  
124  
125  
126  
127  
128  
129  
130  
131  
132  
133  
134  
135  
136  
137  
138  
139  
140  
141  
142  
143  
144  
145  
146  
147  
148  
149  
150  
151  
152  
153  
154  
155  
156  
157  
158  
159  
160  
161  
162  
163  
164  
165  
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();

            }
        });
    }
}
Offline kingroka123

JGO Knight


Medals: 22
Projects: 3
Exp: 10-12 months


Gamer's Helmet


« Reply #1 - Posted 2013-06-10 20:00:15 »

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

Offline Xuang Zang

Senior Newbie





« Reply #2 - Posted 2013-06-10 20:15:20 »

Hi, can i ask why you said that just extending JFrame wont work? why?
Games published by our own members! Check 'em out!
Legends of Yore - The Casual Retro Roguelike
Offline Xuang Zang

Senior Newbie





« Reply #3 - Posted 2013-06-10 20:17:25 »

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 my frame is now loading but the image of my ship won't display,how can i display the image ?

Thank you in advance

1  
2  
3  
4  
5  
6  
7  
8  
9  
10  
11  
12  
13  
14  
15  
16  
17  
18  
19  
20  
21  
22  
23  
24  
25  
26  
27  
28  
29  
30  
31  
32  
33  
34  
35  
36  
37  
38  
39  
40  
41  
42  
43  
44  
45  
46  
47  
48  
49  
50  
51  
52  
53  
54  
55  
56  
57  
58  
59  
60  
61  
62  
63  
64  
65  
66  
67  
68  
69  
70  
71  
72  
73  
74  
75  
76  
77  
78  
79  
80  
81  
82  
83  
84  
85  
86  
87  
88  
89  
90  
91  
92  
93  
94  
95  
96  
97  
98  
99  
100  
101  
102  
103  
104  
105  
106  
107  
108  
109  
110  
111  
112  
113  
114  
115  
116  
117  
118  
119  
120  
121  
122  
123  
124  
125  
126  
127  
128  
129  
130  
131  
132  
133  
134  
135  
136  
137  
138  
139  
140  
141  
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);


            }
        });
    }
}
Offline Z-Man
« Reply #4 - Posted 2013-06-10 20:18:34 »

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
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:
1  
2  
3  
public void addNotify() {
   super.addNotify();
}
Offline Xuang Zang

Senior Newbie





« Reply #5 - Posted 2013-06-10 20:24:15 »

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
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:
1  
2  
3  
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 ?
Offline Z-Man
« Reply #6 - Posted 2013-06-10 20:29:26 »

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:
1  
2  
3  
4  
5  
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:
1  
2  
3  
4  
5  
6  
7  
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);
Offline Xuang Zang

Senior Newbie





« Reply #7 - Posted 2013-06-10 20:34:41 »

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:
1  
2  
3  
4  
5  
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:
1  
2  
3  
4  
5  
6  
7  
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
1  
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
Offline Z-Man
« Reply #8 - Posted 2013-06-10 20:38:29 »

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.
Offline Xuang Zang

Senior Newbie





« Reply #9 - Posted 2013-06-10 20:43:23 »




Thank you so much i got it now Smiley
Games published by our own members! Check 'em out!
Legends of Yore - The Casual Retro Roguelike
Offline Xuang Zang

Senior Newbie





« Reply #10 - Posted 2013-06-10 21:12:52 »

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.

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.
Offline Z-Man
« Reply #11 - Posted 2013-06-10 22:20:56 »

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.
Offline Xuang Zang

Senior Newbie





« Reply #12 - Posted 2013-06-11 21:57:25 »



Hi, Thank you again Smiley
Offline Xuang Zang

Senior Newbie





« Reply #13 - Posted 2013-06-13 20:52:39 »

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,  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....

1  
2  
3  
4  
5  
6  
7  
8  
9  
10  
11  
12  
13  
14  
15  
16  
17  
18  
19  
20  
21  
22  
23  
 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();
        }
    }
Offline Xuang Zang

Senior Newbie





« Reply #14 - Posted 2013-06-13 21:12:06 »

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, i think this is not correct...because my code is useless


1  
2  
3  
4  
5  
6  
7  
8  
9  
10  
11  
12  
13  
14  
15  
16  
17  
18  
19  
20  
21  
22  
23  
 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...

1  
2  
3  
4  
5  
6  
7  
 Action arrowUP = new AbstractAction() {
            public void actionPerformed(ActionEvent e) {
                up = true;
                posY-=5; // I just put this line here
               repaint();
            }
        };
Pages: [1]
  ignore  |  Print  
 
 
You cannot reply to this message, because it is very, very old.

 

Add your game by posting it in the WIP section,
or publish it in Showcase.

The first screenshot will be displayed as a thumbnail.

xsi3rr4x (31 views)
2014-04-15 18:08:23

BurntPizza (28 views)
2014-04-15 03:46:01

UprightPath (43 views)
2014-04-14 17:39:50

UprightPath (26 views)
2014-04-14 17:35:47

Porlus (42 views)
2014-04-14 15:48:38

tom_mai78101 (64 views)
2014-04-10 04:04:31

BurntPizza (124 views)
2014-04-08 23:06:04

tom_mai78101 (223 views)
2014-04-05 13:34:39

trollwarrior1 (190 views)
2014-04-04 12:06:45

CJLetsGame (198 views)
2014-04-01 02:16:10
List of Learning Resources
by SHC
2014-04-18 03:17:39

List of Learning Resources
by Longarmx
2014-04-08 03:14:44

Good Examples
by matheus23
2014-04-05 13:51:37

Good Examples
by Grunnt
2014-04-03 15:48:46

Good Examples
by Grunnt
2014-04-03 15:48:37

Good Examples
by matheus23
2014-04-01 18:40:51

Good Examples
by matheus23
2014-04-01 18:40:34

Anonymous/Local/Inner class gotchas
by Roquen
2014-03-11 15:22:30
java-gaming.org is not responsible for the content posted by its members, including references to external websites, and other references that may or may not have a relation with our primarily gaming and game production oriented community. inquiries and complaints can be sent via email to the info‑account of the company managing the website of java‑gaming.org
Powered by MySQL Powered by PHP Powered by SMF 1.1.18 | SMF © 2013, Simple Machines | Managed by Enhanced Four Valid XHTML 1.0! Valid CSS!