I want to display image in an applet and play audio clip. I wrote the following code but its not working. I have written code just for image but dont have any idea for audio clip. Please let me know where I am making mistake..
import java.applet.*;
import java.awt.*;
import java.net.*;
/*
<applet code="Showimage" width = 400 height = 400>
</applet>
*/
public class Showimage extends Applet
{
URL codb;
Image picture;
public void init()
{
codb = getCodeBase();
picture = getImage(codb, "Choti.jpg");
}
public String getAppletInfo()
{
return "Hi...";
}
public void start() { }
public void paint(Graphics g)
{
g.drawImage(picture, 10, 10, this);
showStatus(getAppletInfo());
}
}
import java.applet.*;
import java.awt.*;
import java.net.*;
/*
<applet code="Showimage" width = 400 height = 400>
</applet>
*/
public class Showimage extends Applet
{
URL codb;
Image picture;
AudioClip clip;
public void init()
{
picture = getImage(getCodeBase(), "../images/Beagle.jpg");
clip = getAudioClip(getDocumentBase(), "sound/woof.wav");
}
public String getAppletInfo()
{
return "Hi...";
}
public void start() {
clip.play();
showStatus(getAppletInfo());
}
public void paint(Graphics g)
{
g.drawImage(picture, 10, 10, this);
}
}
Would find the image & sound with this directory structure.
images
Beagle.jpg
applet
sound
woof.wav
applet.html
An applet class and image "Choti.jpg" must be in same folder.
Use getImage(java.net.URL) method to get an image from other location/folder and use play(URL,string) or play(URL) method to play audio clip. For more detail visit applet tutorial.
Related
Recently i decided to start learning how to make 2D games With JAVA ( eclipse ) so i found a tutorial online that shows how to make superMari game with java, i wrote the same code he wrote and i followed step by step what he did, which wasn't a big thing to talk about, unfortunately he's code shows, after excuting, a window with two images in it while mine shows just the window with no images, i ensure you that i imported the two images and put them in one package to avoid all kind of problems but it still shows nothing.
my code has two classes, "main" and "Scene", here it is, hopefully someone will find a solution for me, thank you guys!
Main.java :
package AiMEUR.AMiN.jeu;
import javax.swing.JFrame;
public class Main {
public static Scene scene;
public static void main(String[] args) {
JFrame fenetre = new JFrame("Naruto in mario World!!");
fenetre.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
fenetre.setSize(700, 360);
fenetre.setLocationRelativeTo(null);
fenetre.setResizable(false);
fenetre.setAlwaysOnTop(true);
scene = new Scene();
fenetre.setContentPane(scene);
fenetre.setVisible(true);
}
}
Scene.java :
package AiMEUR.AMiN.jeu;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Image;
import javax.swing.ImageIcon;
import javax.swing.JPanel;
#SuppressWarnings("serial")
public class Scene extends JPanel{
private ImageIcon icoFond;
private Image imgFond1;
private ImageIcon icoMario;
private Image imgMario;
private int xFond1;
public Scene(){
super();
this.xFond1 = -50;
icoFond = new ImageIcon(getClass().getResource("/Images/fond.gif"));
this.imgFond1 = this.icoFond.getImage();
icoMario = new ImageIcon(getClass().getResource("/Images/1.png"));
this.imgMario = this.icoMario.getImage();
// paintComponent(this.getGraphics());
}
public void paintCompenent(Graphics g){
super.paintComponent(g);
Graphics g2 = (Graphics2D)g;
g2.drawImage(this.imgFond1, this.xFond1, 0, null);
g2.drawImage(imgMario, 300, 245, null);
}
}
You have not named the paintComponent method correctly, and therefore it is not being overridden.
The correct name is paintComponent not paintCompenent:
public class Example extends JPanel {
#Override
public void paintComponent(final Graphics g) {
super.paintComponent(g);
}
}
You can determine the loading status of an ImageIcon by doing something like this:
public Scene(){
super();
this.xFond1 = -50;
icoFond = new ImageIcon(getClass().getResource("/Images/fond.gif"));
int status = icoFond.getImageLoadStatus();
switch (status) {
case (MediaTracker.COMPLETE): {
System.out.println("icoFond image has successfully loaded");
}
case (MediaTracker.ERRORED): {
System.out.println("The icoFond image didn't load successfully");
// probably because the image isn't actually at "/Images/fond.gif"
}
}
this.imgFond1 = this.icoFond.getImage();
icoMario = new ImageIcon(getClass().getResource("/Images/1.png"));
this.imgMario = this.icoMario.getImage();
// paintComponent(this.getGraphics());
}
import java.awt.*;
import javax.swing.ImageIcon;
import javax.swing.JApplet;
public class MonoplyDriver extends JApplet {
boolean isFirst=true;
Player John = new Player(1500,"Circle","John");
Board board = new Board();
Image imgBoard;
public void init()
{
//imgBoard = new ImageIcon("res/board.png").getImage();
imgBoard = getImage(getDocumentBase(),"res/board.png");
setSize(750,750);
System.out.println(getDocumentBase());
}
public void paint(Graphics g)
{
//super.paint(g);
if(isFirst)
{
isFirst=false;
}
g.drawImage(imgBoard, 0, 0, this);
}
}
From the sounds of it, the image is not being found because it is a internal resource.
You could try something like...
imgBoard = ImageIO.read(getClass().getResource("res/board.png"));
This will throw an IOException if the image cannot be loaded for some reason, which is more useful than what you're getting right now
As an aside. You should avoid painting directly to top level containers, but instead using something that extends from JComponent and override it's paintComponent method
Take a look at Performing Custom Painting and Reading/Loading an Image for more details
package org.kodejava.example.applet;
import java.applet.Applet;
import java.awt.*;
public class AppletGetImage extends Applet {
private Image logo;
#Override
public void init() {
logo = getImage(getDocumentBase(), "/images/logo.png");
}
#Override
public void paint(Graphics g) {
g.drawRect(0, 0, getWidth() - 1, getHeight() - 1);
g.drawImage(logo, 10, 10, this);
}
}
Questions:
compalsary package declare in all java program?
private Image logo; for which purpose this variable can be use in applet class?
public void init() for which purpose this method can be use in applet class?
compalsary package declare in all java program?
No. See here for more: Java Package
private Image logo; for which purpose this variable can be use in
applet class?
See here: Declaring Member Variables in Java
public void init() for which purpose this method can be use in applet
class?
See here: Life Cycle of an Applet and Applet init() method
I'm trying to add a JPanel with a picture in it. I'm using ImageIO.read to get the path but i get an IOException saying : can't read input file
The picture is called TCHLogo. It's a PNG inside a 'res' folder inside my project.
If there is any better way of displaying this image please also mention it!
Here is the code for my JPanel:
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.JPanel;
public class ImagePanel extends JPanel{
private BufferedImage image;
public ImagePanel() {
try {
//THIS LINE BELLOW WAS ADDED
image = ImageIO.read(getClass().getResourceAsStream("res/TCHLogo.png"));
} catch (IOException ex) {
// handle exception...
System.out.println(ex);
}
}
#Override
public void paintComponent(Graphics g) {
super.paintComponent(g); //THIS LINE WAS ADDED
g.drawImage(image, 0, 0, null); // see javadoc for more info on the parameters
}
}
Here is how i add the JPanel in my Applet:
ImagePanel appletRunningPanel;
appletRunningPanel = new ImagePanel();
appletRunningPanel.setSize(300, 300);
appletRunningPanel.validate();
add(appletRunningPanel);
EDIT
I created a folder inside the bin which the application starts to look in currently..
the folder is called res and the picture is inside..
Now i get the following IOException when i run the line:
image = ImageIO.read(getClass().getResourceAsStream("res/TCHLogo.png"));
Here is the error log:
java.lang.IllegalArgumentException: input == null!
at javax.imageio.ImageIO.read(ImageIO.java:1338)
at surprice.applet.ImagePanel.<init>(ImagePanel.java:17)
at surprice.applet.MainClass.init(MainClass.java:41)
at sun.applet.AppletPanel.run(AppletPanel.java:436)
at java.lang.Thread.run(Thread.java:679)
Likely your image's file path isn't correct relative to the user directory. To find out where Java is starting to look, where the user directory is, place something like this line of code somewhere in your program:
System.out.println(System.getProperty("user.dir"));
Perhaps you'd be better off getting the image as an InputStream obtained from a resource and not as a file. e.g.,
image = ImageIO.read(getClass().getResourceAsStream("res/TCHLogo.png"));
This will look for the image at the path given relative to the location of the class files, and in fact this is what you must do if your image is located in your jar file.
Edit 2
As an aside, often you need to first call the super's paintComponent method before doing any of your own drawing so as to allow necessary house-keeping can be done, such as getting rid of "dirty" image bits. e.g., change this:
public void paintComponent(Graphics g) {
g.drawImage(image, 0, 0, null);
}
to this:
public void paintComponent(Graphics g) {
super.paintComponent(g); // **** added****
g.drawImage(image, 0, 0, null);
}
I've written this ImagePanel class that i use for this scope :
public class ImagePanel extends JPanel {
private static final long serialVersionUID = 7952119619331504986L;
private BufferedImage image;
public ImagePanel() { }
public ImagePanel(String resName) throws IOException {
loadFromResource(resName);
}
public ImagePanel(BufferedImage image) {
this.image = image;
}
#Override
public void paintComponent(Graphics g) {
g.drawImage(image, 0, 0, null); // see javadoc for more info on the parameters
}
public BufferedImage getImage() {
return image;
}
public void setImage(BufferedImage image) {
this.image = image;
}
/**
* Load the Image from a File
* #param path image name and path
* #throws IOException
*/
public void loadFromFile(String path) throws IOException {
image = ImageIO.read(new java.io.File(path));
}
/**
* Load Image from resource item
* #param resName name of the resource (e.g. : image.png)
* #throws IOException
*/
public void loadFromResource(String resName) throws IOException {
URL url = this.getClass().getResource(resName);
BufferedImage img = ImageIO.read(url);
image = img;
}
}
Then i use the ImagePanel in this way :
//Inizialization of the ImagePanel
ImagePanel panelImage = new ImagePanel();
//Try loading image into the image panel
try {
panelImage.loadFromResource("/Resources/someimage.png");
} catch (java.io.IOException e) {
//Handling Exception
}
I have an image and I want to display it in the applet, The problem is the image wont display. Is there something wrong with my code?
Thanks...
Here's my code :
import java.applet.Applet;
import java.awt.*;
public class LastAirBender extends Applet
{
Image aang;
public void init()
{
aang = getImage(getDocumentBase(), getParameter("images.jpg"));
}
public void paint(Graphics g)
{
g.drawImage(aang, 100, 100, this);
}
}
aang = getImage(getDocumentBase(), getParameter("images.jpg"));
I suspect you are doing something wrong, and that should be just plain:
aang = getImage(getDocumentBase(), "images.jpg");
What is the content of HTML/applet element? What is the name of the image? Is the image in the same directory as the HTML?
Update 1
The 2nd (changed) line of code will try to load the images.jpg file in the same directory as the HTML.
Of course, you might need to add a MediaTracker to track the loading of the image, since the Applet.getImage() method returns immediately (now), but loads asynchronously (later).
Update 2
Try this exact experiment:
Save this source as ${path.to.current.code.and.image}/FirstAirBender.java .
/*
<applet class='FirstAirBender' width=400 height=400>
</applet>
*/
import javax.swing.*;
import java.awt.*;
import java.net.URL;
import javax.imageio.ImageIO;
public class FirstAirBender extends JApplet {
Image aang;
public void init() {
try {
URL pic = new URL(getDocumentBase(), "images.jpg");
aang = ImageIO.read(pic);
} catch(Exception e) {
// tell us if anything goes wrong!
e.printStackTrace();
}
}
public void paint(Graphics g) {
super.paint(g);
if (aang!=null) {
g.drawImage(aang, 100, 100, this);
}
}
}
Then go to the prompt and compile the code then call applet viewer using the source name as argument.
C:\Path>javac FirstAirBender.java
C:\Path>appletviewer FirstAirBender.java
C:\Path>
You should see your image in the applet, painted at 100x100 from the top-left.
1) we living .. in 21century, then please JApplet instead of Applet
import java.awt.*;
import javax.swing.JApplet;
public class LastAirBender extends JApplet {
private static final long serialVersionUID = 1L;
private Image aang;
#Override
public void init() {
aang = getImage(getDocumentBase(), getParameter("images.jpg"));
}
#Override
public void paint(Graphics g) {
g.drawImage(aang, 100, 100, this);
}
}
2) for Icon/ImageIcon would be better to look for JLabel
3) please what's getImage(getDocumentBase(), getParameter("images.jpg"));
there I'll be awaiting something like as
URL imageURL = this.getClass().getResource("images.jpg");
Image image = Toolkit.getDefaultToolkit().createImage(imageURL);
Image scaled = image.getScaledInstance(100, 150, Image.SCALE_SMOOTH);
JLabel label = new JLabel(new ImageIcon(scaled));
Well , above answers are correct. This is the code I used to display image. Hope it helps:
/*
<applet code = "DisplayImage.class" width = 500 height = 300>
</applet>
*/
import java.applet.Applet;
import java.awt.*;
public class DisplayImage extends Applet
{
Image img1;
public void init(){
img1 = getImage(getCodeBase(),"Nature.jpg" );
}
public void paint(Graphics g){
g.drawImage(img1, 0,0,500,300,this);
}
}
In above code, we create an image class object and get image from location specified by codebase. Then plot the image using drawImage method. Those who are interested in knowing value of getCodeBase() and getDocumentBase() methods can add following code in paint method. They are actually location of src folder in your project folder:-
String msg;
URL url=getDocumentBase();
msg="Document Base "+url.toString();
g.drawString(msg,10,20);
url=getCodeBase();
msg="Code Base "+url.toString();
g.drawString(msg,10,40);
One more point to note:- Make sure images and classes don't have same name in src folder. This was preventing my image to be displayed.