How do I import a .gif?
Hi! :-)
I'm just learning :-O
I figure I'm going to learn java better by making a fun game! So, i'm going to do it all in baby steps.
My first question, is how do I import a .gif file and give it a variable or class value? Like with a JOPtionpane, whatever comes in from the users input gets a primitive data type value.
In flash (I know flash, but i want to learn java) a graphic you put onto the stage becomes an object of the movieClip class and then you can name it which gives it an instance of that movieClip class. So, I guess I am realizing now, that using Java i will probably have to write my own movieClip type object class so I can give the gif programable properties. Does a class like this already exist?
To make my question more concise:
1: how do I bring in a .gif
2: how do I give that .gif programmable properites.
Thanks so much for any help. I love you all :-*
Threebrain
[963 byte] By [
threebrain] at [2007-9-27 15:04:39]

so i got the image to work in the applet - yes!
here is the code I got so far...
import java.awt.Graphics;
import java.awt.Image;
import java.applet.Applet;
import java.lang.ref.SoftReference;
public class Balloon extends Applet {
SoftReference sr = null;
public void init() {
System.out.println("Initializing");
}
public void paint(Graphics g) {
Image im = (sr == null) ? null : (Image)(sr.get());
if (im == null) {
System.out.println("Fetching image");
im = getImage(getCodeBase(), "images/balloonClosed.gif");
sr = new SoftReference(im);
}
System.out.println("Painting");
g.drawImage(im, 25, 25, this);
im = null;/* Clear the strong reference to the image */
}
public void start() {
System.out.println("Starting");
}
public void stop() {
System.out.println("Stopping");
}
}
So, how do I make the balloon move around? eventually, i want to make the balloon look like it's floating randomly but for now, if i can just learn how to make it move at all that would be phat! :-O
You load an Image using the 'Toolkit' classes method createImage(....)
The code will look something like
Toolkit.getDefaultToolkit().createImage("image.gif");
there are several overloaded variants of this method, that take different parameters - but they all return an 'Image' object.
rob,
Abuse at 2007-7-5 23:04:52 >

I can tell you copied that code from somewhere :P
I have been using Java for 5 years now, and havn't once used the SoftReference class. Neither should you! Also, Applets do not use the 'regular' way of loading images, I would recommend learning to write Java Applications before you attempt to write Applets.
rob,
Abuse at 2007-7-5 23:04:52 >

here is a little sample app. I knocked up 4 ya
it got a few bits of everything in it.
import java.awt.*;
import java.awt.image.*;
import java.awt.event.*;
public class FirstFrame extends Frame implements ImageObserver, WindowListener
{
Image firstImage;
public FirstFrame()
{
firstImage = getToolkit().createImage("1stImage.gif");
//gets a reference to the image resource
//but doesn't begin the loading of the resource
//it uses the getToolkit() method inherited from Component
//(the class from which all AWT Components are derived)
//to get a Toolkit compatible with this AWT Component
//in most cases, Toolkit.getDefaultToolkit() would have the same effect.
synchronized(this)
{
if(firstImage.getHeight(this)==-1 || firstImage.getWidth(this)==-1)//either of these method calls will make the image loading process begin
{
System.out.print("Loading Image ");
try
{
wait();//loading of images is done asyncronously
//so put the main Thread on wait, until the image is loaded
}
catch(Exception e)
{
}
}
}
setBounds(50,50,100,100);
addWindowListener(this);
setVisible(true);
}
//this method is a callback method, that gives updates on the image loading progress
public boolean imageUpdate(Image img, int flags, int x, int y, int width, int height)
{
if((flags&ImageObserver.ALLBITS)!=0)
{
synchronized(this)
{
System.out.println(" Complete");
try
{
notify();
//image loading is complete, so notify the main Thread to continue
}
catch(Exception e)
{}
}
return false;//no more updates are necessary
}
else if((flags&ImageObserver.ERROR)!=0)
{
System.out.println(" Error loading image - Exiting");
System.exit(1);
}
System.out.print(".");
return true;//loading not complete yet, continue sending load progress updates
}
//overriding update to remove repaint flicker
//update would normally clear the screen before doing a paint
//this is not desired in most cases
public void update(Graphics g)
{
paint(g);
}
//draws the image onto the frame at the origin
//the 'null' parameter is the ImageObserver
//in 99% of cases this is not required for drawImage requests.
public void paint(Graphics g)
{
g.drawImage(firstImage,0,0,null);
}
//this stuff is to allow you to close the window
public void windowActivated(WindowEvent e){}
public void windowClosed(WindowEvent e){}
public void windowClosing(WindowEvent e){System.exit(0);}
public void windowDeactivated(WindowEvent e){}
public void windowDeiconified(WindowEvent e){}
public void windowIconified(WindowEvent e){}
public void windowOpened(WindowEvent e){}
public static void main(String [] args)
{
new FirstFrame();
}
}
rob,
Abuse at 2007-7-5 23:04:52 >

rob, you got me! but! i just figured it out way simpler and re-wrote it on my own, and it works :-O Below is what I did and it's way more simple, and I understand it all:
import java.awt.*;
import java.awt.Image;
import java.applet.Applet;
public class Balloon extends Applet {
public void paint(Graphics g) {
Image balloon = getImage(getCodeBase(), "images/balloonClosed.gif");
g.drawImage(balloon, 25, 25, this);
}
}
I am thinking that I should make this game an applet, so I can put it up on the internet for people to play, no?
Anyways, now I need to learn how to move it :-O I'm going to check out that other guy's code below
:-O
I understand most of it though, we were doing the TRY and CATCH stuff yesterday at school. So does it have to go through all of this every frame? or is this all just for the inital frame1 where the images load? Holy ****! i'll have to go back and look some more...
oh wait! but i wanna make it an applet for the internet so people can play it and go, "hahahahahahahah" because the balloon I drew is so funny! XD
So, does this code you wrote apply to applets? like all the windowListner stuff?
threebrain
the code you posted will work, but would be much more efficient if it looked like this...
import java.awt.*;
import java.awt.Image;
import java.applet.Applet;
public class Balloon extends Applet
{
Image balloon = getImage(getCodeBase(), "images/balloonClosed.gif");
public void paint(Graphics g)
{
g.drawImage(balloon, 25, 25, this);
}
}
i've moved the Image creation outside of the paint event, so it is executed only once, not every time the window is repainted.
rob,
Abuse at 2007-7-5 23:04:52 >

> :-O
>
> I understand most of it though, we were doing the TRY
> and CATCH stuff yesterday at school. So does it have
> to go through all of this every frame? or is this all
> just for the inital frame1 where the images load?
> Holy ****! i'll have to go back and look some
> more...
the only code executed every frame(repaint) is the code contained in the public void update(Graphics g) method. (and consequently the public void paint(Graphics g) method which is called from within update)
>
> oh wait! but i wanna make it an applet for the
> internet so people can play it and go,
> "hahahahahahahah" because the balloon I drew is so
> funny! XD
>
> So, does this code you wrote apply to applets? like
> all the windowListner stuff?
yes, most of the code is applicable to applets - the WindowListener stuff is only applicable to Classes derived from 'Window' - so, you won't need it, unless you make your Applet spawn some popup windows.
There are a number of other issues regarding Applets, mostly related to security.
Even more important, are the problems with different versions of Java supported in browsers.
Most browsers only support Java1.1x - if you are developing Applets, I guess you are using Java1.2, 1.3 or 1.4. If you want your applets to be usable by the vast majority of people, you will have to make sure none of your code uses any 1.2+ features
>
> threebrain
rob,
Abuse at 2007-7-5 23:04:52 >

hahahahahahah XD
i got it move by changing the code in this tutorial I found. But, It is based on moving one object in front of another foreground in front of background. I don't want to have a background image, so i'm going to try and modify this code so there is no background image and the balloon is just moving by itself thus way simplifying the code :D
/*
* Swing version.
*/
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
/*
* Moves a foreground image in front of a background image.
* See MovingLabels.java for an alternative implementation
* that uses two labels instead of doing its own painting.
*/
public class Balloon extends JApplet
implements ActionListener {
int frameNumber = -1;
boolean frozen = false;
Timer timer;
AnimationPane animationPane;
static String fgFile = "images/balloonClosed.gif";
static String bgFile = "images/starfield.gif";
//Invoked only when run as an applet.
public void init() {
//Get the images.
Image bgImage = getImage(getCodeBase(), bgFile);
Image fgImage = getImage(getCodeBase(), fgFile);
buildUI(getContentPane(), bgImage, fgImage);
}
void buildUI(Container container, Image bgImage, Image fgImage) {
int fps = 10;
//How many milliseconds between frames?
int delay = (fps > 0) ? (1000 / fps) : 100;
//Set up a timer that calls this object's action handler.
timer = new Timer(delay, this);
timer.setInitialDelay(0);
timer.setCoalesce(true);
animationPane = new AnimationPane(bgImage, fgImage);
container.add(animationPane, BorderLayout.CENTER);
animationPane.addMouseListener(new MouseAdapter() {
public void mousePressed(MouseEvent e) {
if (frozen) {
frozen = false;
startAnimation();
} else {
frozen = true;
stopAnimation();
}
}
});
}
//Invoked by a browser only.
public void start() {
startAnimation();
}
//Invoked by a browser only.
public void stop() {
stopAnimation();
}
//Can be invoked from any thread.
public synchronized void startAnimation() {
if (frozen) {
//Do nothing. The user has requested that we
//stop changing the image.
} else {
//Start animating!
if (!timer.isRunning()) {
timer.start();
}
}
}
//Can be invoked from any thread.
public synchronized void stopAnimation() {
//Stop the animating thread.
if (timer.isRunning()) {
timer.stop();
}
}
public void actionPerformed(ActionEvent e) {
//Advance animation frame.
frameNumber++;
//Display it.
animationPane.repaint();
}
class AnimationPane extends JPanel {
Image background, foreground;
public AnimationPane(Image background, Image foreground) {
this.background = background;
this.foreground = foreground;
}
//Draw the current frame of animation.
public void paintComponent(Graphics g) {
super.paintComponent(g); //paint any space not covered
//by the background image
int compWidth = getWidth();
int compHeight = getHeight();
int imageWidth, imageHeight;
//If we have a valid width and height for the
//background image, draw it.
imageWidth = background.getWidth(this);
imageHeight = background.getHeight(this);
if ((imageWidth > 0) && (imageHeight > 0)) {
g.drawImage(background,
(compWidth - imageWidth)/2,
(compHeight - imageHeight)/2, this);
}
//If we have a valid width and height for the
//foreground image, draw it.
imageWidth = foreground.getWidth(this);
imageHeight = foreground.getHeight(this);
if ((imageWidth > 0) && (imageHeight > 0)) {
g.drawImage(foreground,
((frameNumber*5)
% (imageWidth + compWidth))
- imageWidth,
(compHeight - imageHeight)/2,
this);
}
}
}
}
also! how did you get your code to colorize in your post? i wanna colorize code i post
You will gain more understanding by writing your applet from scratch, not modifying others code.rob,
Abuse at 2007-7-5 23:04:52 >

yup, i already scratched that file and went back to my other one from before.
i was just reading your code again, and all that stuff in the begining the TRY and CATCH stuff. What is all that for? all your code does is load the image right? Is all the stuff just mad safetry precautions?
> Is all the stuff just mad safetry precautions?
basically - yes
createImage(...) does not immediatly load the image. The image loading begins asyncronously (in the background) when the Image is first used.
My code creates the Image, then calls getWidth and getHeight to force the image to fully load before the application proceeds.
You can take out this code, but, if your balloon image is big, it may take a considerable time to load. So, by the time your program gets around to repainting the screen, your image may not have fully loaded - this will mean you will get a partly drawn image painted to the screen.
Not a particularly desirable effect! ;]
rob,
Abuse at 2007-7-5 23:04:52 >

p.s.encapsulate your code segments in [code][/code]to make it more readablerob,
Abuse at 2007-7-5 23:04:52 >

only 2 people talking and it makes the front page i smell a hambone
kaze0a at 2007-7-18 11:44:39 >

hahahahahah i got it to move! it was weird though, it made a trail of itself. I showed my teacher And I suggested that we draw a white rectangle to white wash the whole thing and then have the balloons x,y move everyframe, it works, but that dosn't seem an efficient way to make a game, and also because i'm going to have other graphics too. can't i just move the balloon without having to repaint the whole page. Below is my code so far. Right now the balloon just keeps going down diagnally, i'm gonna change that right now and make it look like he's floating...
/*
* Swing version.
*/
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
/*
* A template for animation applets.
*/
public class AnimatorAppletTimer3 extends JApplet
implements ActionListener {
int frameNumber = -1;
Timer timer;
JLabel label;
Image balloon;
int x,y;
public void init() {
x = 25;
y = 25;
int fps = 0;
int delay = (fps > 0) ? (1000 / fps) : 100;
balloon = getImage(getCodeBase(), "images/balloonClosed.gif");
//Set up a timer that calls this object's action handler.
timer = new Timer(delay, this);
//timer.setInitialDelay(0);
label = new JLabel("Frame", JLabel.CENTER);
getContentPane().add(label, BorderLayout.CENTER);
}
public void paint(Graphics g) {
g.setColor(Color.white);
g.fillRect(0, 0, 1000, 1000);
g.drawImage(balloon, x, y, this);
}
//Invoked by the browser only. invokeLater not needed
//because startAnimation can be called from any thread.
public void start() {
timer.start();
}
public void actionPerformed(ActionEvent e) {
//Advance the animation frame.
frameNumber++;
x += 2;
y += 2;
//Request that the frame be painted.
repaint();
}
}
also, the balloon flickers sometimes X(
you can do a graphics.clearRect(location of balloon) to clear the error
im sure that theres an easier and more efficient way to do this but i cant think of it right now, i have some source at home that accomplishes that and double buffers.
you have to repaint the whole screen on every move, although i suggest that you keep the background as a seperate graphics object
kaze0a at 2007-7-18 11:44:39 >

clearing the whole background is less efficient with small numbers of sprites - but as the number increases, this cost becomes unimportant.
Basically, don't worry about it.
I assume your talking about white flicker?
This is because the default implementation of update(Graphics g) clears the screen with a white rectangle before rendering the next frame. t can be fixed by overriding the update(Graphics) method with this.
public void update(Graphics g)
{
paint(g);
}
Another problem, is being able to see the sprites being drawn - this is because you are drawing directly onto the screen buffer. You will need to implement double buffering. This is done like this...
Image buffer = new BufferedImage(getWidth(),getHeight(),BufferedImage.TYPE_INT_BGR);
Graphics bg = buffer.getGraphics();
then, in the paint method
[/code]
public void paint(Graphics g)
{
//replace all your g.XXXX calls, with bg.XXXXX
g.drawImage(buffer,0,0,null);
}[/code]
the 3rd problem you will come across, is tearing. This is because the screen repaint is not synchronised with the screen refresh.
It is more complex to fix, and is abit beyond what you need to know. (but thanx to jdk1.4, can be fixed)
rob,
Abusea at 2007-7-18 11:44:39 >

