Runnable JAR file won't - java

I created this card game in Java. What it does it it presents one card face up and 4 more cards face down. You wager from 1 to 100 coins and try to pick a higher card from the face down cards. If you pick a higher card, your wager is doubled and you can choose to go double or nothing on another round.
The program uses 3 .java files in one package:
HigherNumber: Main class, contains the bulk of the code.
Deck: Contains definition for a class representing a deck of cards.
Card: Contains definition for a class representing an individual card.
So naturally, this program uses a lot of pictures, to represent the cards. In my original implementation, I just passed ImageIcon a string to represent the location of the cards. So like, for the icon for a face down card,
faceDown = new ImageIcon("multimedia/redBack.gif");
When I did this, the program ran perfectly when run through Eclipse. So I used Eclipse to Export to a runnable JAR file. This JAR file then ran without a problem, except if I moved the JAR file anywhere else, none of the images showed up.
So I researched and found out about using URLs to combat this. I reworked the program to use URLs, so now I have stuff like this:
//Set URL for default faceDown icon.
faceDownURL = this.getClass().getResource(pictureRoot +"redBack.gif");
//Set location for default back face of cards.
faceDown = new ImageIcon(faceDownURL);
Now it runs fine in Eclipse, but I cannot get the exported runnable JAR to work. When run from Windows, it just kinda blinks and does nothing. When I run through the command line, I get this:
C:\Documents and Settings\mstabosz>java -jar C:\Temp\HigherNumber.jar
Exception in thread "main" java.lang.NullPointerException
at javax.swing.ImageIcon.<init>(Unknown Source)
at higherNumber.Card.setImage(Card.java:150)
at higherNumber.Card.<init>(Card.java:36)
at higherNumber.Deck.<init>(Deck.java:22)
at higherNumber.HigherNumber.<init>(HigherNumber.java:16)
at higherNumber.HigherNumber.main(HigherNumber.java:857)
Trying to follow this code, it looks like the source of the problem is in the Card class at line 150. At line 150, the class is in the setImage() function, which is building a string called iconName to be used to set the image for each card as it is created. It then returns an ImageIcon to the Card class's constructor.
//Set up the icon for the card.
this.cardIcon = setImage();
Line 150 is the return statement. Here are the statements that create the URL cardIconURL which is used in the ImageIcon.
//Create a URL based on the constructed string.
URL cardIconURL = this.getClass().getResource(iconName);
return new ImageIcon(cardIconURL);
I just don't get what's going wrong here. The program worked fine as a runnable JAR when I was using Strings instead of URLs. It works fine when run through Eclipse. It doesn't work as a runnable JAR now.
I did read up on something called manifests, which I had trouble understanding. I did have Eclipse generate a manifest for this program:
Manifest-Version: 1.0
Main-Class: higherNumber.HigherNumber
What am I missing?

i use something like:
URL myurl = this.getClass().getResource("file.png");
myIconImage = Toolkit.getDefaultToolkit().getImage(myurl);
you're doing:
return new ImageIcon(cardIconURL);
Maybe try my second line. Also i store the images in the jar.

Okay it looks like I got the image files in the runnable JAR by dragging and dropping the "multimedia" folder which contains the pictures into the "highernumber" package in Eclipse. I'm still getting the NullPointerException though.

Related

How to write the right URL for an image

Im making a game with JavaFX and want to load images into it. Im having trouble with finding the correct URL to load the image
Its supposed to be a Memory game and the image is supposed to be loaded into a button for the player to interact with. Normally when I tried working with images, I start the URL at the projects folder and it works fine but here I keep getting error messages. I only get it to work when I type in the full URL from the C: Drive but shouldnt it also be possible to access it just from projects folder?
This is the constructor of the class for the Memory Cards
public MemoryCard(String front, int picID)
{
front = new ImageView(front);
picBack = new ImageView("src/grafics/back.jpg");
setGraphic(picBack);
//...
}
I have created a folder called 'grafics' under the source folder with the correct images inside. I thought this would work but it just gives me the IllegalArgumentException message on the line where I load the image.

Unable to set icon for java application using setIconImage() method

I'm trying to create one simple GUI based testing tool in Java using Eclipse. I have been trying to add icon to my application. Images are present inside the project in a folder. Could you please suggest what mistake I'm doing.
I'm used below two ways, unfortunately both are not helping me. -
1.) frame.setIconImage(image).
2.) setIconImage(Toolkit.getDefaultToolkit().getImage(getClass().getResource(Filepath)));
Below is the setup of my project in Eclipse -
Below is code which i'm using -
public static void main(String[] args) {
JFrame frame = new JFrame("Testing Tool");
// setting close operation
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// sets 500 width and 600 height
frame.setSize(500, 600);
try {
Image image = new ImageIcon("/Project_T/Images/biplane.jpg").getImage();
frame.setIconImage(image);
} catch(Exception e) {
System.out.println("Application icon not found");
}
// uses no layout managers
frame.setLayout(null);
// makes the frame visible
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
Since i'm going to create an .exe file for this project using lunach4J, is this the way of keeping files (placing them in a folder of project since I would be using multiple images and files) that ensures the application running on any machine.
This is the code I used with a Swing application packaged in an executable JAR file. The JFrame has the icon image.
private static final String APP_ICON_PATH = "myapp/icondirectory/report.png";
ImageIcon icon = new ImageIcon(ClassLoader.getSystemResource(APP_ICON_PATH));
frame.setIconImage(icon.getImage())
The "myapp" is the root of my package structure; e,g., the GUI class using the frame is in the package myapp.gui package. The image PNG files are within the application's executable JAR file (as you see in the code within a separate folder).
Also, look at the Oracle's Java Swing tutorials explain the usage of icons.
I fiddled a lot and finally found a way out , since my explanation was a bit long so I thought of writing an answer. Also please suggest that is this a good way since we would be exporting our project.
Java gives you the power to change the ICON for your application with the help
of setIconImage(image), but this method is not that direct, since we are
dealing with multiple files those should be present while executing the code so we
would have to ensure that their paths are correct and accessible in order to run smoothly.
Hence we save our files inside the src by creating another folder and from there
we can import the files easily. Follow these steps
Step - 0 - Place the files inside src folder of the project
Put the files inside the scr folder by creating another folder, here I created another folder by the name of images and placed my files there, hence the file path would be
"Images/biplane.png",
please ensure that there are no "/" placed before Images (our folder name)
Step - 1 - Place the file path inside a URL variable
Step - 2(Optional) - Print this URL variable to cross check that this is not null. If this is null check your path again and repeat the activity so that this value is not null.
Step - 3 - Now pass this URL to ImageIcon method.
Step - 4 - Call the setIconImage method with that image.
Code Used -
URL url = test.class.getClassLoader().getResource("Images/biplane.png");
System.out.println("Path for file is :- \"" + url + "\"");
Image image = new ImageIcon(url).getImage();
frame.setIconImage(image);

mediaPlayer.setSpu() not working

Currently I am working on some code based on VLCJ to play video content, which is working pretty fine, but I am struggling hard making the setSpu() method work.
Just to mention, when it comes to load an external subtitle, in a file apart from the video file, it is working fine. The problem appears when I try to play subtitles contained in the media file. (e.g. subs contained into a MKV file).
I read carefully GitHub post "setSpu not working #278", and I think that maybe the problem is that I am not invoking the setSpu() method correctly.
To make it simple, I am trying to make it works on the example "uk.co.caprica.vlcj.test.basic.TestPlayer".
On TestPlayer.java class, I loaded all native vlc required libs and configured the mediaPath, and mediaPlayer, so if I execute the class, the media player is built properly, and the video starts playing.
Now, to try make the subtitle work, I reused the button "subTitlesButton" on "PlayerControlsPanel.java". First of all, as the spu to be set is the ID of the TrackDescription, I added the following code, and executed to get the spuDescriptions list:
subTitlesButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
System.out.println(mediaPlayer.getSpuDescriptions());
}
});
When the Sub-titles button is pressed, the following output is get:
spuDescriptions=[TrackDescription[id=-1,description=Deshabilitar], TrackDescription[id=3,description=Pista 1 - [Español]], TrackDescription[id=4,description=Pista 2 - [Inglés]], TrackDescription[id=5,description=Pista 3 - [Español]]]
So, to keep it simple, I just tried to add the following code and execute it:
subTitlesButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
System.out.println(mediaPlayer.getSpuDescriptions());
mediaPlayer.setSpu(3); // TrackDescription[id=3,description=Track 1 - [Spanish]]
}
});
The expected resault would be the subtitle "Track 1 - [Spanish]" with ID=3 to appear on screen, but nothing happens. The video goes on and is being played properly, but the sub-title is not shown.
All the other buttons, work fine when you pressed them, you get the expected result (pause, stop, play, fastforward, rewind, and so on)... so I dont get the point on why media.setSpu() is not working there.
Would be much appreciated some help :)
Thanks in advance.
EDITED The exact problem was that all subtitles contained in the media file (video.mkv) were UTF8 text encoded. I tried to re-mount the video.mkv file with mkvmerge, but this program allways converts SRT files to UTF8 text format.
WORKAROUND convert the SRT files to ASS subtitles format. If the video.mkv contains .ASS subtitles format, the subtitles are always loaded properly by VLC and also by vlcj libs.
Thanks a lot in advance for all the help provided.
If this question can be distilled down to how to use external SPU files with non-ASCII characters, you can try this:
Suppose you have some filename for your external SPU file, the filename containing non-ASCII characters, let's call this spuFileName...
Try:
String asciiFileName = new File(spuFileName)
.toURI()
.toASCIIString();
Or:
String asciiFileName = new File(spuFileName)
.toURI()
.toASCIIString()
.replaceFirst("file:/", "file:///");
Then use asciiFileName instead when you specify the SPU file for vlcj.
If I remember correctly, LibVLC requires ASCII strings on its API. This problem can also show itself if you try and play a video with a filename that contains non-ASCII characters (vlcj detects this and handles it automatically).
But I'm not sure if this really is your problem as given the partial log you posted it looks like VLC has indeed detected the SPU tracks correctly.
On the other hand, if this suggestion does actually work, vlcj could be changed to handle this case (an external SPU file) automatically.
When actually selecting SPU for display, whether the SPU are in a separate file or contained within the video itself, the only thing that matters is the id of the SPU track. vlcj passes this id directly to the LibVLC API method. The fact that the track description strings are not being encoded directly does not matter.
In earlier versions of VLC, this id was actually the index of the SPU track - so 0, 1, 2, 3 and so on.
With the current version of VLC (this was changed around February 2013, I think this means VLC 2.1+) this was fixed to use the actual SPU track identifiers.
So depending on your version of VLC, if the track identifiers are not working for you try just passing an index instead.

NPE when referring to application resources

I am trying to display an icon on a button using the code posted below. But at run time, the console shows an NPE and highlights the code posted despite I am sure that the icon I wish to display on the button is placed in that path.
Note: the .. in the path is just a short for writing the whole path.
Code
ImageIcon iconplay = new ImageIcon (ClassLoader.getSystemResource("L:\\..\\..\\..\\..\\..\\..\\..\\..\\..\\Play.png"));
This is not a system resource, so don't try to use the system class loader. Something more like the following will use the context class loader.:
URL url = this.getClass().getResource("/path/to/the.resource");
That path starting with a drive letter is wrong. It should be a path relative to the class-path.

Creating a Pixmap in LibGDX can't find file

This code keeps throwing io.FileNotFoundException:
spriteBatch = new SpriteBatch();
spriteMap = new Texture(new Pixmap(new FileHandle("Sprites.png")));
spriteMap.setFilter(TextureFilter.MipMapLinearNearest, TextureFilter.MipMapLinearNearest);
spriteMap.setWrap(TextureWrap.ClampToEdge, TextureWrap.ClampToEdge);
sprites = new TextureRegion(spriteMap).split(16, 16);
any ideas what's wrong? i have also tried spriteMap = new Texture(new Pixmap(Gdx.files.internal("Sprites.png"))); but no luck...Sprites.png is just right in the package this class is in
While using this:
spriteMap = new Texture(new Pixmap(Gdx.files.internal("Sprites.png")));
be totally sure you have a file called "Sprites.png" (with the capital 'S') inside your assets folder.
assets/Sprites.png
If you have a folder between, for example data (created with the Libgdx-setup-ui by default). then you would need to put it aswell.
assets/data/Sprites.png
If you are sure the file is there. Then:
If running from eclipse, refresh your project (f5), it may be unsynchronized)
If this only happens in the Desktop project, then maybe your assets folder is not correctly linked.
Edit:
You edited your question :p
Sprites.png is just right in the package this class is in
thats your problem, Gdx.files.internal looks into the Android assets folder. not the folder in which the class is in.

Categories

Resources