Help displaying an image in a java applet - java

Below is a simple applet im writing to display a single picture. The code compiles fine, and the applet loads but the image file is never drawn to the applet. Im thinking that it cant find the image using the this.getImage(appletBaseURL, filename); I have the image file stored in all the folders associated with this package but its still not drawing it.
import java.applet.Applet;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Image;
import java.io.File;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.imageio.ImageIO;
public class imageTest extends Applet {
private Image spaceShip;
private final String filename = "spaceshipcropped.jpg";
public void init() {
java.net.URL appletBaseURL = getCodeBase();
File file = new File("spaceshipcropped.jpg");
try {
spaceShip = ImageIO.read(file);
} catch (IOException ex) {
Logger.getLogger(imageTest.class.getName()).log(Level.SEVERE, null, ex);
}
}
public void paint(Graphics g)
{
Graphics2D g2d = (Graphics2D)g;
g2d.drawImage(spaceShip, 0,0, null);
}
public void update(Graphics g) {
repaint();
}
}
After i made theses changes it worked. thank you all very much for your help!

Don't call setSize() in an applet. The size is set by HTML.
Don't code in AWT in this millennium.
The object passed to a Swing component should be a Graphics2D object, but I've never heard the same said of an Applet. Are you checking the Java Console?
That code has some redundant imports.
In the paint method, check to see if the image is null.
The JavaDocs for the getImage(URL,String) method state "This method always returns immediately, whether or not the image exists." Either add a MediaTracker or join us in the 3rd millennium and use ImageIO.read(URL) - which blocks until the image is loaded.
I expect that fixing point 6 will solve the problem, but attend to the other 5 points as well.

add this
public void update(Graphcs g) {
repaint();
}

Related

Java repaint() doesn't call the paint() in applet

To be clear, I've been researching for more than five hours now, I read all the related questions and more than 20 google searches, none of them worked for me and none of them described my case specifically.
First of all here's my code :
import java.util.*;
import java.applet.*;
import java.awt.*;
import java.awt.image.*;
import java.io.IOException;
import static Debug.StaticVar.*;
/*
<applet code="ImageTest" width=300 height=100>
</applet>
*/
public class ImageTest extends Applet {
Image img;
MediaTracker tracker;
public void init() {
tracker = new MediaTracker(this);
Thread Loader = new Thread(() -> {
img = getImage(getCodeBase(), "1.jpg");
tracker.addImage(img, 1);
});
Loader.setPriority(10);
Loader.start();
}
public void start() {
try {
tracker.waitForAll();
repaint();
} catch (InterruptedException e) {
}
}
public void paint(Graphics g) {
g.drawImage(img, 0, 0, null);
}
}
My Problem is the repaint method not calling paint method. To be more specific the paint method executes if I call repaint from another thread, or if I add the paint method to a child class and call repaint but it doesn't work in my code, where I directly call it from the applet main thread. Please HEEEEELP, I'm tired

Java: drawImage animated gif is frozen on first frame

I got my code to draw my image in an applet, but it is an animated gif and it is stopped on the first frame as if it were a single image.
It is supposed to be the spooky scary skeleton dancing, but he's just standing still.
Here is my code:
import java.util.*;
import java.awt.*;
import java.applet.*;
import java.net.*;
import java.awt.image.BufferedImage;
import javax.imageio.ImageIO;
import java.io.*;
public class Spooky extends Applet
{
Image scary, trumpet, walking;
MediaTracker mt;
AudioClip spoopy;
Graphics buffer;
Image offscreen;
Dimension dim;
public void init()
{
setLayout(null);
mt = new MediaTracker(this);
mt.addImage(scary,1);
mt.addImage(trumpet,1);
mt.addImage(walking,1);
spoopy = getAudioClip(getDocumentBase(),"spoopy.wav");
spoopy.loop();
}
public void paint(Graphics g)
{
try
{
URL url = this.getClass().getResource("spooky.gif");
BufferedImage img;
img = ImageIO.read(url);
mt.addImage(img,1);
g.drawImage(img,0,0,300,300,this);
}
catch(IOException e)
{
}
}
}
The problem is the ImageIO.read(url); method. Not sure how, but internally, it messes up the reading of the gif. Instead, construct an ImageIcon from the URL and use getImage() of the ImageIcon to get an Image
As an aside, don't load the image in the paint method. Load it in the init method.
public class Spooky extends Applet {
Image image;
public void init() {
URL url = this.getClass().getResource("spooky.gif");
image = new ImageIcon(url).getImage();
}
public void paint(Graphics g) {
super.paint(g);
g.drawImage(image, 0, 0, 300, 300, this);
}
}
I don't know if it helps but usually it is a problem of needing a separate Thread/Runnable for the animation and a separate for the rest of the code. At least that was a problem I had when I was making a small game. Try this one and let me know if it helps :)
Check this too: Displaying Gif animation in java
Update: An example I found (http://examples.oreilly.com/jswing2/code/) uses JApplet that supports gifs (Applet is the old one)
// AnimationApplet.java
// The classic animation applet rewritten to use an animated GIF.
//
import javax.swing.*;
public class AnimationApplet extends JApplet {
public void init() {
ImageIcon icon = new ImageIcon("images/rolling.gif"); // animated gif
getContentPane().add(new JLabel(icon));
}
}
Did you try not to put sound to see if animation works alone? It could be that sound needs a separate Runnable/Thread
I had a similar problem. Michail Michailidis's answer is one solution. However, if you are trying to load the GIF from an InputStream (which was the situation in my case) you will need a different solution. In this case, I would use the Toolkit class to load your image, more specifically, Toolkit#createImage(byte[]):
Image image;
try(InputStream stream = this.getClass().getResourceAsStream("/someImage.gif")) {
ByteArrayOutputStream buffer = new ByteArrayOutputStream();
int nRead;
byte[] data = new byte[16384];
while ((nRead = stream.read(data, 0, data.length)) != -1) {
buffer.write(data, 0, nRead);
}
buffer.flush();
image = Toolkit.getDefaultToolkit().createImage(buffer.toByteArray());
} catch (IOException e) {
e.printStackTrace();
}

repaint not being called

Hi I have googled and can't figured out why my paintComp method isnt being called
I have the following code
package com.vf.zepto.view;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Properties;
import javax.imageio.ImageIO;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
import com.vf.zepto.view.interfaces.ProcessorPanel;
public class CountryDetailsPanel extends JPanel implements ProcessorPanel, Runnable {
private GridBagConstraints c = new GridBagConstraints();
private String countryName;
private Properties prop = new Properties();
private BufferedImage image;
public CountryDetailsPanel() {
try {
prop.load(new FileInputStream("country.props"));
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
//this.setLayout(new GridBagLayout());
c.gridx = 0;
c.gridy = 0;
c.fill = GridBagConstraints.BOTH;
c.insets = new Insets(5, 5, 5, 5);
this.setPreferredSize(new Dimension(200, 200));
}
#Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
try {
if(countryName != null) {
String asset = prop.getProperty(countryName+".flag");
if(!asset.equals(null)) {
image = ImageIO.read(new File(asset));
g.drawImage(image, 0, 0, null);
}
}
}
catch (IOException e) {
e.printStackTrace();
}
}
#Override
public void updateDetails(Object o) {
countryName = (String)o;
SwingUtilities.invokeLater(this);
}
#Override
public void run() {
this.repaint();
}
}
and when calling this.repaint() expect the paintComponent method to be called but for love nor money it isnt.
Have tried to force it to use the EDT incase that was the issue but its not.
any ideas?
You should never call paintComponent() the repaint() method consolidates all requests to change the component (there may be several repaint requests between screen refreshes). It adds an update request to the GUI event queue so that the update will be properly coordinated with other GUI actions (Swing and AWT are not thread-safe). This update request, when processed, calls update(), which calls paint(), which calls your paintComponent()
Why have this:
#Override
public void run() {
this.repaint();
}
It does not seem of any use (creating a new thread to repaint once? Not to mention the thread is not on EDT rather call repaint() on the JPanel instance (if modified externally other than that you shouldnt even worry). However to start a thread which modifeis UI componets use s SwingTimer/SwingWorker or SwingUtilities#invokeXXX()
This might not be related but in your code I see this:
if(!asset.equals(null)) {
image = ImageIO.read(new File(asset));
g.drawImage(image, 0, 0, null);
}
dont use equals() to compare to a null value as this might throw a NullPointerException because you are attempting to
deference a null pointer, for example this code throws a NPE:
String s=null;
if(!s.equals(null)) {//throws NPE
System.out.println("Here");//is never printed
}
Also as mKorbel has said (+1 to him) dont do long running tasks in paintComponent() declare your Image globally, assign it in the constructor and then use it in paintComponent(). F.i
rather do:
public class TestPanel extends JPanel {
private Image image;
public TestPanel() {
image = ImageIO.read(new File(asset));
}
#Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
if(asset!=null) {
g.drawImage(image, 0, 0, null);
}
}
}
Do not load image or another hard or long running code in paintComponent
Load this Object as a local variable and only one time
paintComponent() is called
implicitly, when JComponent requires repaint, or
explicitly, for example on every of mouse event if one were to invoke paintComponent() from a MouseMotionListener.
If there is animation, then to use Swing Timer and call repaint().

Java - Picture doesn't show until end of loop?

In Java, I have successfully displayed an image on the screen. Now I want to make it move by running it through a for loop. The for loop runs 10 times and sleeps for 1 second each time. Instead of moving the image every second as expected, I have to wait 10 seconds, then 10 images show up.
Here's my code:
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.Toolkit;
import javax.swing.JComponent;
import javax.swing.JFrame;
public class ImageDraw extends JComponent {
public void paint(Graphics g) {
Graphics2D g2 = (Graphics2D) g;
Image img1 = Toolkit.getDefaultToolkit().getImage("player.png");
int x = 0;
int y = 0;
for(int i = 0;i<10;i++){
try {
Thread.sleep(1000);
x+=10;
y+=10;
g2.drawImage(img1, x, y, this);
repaint();
} catch (InterruptedException e) {
e.printStackTrace();
System.exit(0);
}
} //end for
} //end paint
} //end class
How would I make it so the image looks as if it's moving everytime it runs through the loop?
In addition to other suggestions:
Never read the image in the painting method. Read the image when you construct the class or pass in the image with a setImage(...) method.
Custom painting is done by overriding the paintComponent() method, not the paint() method.
Use a Timer for this, and get rid of the Thread.sleep(). You're running this code on the UI thread, and when you call Thread.sleep() you're putting the UI thread to sleep, which means no updating until the entire loop is complete.

Dynamic splash screens for my java application

I want to create a splash screen for my Java application. I managed to do this using the NetBeans default tool that allows me to put some image in. But i want to have something "live" there, such as a progress bar showing the status of application load, some dynamic text, etc.
How do I do this? What are the things I need to know to start doing something like this?
Here is the Java tutorial walking you through exactly what you want to do. You can set the image on the command line so that it shows immediately, then you can manipulate it once the JVM is initialized to add text, progress bars, etc.
http://download.oracle.com/javase/tutorial/uiswing/misc/splashscreen.html
The trick is to create a splash screen using swing and then invoke using Java reflection the method, which is in another .java file, that loades the application. When done loading, dispose your splash screen.
After checking the code, you will understand how it works and now customize it your own way.
Here is some code:
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.JDialog;
/**
*
* #author martijn
*/
public class Splash {
public static void splash() {
try {
final BufferedImage img = ImageIO.read(Splash.class.getResourceAsStream("/path/to/your/splash/image/splash.png"));
JDialog dialog = new JDialog() {
#Override
public void paint(Graphics g) {
g.drawImage(img, 0, 0, null);
}
};
// use the same size as your image
dialog.setPreferredSize(new Dimension(450, 300));
dialog.setDefaultCloseOperation(JDialog.DO_NOTHING_ON_CLOSE);
dialog.setUndecorated(true);
dialog.pack();
dialog.setLocationRelativeTo(null);
dialog.setVisible(true);
dialog.repaint();
try {
// Now, we are going to init the look and feel:
Class uim = Class.forName("javax.swing.UIManager");
uim.getDeclaredMethod("setLookAndFeel", String.class).invoke(null, (String) uim.getDeclaredMethod("getSystemLookAndFeelClassName").invoke(null));
// And now, we are going to invoke our loader method:
Class clazz = Class.forName("yourpackage.YourClass");
dialog.dispose();
// suppose your method is called init and is static
clazz.getDeclaredMethod("init").invoke(null);
} catch (Exception ex) {
ex.printStackTrace();
}
dialog.dispose();
} catch (IOException ex) {
ex.printStackTrace();
}
}
}

Categories