Java-Gaming.org    
Featured games (81)
games approved by the League of Dukes
Games in Showcase (481)
Games in Android Showcase (110)
games submitted by our members
Games in WIP (547)
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  
  Sun Tutorial: LoadImageApp  (Read 3516 times)
0 Members and 1 Guest are viewing this topic.
Offline Aoshi

Senior Newbie





« Posted 2008-08-24 22:03:31 »

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  
import java.awt.*;
import java.awt.event.*;
import java.awt.image.*;
import java.io.*;
import javax.imageio.*;
import javax.swing.*;

/**
 * This class demonstrates how to load an Image from an external file
 */

public class LoadImageApp extends Component {
         
    BufferedImage img;

    public void paint(Graphics g) {
        g.drawImage(img, 0, 0, null);
    }

    public LoadImageApp() {
       try {
           img = ImageIO.read(new File("knight.png"));
       } catch (IOException e) {
       }

    }

    public Dimension getPreferredSize() {
        if (img == null) {
             return new Dimension(100,100);
        } else {
           return new Dimension(img.getWidth(null), img.getHeight(null));
       }
    }

    public static void main(String[] args) {

        JFrame f = new JFrame("Load Image Sample");
           
        f.addWindowListener(new WindowAdapter(){
                public void windowClosing(WindowEvent e) {
                    System.exit(0);
                }
            });
        f.add(new LoadImageApp());
        f.pack();
        f.setVisible(true);
    }
}


I do not understand what the following line means:
1  
 f.add(new LoadImageApp()); 


LoadImageApp() is void, isn't it? So what does "new LoadImageApp()" return?
How do I remove the image from JFrame f again?
Offline Eli Delventhal

JGO Kernel


Medals: 42
Projects: 11
Exp: 10 years


Game Engineer


« Reply #1 - Posted 2008-08-24 22:39:58 »

By calling "new," it means you are creating a new object. The parameters afterward are dependent upon the constructor allowed.

Example:
1  
2  
3  
4  
5  
6  
7  
8  
9  
10  
11  
12  
13  
14  
15  
16  
17  
18  
19  
20  
21  
22  
public class Test
{
     public Test()
     {
          //Blah
    }

     public Test(int x)
     {
          //blah
    }

     public Test (int x, int y)
     {
          //blah
    }

     public void doSomething()
     {
          //blah
    }
}


If I want to create a new Test object, then I can say one of the following:
1  
2  
3  
Test a = new Test();
Test b = new Test(5);
Test c = new Test(1,2);


Those would call the respective constructors that match the number and type of parameters given. Constructors have no return type - they are not void. In addition, they must match the name of the class they are contained in. Notice they all say Test.

A method that is void is doSomething(). Notice the difference - it has "void" written there. So, I couldn't do this:
1  
2  
//not allowed:
int i = a.doSomething();


Because doSomething() doesn't return anything.

See my work:
OTC Software
Offline Aoshi

Senior Newbie





« Reply #2 - Posted 2008-08-25 09:00:01 »

Sorry, void is a wrong expression. What I mean is, that LoadImageApp() doesn't return anything. But if it doesn't return anything, and f.add() expects something to be added to the JFrame, how does the system ensure that my program actually knows what I want to be added to the frame?

1  
f.add(new LoadImageApp());
Games published by our own members! Check 'em out!
Legends of Yore - The Casual Retro Roguelike
Offline Addictman

Senior Member


Medals: 3
Projects: 1


Java games rock!


« Reply #3 - Posted 2008-08-25 09:50:38 »

Hi.

LoadImageApp() is the constructor, and invoking a constructor with the new keyword gives you a new instance(object) of the class LoadImageApp.

Consider this:

LoadImageApp myLoader = new LoadImageApp();
f.add( myLoader );

This is equivalent to your line, - you're just saying you dont need a direct reference to your instance.

f.add(new LoadImageApp());

To fully understand, google "Constructor", or look here for instance:

http://www.ccnyddm.com/AdvJava/java_constructor_tutorial.htm
Offline Eli Delventhal

JGO Kernel


Medals: 42
Projects: 11
Exp: 10 years


Game Engineer


« Reply #4 - Posted 2008-08-25 15:52:21 »

Yeah, that's what I meant by "Constructors have no return type - they are not void. In addition, they must match the name of the class they are contained in. Notice they all say Test." You will have a public method with no return type that is called the same thing as the class, and that will always be your constructor that comes into play whenever someone uses "new."

See my work:
OTC Software
Offline Aoshi

Senior Newbie





« Reply #5 - Posted 2008-08-25 18:35:45 »

Thank you, but these are not the answers that I expected. I know what a constructor is... Let me explain it again:

I took the previous code and replaced

1  
2  
3  
4  
5  
    public LoadImageApp() {
       try {
           img = ImageIO.read(new File("knight.png"));
       } catch (IOException e) {
       }


with

1  
2  
3  
4  
5  
6  
    public LoadImageApp() {
       try {
           img = ImageIO.read(new File("knight.png"));
           img2 = ImageIO.read(new File("squire.png"));             <==
       } catch (IOException e) {
       }
.

One might expect that the program now adds TWO images instead of one. But it doesn't! It still shows only one - the first one. So how does it know that I want it to display this one and not the other one, or even both of them? That's why I thought that there must be some kind of return value. How does it work? How does add() know that it shall take "img" instead of "img2"?
Offline Aoshi

Senior Newbie





« Reply #6 - Posted 2008-08-25 18:52:00 »

I did another test replacing...

1  
2  
3  
    public void paint(Graphics g) {
       g.drawImage(img, 0, 0, null);
    }


with

1  
2  
3  
4  
    public void paint(Graphics g) {
        g.drawImage(img, 0, 0, null);
        g.drawImage(img2, 0, 0, null);
    }


And now both images are shown! Does "setVisible()" call my "paint()" function!?
Online Riven
« League of Dukes »

JGO Overlord


Medals: 781
Projects: 4
Exp: 16 years


Hand over your head.


« Reply #7 - Posted 2008-08-25 22:40:25 »

First you say you know constructors, but you seem puzzled by the way the simplest code behaves.


I'd advice you to first learn Java (maybe by working with UML schemes, or heck, a good book...).

Java itself is hard enough. Trying to learn Java *and* user interfaces at the same time, will make your head hurt.


I understand it's very rewarding to see an Image being painted on the screen by a program that you wrote, but you won't get much further than that with some trial-and-error hacking. Try to first understand what you're doing, by staring small. Let System.out and System.in be your friend for the first few months.

Hi, appreciate more people! Σ ♥ = ¾
Learn how to award medals... and work your way up the social rankings
Offline Eli Delventhal

JGO Kernel


Medals: 42
Projects: 11
Exp: 10 years


Game Engineer


« Reply #8 - Posted 2008-08-25 23:27:49 »

In your first post (3 posts ago), you are creating the actual images. In your second post (2 posts ago), you are actually drawing them. With just the first post's code, you can create 500 images that way and none of them will be drawn unless you actually draw it.

Think of having 500 paint cans. You might have all the colors you need to create the Mona Lisa, but you've got actually put down the paint in order to show it.

See my work:
OTC Software
Offline Aoshi

Senior Newbie





« Reply #9 - Posted 2008-08-26 16:08:55 »

Okay, it's as I suspected: paint() is called by setVisible(). That's why I initially couldn't figure out how the system works... But now its perfectly clear to me. Thanks. Smiley

I for myself prefer this trial-and-error method. In my opinion, it's far more interesting to simply start working on a game than reading boring books and tutorials. Only if I get stuck, do I try to find a solution. In my experience, that's the most efficient way of learning.
Games published by our own members! Check 'em out!
Legends of Yore - The Casual Retro Roguelike
Online Riven
« League of Dukes »

JGO Overlord


Medals: 781
Projects: 4
Exp: 16 years


Hand over your head.


« Reply #10 - Posted 2008-08-26 23:40:49 »

Well, in my opinion, trial and error is certainly an option when coding, but only once you know enough that most of the trials don't turn into errors. In all other cases you need to study the problem with some background info / documentation / tutorials / browsing sourcecode.

Hi, appreciate more people! Σ ♥ = ¾
Learn how to award medals... and work your way up the social rankings
Offline Eli Delventhal

JGO Kernel


Medals: 42
Projects: 11
Exp: 10 years


Game Engineer


« Reply #11 - Posted 2008-08-27 04:26:23 »

I tried to post this a while ago but the forum bugged out on me.

Ahh, yes, the whole hierarchy of Java2D drawing methods is a bit confusing.

setVisible() does not call paint - your window calls paint when it is first created. In order to convey any graphic updates, you're going to want to call repaint() every time you change something. But you probably don't want to use paint(). Instead, override paintComponent() and put all drawing in there.

1  
2  
3  
4  
5  
6  
7  
public void paintComponent(Graphics g)
{
     //Do default stuff like draw the background and refresh the canvas.
    super.paintComponent(g);

     //Do your drawing here:
}


As for your method of learning, I agree that you will learn significantly more with the hands-on approach. However, you're going to have huge gaps in your knowledge unless you have some book or teacher to work alongside with you. I would get a book and use it as reference as you go.

See my work:
OTC Software
Offline Aoshi

Senior Newbie





« Reply #12 - Posted 2008-08-27 22:06:30 »

"But you probably don't want to use paint(). Instead, override paintComponent() and put all drawing in there."

That's right, I don't use paint() by myself. But refresh() calls it for me. In order to redraw the screen, all I have to do is typing "MyFrame.refresh()". That's quite comfortable, I think. I do not understand why I should override paintComponent(). What's the intention/advantage of doing so?


"Well, in my opinion, trial and error is certainly an option when coding, but only once you know enough that most of the trials don't turn into errors. In all other cases you need to study the problem with some background info / documentation / tutorials / browsing sourcecode."

Yes, you are right. I forgot to mention that I already have some experience in C++ and in other languages as well. So programming in general isn't new to me. All I have to do is getting familiar with the subtleties of Java. Some of them - especially the fact that there are no pointers in Java - are quite irritating to me at the moment. And that might be the reason why it seems to you that I'm "puzzled by the way the simplest code behaves".
Offline Eli Delventhal

JGO Kernel


Medals: 42
Projects: 11
Exp: 10 years


Game Engineer


« Reply #13 - Posted 2008-08-28 04:04:25 »

I'm not sure for the exact technical reason, but typically you override paintComponent() when drawing with Swing.

Also, you mean MyFrame.repaint() I believe.

See my work:
OTC Software
Online Riven
« League of Dukes »

JGO Overlord


Medals: 781
Projects: 4
Exp: 16 years


Hand over your head.


« Reply #14 - Posted 2008-08-29 18:25:39 »

paint() is part of java.awt.Component
paintComponent is part of javax.swing.JComponent

paint() calls paintComponent, and a bunch of other stuff, like paintBorder


so if you override paint() your border will be gone (if any) among other things.

Hi, appreciate more people! Σ ♥ = ¾
Learn how to award medals... and work your way up the social rankings
Offline Eli Delventhal

JGO Kernel


Medals: 42
Projects: 11
Exp: 10 years


Game Engineer


« Reply #15 - Posted 2008-08-30 07:29:49 »

paint() is part of java.awt.Component
paintComponent is part of javax.swing.JComponent

paint() calls paintComponent, and a bunch of other stuff, like paintBorder


so if you override paint() your border will be gone (if any) among other things.

There's the reason. Tongue

One of those places where I learned what to do but never bothered to check why.  Grin

See my work:
OTC Software
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.

atombrot (26 views)
2014-08-19 09:29:53

Tekkerue (24 views)
2014-08-16 06:45:27

Tekkerue (23 views)
2014-08-16 06:22:17

Tekkerue (13 views)
2014-08-16 06:20:21

Tekkerue (20 views)
2014-08-16 06:12:11

Rayexar (58 views)
2014-08-11 02:49:23

BurntPizza (38 views)
2014-08-09 21:09:32

BurntPizza (30 views)
2014-08-08 02:01:56

Norakomi (37 views)
2014-08-06 19:49:38

BurntPizza (67 views)
2014-08-03 02:57:17
List of Learning Resources
by Longor1996
2014-08-16 10:40:00

List of Learning Resources
by SilverTiger
2014-08-05 19:33:27

Resources for WIP games
by CogWheelz
2014-08-01 16:20:17

Resources for WIP games
by CogWheelz
2014-08-01 16:19:50

List of Learning Resources
by SilverTiger
2014-07-31 16:29:50

List of Learning Resources
by SilverTiger
2014-07-31 16:26:06

List of Learning Resources
by SilverTiger
2014-07-31 11:54:12

HotSpot Options
by dleskov
2014-07-08 01:59:08
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!