Background not showing up in java processing project - java

I think I'm doing everything right in my code but my background won't show up in my processing project, here is my code.
package finalproject;
import processing.core.PApplet;
import processing.core.PImage;
public class FinalProject extends PApplet {
PImage background;
PImage player;
public void setup() {
size(1360, 1080);
player = loadImage("player.png");
background = loadImage("rust.png");
}
public void draw() {
background(background);
image(player, 500, 500);
}
}

Processing expects files to be inside a data directory next to the code.
You're presumably running this from an IDE like Eclipse instead of the Processing editor, so where you put that data directory depends on how your code is setup. And you haven't posted a MCVE, so it's hard to help you with that.
But basically, you need to debug your sketch to figure out exactly where Processing is looking for the files. Then you need to move the files there. This is probably something simple like putting them inside a data directory.
If you still can't get it working, please post a MCVE along with a screenshot or a description of your directory structure.

If you are using the processing IDE than the data folder should be located in your sketch folder next to all the .pde files. Make sure that the image you are using has the same resolution as the sketch window. If you are still having issues I would recommend that you try moving your setup and draw methods out of your class and into the main processing sketch.

Related

Getting a mp3 file to play using javafx

I have spent hours today looking up how to get some form of audio in eclipse and have had trouble every step of the way. Currently I have something that should work but I get an error:
Exception in thread "main" java.lang.IllegalArgumentException: expected file name as argument
at com.sun.javafx.css.parser.Css2Bin.main(Css2Bin.java:44)
I have basically copied this from someone who had it working. I would like to say that the FX lib is added where it should be. I know this isn't fancy but I was just trying the basics.
package b;
import java.io.File;
import javafx.scene.media.Media;
import javafx.scene.media.MediaPlayer;
public class test {
public static void main(String[] args){
String uriString = new File("C:\\Users\\Mike\\workspace\\b\\src\\hero.mp3").toURI().toString()
MediaPlayer player = new MediaPlayer( new Media(uriString));
player.play();
}}
I have also tried many different path names in case it was wrong with no luck, I also just tried to copy and paste the path name that i got in eclipse by going to properties ex: /b/src/hero.mp3. Help would be appreciated to get me out of this nightmare.
The files located outside the workspace should be included with file:// prefix. A simple example demonstrating the functionality is
public class Reproductor extends Application {
public static void main(String[] args) {
launch(args);
}
#Override
public void start(Stage stage) throws Exception {
Media media = new Media("file:///Movies/test.mp3"); //replace /Movies/test.mp3 with your file
MediaPlayer player = new MediaPlayer(media);
player.play();
}
}
If the file is into the resources/music this will work and the application will be portable,.mp3 inside the .jar:
Media media = null;
try {
media = new Media(getClass().getResource("/music/hero.mp3").toURI().toString());
} catch (URISyntaxException e) {
e.printStackTrace();
}
I suspect you have a issue with referencing embedded resources. An embedded resource is any file which is contained within the application context (ie. In this case, stored within the application Jar).
In order to obtain a reference to these resources, you need to use Class#getResource, which returns a URL, which you can then use to load the resource depending on your requirements, for example...
public class Main extends Application {
#Override
public void start(Stage primaryStage) {
String path = Test.class.getResource("/Kalimba.mp3").toString();
Media media = new Media(path);
MediaPlayer mp = new MediaPlayer(media);
mp.play();
System.out.println("Playing...");
}
public static void main(String[] args) {
launch(args);
}
}
Now, I couldn't get it to work until I wrapped in a Application context...
JavaFX EMBED an MP3 into the jar (in the jar) with NetBeans
I programmed my very first JavaFX package in NetBeans, and then I wanted to add sound, an mp3 music file, embedded in the jar, inside the jar, so that I could email the jar to my friends and the music would play on their computers. Thank you StackOverflow for your help. Thanks especially to the member who said “put your music file IN THE JAR, getResourceAsStream() is the API you want to use.” He put me on the right track, although I ended up using getResource(). It works.
STEP 1: Firstly, I got the music to play when I hit run in NetBeans.
STEP 2: I wanted the music to loop (repeat). Eventually I got that right, thanks to the members of StackOverflow. Please see my source code.
STEP 3: Finally I got the mp3 to EMBED in the jar. Now, this is important. At first the music played on my computer, but the jar read it off my hard disc. When I changed the name of the mp3, then the jar crashed, it would not run, it could not find the mp3. I had to embed the mp3 into the jar, put it inside the jar (in the jar) otherwise it would not play on somebody else’s computer. That’s where getResource() did the trick.
STEP 4: Then I emailed my jar to friends. Some service providers don’t trust a jar, they sent the emails back to me, undelivered. Other service providers don’t have a problem and delivered the emails. So, what did I do? I changed the name of the *.jar to *.mp4 and the emails were delivered, I asked my friends to change it back from *.mp4 to *.jar. It worked.
Here is my source code. I’m sure it’s not perfect, but it works, thanks to StackOverflow.
/* Of course, one needs to import the following gizmo’s (and others): */
import javafx.util.Duration;
import javafx.scene.media.Media;
import javafx.scene.media.MediaPlayer;
/* I want to EMBED the music inside the jar (in the jar).
The secret seems to be getResource. The source code starts here,
to EMBED the sound (DollyParton.mp3) into the jar: */
//************************ begin the music ***********************
#Override public void start(Stage primaryStage) throws Exception {
init(primaryStage);
primaryStage.show();
play();
}
public static void main(String[] args) {
launch(args);
}
MediaPlayer musicplayer; {
/* Put your music file IN THE JAR, "getResourceAsStream()" is
the API you want to use. Put the DollyParton.mp3 into the Windows
folder src/rockymountain. NetBeans automatically copies the mp3
to the folder build/classes/rockymountain. */
Media mp3MusicFile = new Media(getClass().getResource("DollyParton.mp3").toExternalForm());
musicplayer = new MediaPlayer(mp3MusicFile);
musicplayer.setAutoPlay(true);
musicplayer.setVolume(0.9); // from 0 to 1
//***************** loop (repeat) the music ******************
musicplayer.setOnEndOfMedia(new Runnable() {
public void run() {
musicplayer.seek(Duration.ZERO);
}
});
//*************** end of loop (repeat) the music **************
}
//**************************** end of music *************************
I put the mp3 into the Windows folder src/rockymountain. Then NetBeans automatically copied the mp3 to the folder build/classes/rockymountain. NetBeans does not copy the mp3 to the folder /resources, a file that I created unnecessarily, because someone said so. The /resources folder is not needed, it remains empty.
Create a Java ARchive (jar) file using NetBeans as follows:
Right-click on the Project name
Select Properties
Click Packaging
Check Build JAR after Compiling
Check Compress JAR File
Click OK to accept changes
Right-click on the Project name
Select Clean and Build
The JAR file is built. To view it inside NetBeans:
Click the Files tab
Expand ProjectName >> dist (distribution). The jar file is inside the dist folder.
Try to add --add-modules=javafx.controls,javafx.media in your VM options.
I tried this three lines and it worked!
Media sound = new Media(new File("src/music/menu.mp3").toURI().toString());
MediaPlayer player = new MediaPlayer(sound);
player.play();
First you need to put the code in try and catch to catch any error, second you must
define the JFXPanel to define it to the media package and the tool kit ,so this is the code:
package test1;
import java.io.File;
import javafx.scene.media.Media;
import javax.swing.JOptionPane;
import javafx.scene.media.MediaPlayer;
import javafx.embed.swing.JFXPanel;
public static void main(String[] args) {
try {
JFXPanel j = new JFXPanel();
String uriString = new File(""C:\\Users\\Mike\\workspace\\b\\src\\hero.mp3"").toURI().toString();
MediaPlayer Player = new MediaPlayer(new Media(uriString));
Player.play();
} catch (Exception ex) {
JOptionPane.showMessageDialog(null, ex);
}
}
and a good info for you can put only file name
inside the File() exp: String uri = new File("hero.mp3").toURI().toString();

How am I supposed to draw an image from my Java Applet?

I am not sure how to fully express this but, I have probably gone through 10 pages of Google links on this topic and not one of them has helped me solve my issue.
I thought it would be simple enough, I was just trying to add an image to the paint function of my java applet, like any other shape, but this has turned out to be a nightmare for me.
The problem is that every time I try to run the drawImage function it keeps saying Access Denied ("java.io.FilePermission" "Image.jpg" "read"). Yet, none of the tutorials mention this at all, all they ever say is that I should do the following:
import java.applet.*;
import java.awt.*;
Image img;
//These would go in the paint function
img=getImage(getDocumentBase(),"/Image.jpg"); //I have tried without the slash too
g.drawImage(img,20,20,this);
This is all they do and it works for them, but it just won't work for me. Other methods are far too complex for the sake of just adding an image, and even when I go through the toil of doing those it keeps giving me the "Access Denied" message. There's also the method of "signing" it, but I really don't think that's going to help given all that I have tried, so I am afraid it might just be another wasted endeavor. None of the tutorials even tell you to have your applet signed.
I have the image in the "build" (also called bin) folder together with the classes.
The program seemed to run when I included the entire file path, but even then the image did not display. That is not to mention I can't really include the complete path from my own computer because then it wouldn't work when I actually send it to another person.
Please, I just want to know why it doesn't work for me yet seems to work perfectly for others. That, and if there's a way around this.
This is an example of what I am doing:
import java.applet.*;
import java.awt.*;
public class JavaProject extends JApplet
{
Image img;
public void init()
{
img=getImage(getDocumentBase(),"/Image.jpg");
}
public void paint(Graphics g)
{
super.paint(g);
g.drawImage(img,20,20,this);
}
}
This is my HTML file:
<html>
<head>
<title> My First Web Page </title>
</head>
<body>
<applet code="JavaProject.class" width="400" height="500">
</applet>
</body>
</html>
According JApplet java docs method getImage(URL url, String name) should have two parameter: URL-link to picture and String name.
Is method getDocumentBase() returnig an URL-link?
You must start by understanding that an Applet, unless signed, may not read from the file system. It must use either classpath resources or things fetched from the same place it was fetched from. You have to decide which of these applies to you. If the image is a fixed image, you can put it in your classpath as a resource, and use Class.getResourceAsStream. If it's a different image every time, you'll have to use HTTP.
Try this one if the image in the "build" (also called bin) folder together with the classes.
import java.awt.Graphics;
import java.awt.Image;
import java.net.URL;
import javax.swing.JApplet;
public class JavaProject extends JApplet {
Image img;
public void init() {
img = getImage(getDocumentBase(), "images/222.png");
// Please ensure that 222.png is placed under bin/images folder directly
}
#Override
public void paint(Graphics g) {
update(g);
}
#Override
public void update(Graphics g) {
g.drawImage(img, 20, 20, this);
}
}
Try with HTTP URL first
URL myURL = new URL("https://www.gravatar.com/avatar/a94613cea642e6e9e2105867bc2e103e?s=32&d=identicon&r=PG&f=1");
img = getImage(myURL);
If you are using Eclipse under Windows then have a look at below screenshot:
Please have a look at below post to get some understanding about it.
java.io.FilePermission exception - Read from jar file?

Stanford CS106a newbie - Having trouble compiling in Eclipse

I'm following along with Stanford's CS106a class and trying to do the assigments. I had difficulty running the sample code from the book but somehow managed to run them with the ACM package. Right now I'm trying to do the assignments and run my own code. I've created a "project" and a .java file in that project. I don't know how to run it though. I keep getting the following:
Error: Could not find or load main class Pyramid.
I think it is because the program isn't accessing the ACM package. Below is the code although I think it would happen with any code I write. Any help would be appreciated.
Thanks so much.
import acm.graphics.*;
import acm.program.*;
import java.awt.*;
public class GRectExample extends GraphicsProgram {
public void run() {
GRect rect = new GRect(100, 50, 125, 60);
rect.setFilled(true);
rect.setColor(Color.RED);
add(rect);
}
}
Create a main method inside GRectExample class, for examle
import acm.graphics.*;
import acm.program.*;
import java.awt.*;
public class GRectExample extends GraphicsProgram {
public void run() {
GRect rect = new GRect(100, 50, 125, 60);
rect.setFilled(true);
rect.setColor(Color.RED);
add(rect);
}
public static void main(String args[])
{
new GRectExample().run();
}
}
Looks like you have to tell Eclipse where to locate the ACM package, most of the times it can't assume the exact location.
Right click on your project folder and select Properties.
Select the Java Build Path option and click on the "Add External JARs" and that will include it into your project...
Not too familiar with Eclipse, but here's a suggestion:
Right - Click on the Project folder
click Properties at the bottom
click Run/Debug Settings
Make sure your Launching class is the list. Click on it, make sure it's the Main class
Make sure you use the fully qualified name i.e. mypackage.MyClass
Also try clicking all of them in the list. And make sure only the one you want to be the launching class has the Main Class field filled in.

Error with Images

I recently finished the basics of a game that I'm making and I was going to send it to some friends, but whenever they open the .jar it's just a grey window. When I heard that I assumed it was because of the way I got the images (I used a full path: C:\Users\etc). I did some Googling and found a way to get images that seemed more efficient.
private static Image[] mobImages = new Image[1];
public static void loadImages()
{
mobImages[1] = Handler.loadImage("res/EnemyLv1.png");
}
public static Image getMobImages(int index)
{
return mobImages[index];
}
That's what I would like to use. But I did that and changed the rest of my code to support that. And whenever I run a game I get a few errors. Which all point back to
this:
if(getBounds().intersects(tempEnemy.getBounds()))
and so probably the way I'm getting the images too. How could I fix this? And are there better ways to get Images? I've tried a few but they haven't worked.
EDIT: I finally solved all of the errors! :D The only problem is that none of the images appear. Here's my code again. Any more help? That would be fantastic! Thanks everybody for the support so far!
Hard to say whats going wrong in your code. However I recommend you put your image files into a package in the java project (so they will be part of the JAR file) and access them using Class.getResource()/Class.getResourceAsStream(). That avoids multiple pitfalls and keeps everything together.
A sample how to structure your images into the packages:
myproject
images
ImageLocator.class
MyImage1.jpg
MyImage2.jpg
The ImageLocator class then needs to use relative pathes (just the image name + extension) to access to resources.
public class ImageLocator {
public final static String IMAGE_NAME1 = "MyImage1.jpg";
public static Image getImage(final String name) {
URL url = ImageLocator.class.getResource(name);
Image image = Toolkit.getDefaultToolkit().createImage(url);
// ensure the image is loaded
return new ImageIcon(image).getImage();
}
}
This can be done more elegant, but this should get you started. Defining the image names as constants in the ImageLocator class avoids spreading the concrete path throughout the project (as long as the name is correct in ImageLocator, everything else will be checked by the compiler)
Your code still uses "C:\Users\Kids\Desktop\Java Game\Cosmic Defense\res\EnemyLv2.png" in Enemy.java. Are you sure this exists? If you moved the Cosmic Defense folder, it will not.
(You were talking about changing absolute paths to relative paths, so this may be your problem)
Part of the reason could be that your code is pointing to an index of "1" in an array of size 1, meaning that the only available index is in fact "0".
Try mobImages[0] = Handler.loadImage("res/EnemyLv1.png");

Image not showing in applet

I have a small JApplet that is supposed to simply import an image and display it on screen. However, I am having some trouble with it.
private Image logo1;
public void init() {
logo1 = getImage( getCodeBase(), "Penguins.jpg" );
}
#Override
public void paint( Graphics g ) {
g.drawImage( logo1, 0, 0, this );
}
That is essentially my entire program. Is there any problem with it? I am assuming one of the problems might be that the picture might have to be in a specific part of your computer or something like that...The address for this image is C:\Users\Public\Pictures\Sample Pictures
The reason that getCodeBase() is in the method call of getImage() is to get the codebase location.
The codebase is the folder that holds all of your source packages. It's most likely the folder above your src folder for your project. Here's the basic structure of a normal project (at least my projects):
-MyProject - This is the codebase
-src - All of your code is probably in this folder. All packages show up as folders here
-bin - When your code compiles, it ends up here
-data - This is where all of the resources are held (my preference)
-images - Pretty obvious, the image would go here
-Penguin.jpg - Your image
All this leads up to this answer: With the above structure, your call to getImage() should read:
getImage(getCodeBase(), 'data/images/Penguin.jpg');
Try including the image that you want to display in the folder of your java program. Sometimes if the image is in another folder, it's not displayed in the applet.
I too faced a similar problem. Just copy the image into your project folder.
public void init() {
Picture = getImage(getDocumentBase(),"image.gif");
}
I use this code. Do following steps to add your image:
Clean and Build the project
Add the image into build folder of your project.
Run the project.

Categories