Image reading working in Eclipse but not exported JAR file - java

Everything has been working fine in my level editor program I've been working on until I decided to export the JAR file for a beta version. All the image loading works perfectly in Eclipse but once I try to run it as an external JAR file I get this error: http://puu.sh/kP681/1be9b77e21.png
Here is the code I'm using to load the image, it is working in Eclipse.
public static void main(String[] args) {
BufferedImage appIcon = null;
try {
appIcon = ImageIO.read(new File("res" + File.separator + "appicon.png"));
} catch (IOException e1) {
e1.printStackTrace();
}
JFrame frame = new JFrame("Mario Map Creator");
frame.setSize(RESELOUTION);
frame.setLocationRelativeTo(null);
frame.setResizable(false);
frame.setIconImage(appIcon);
That doesn't appear to be working, that is the MapCreator class.
Then the MapCreatorPanel class
public MapCreatorPanel() {
this.setLayout(null);
try {
levelIcon = new ImageIcon(ImageIO.read(new File("res" + File.separator + "levelicon.png")));
flagIcon = new ImageIcon(ImageIO.read(new File("res" + File.separator + "flagicon.png")));
scriptIcon = new ImageIcon(ImageIO.read(new File("res" + File.separator + "scripticon.png")));
} catch (IOException e) {
e.printStackTrace();
}
scriptManager = new ScriptManager();
}
Thanks for your help in advance!
ALSO NOTE: I've looked at a bunch of other posts on this site and all their solutions didn't seem to work for me (unless I was doing something wrong).

Related

Java Cannot load a custom font from file and set JTextArea's font to it

So I'm trying to make a simple application, and I got a window appearing. The problem is that I require some special font, which I doubt would be installed on the user's OS, so I've got to load it from a file.
I've read countless articles and I've been stuck on this for quite a while and I'm not sure if the font isn't being loaded or it's not registering. I've also gotten confused with the type of "Stream" to use, because countless tries with InputStream, FileInputStream and BufferStream have lead to nothing.
The font is being copied to the output directory. This is my project structure
<packages-with-classes>
fonts
-> gameFont.ttf
This is the code I'm using
displayArea = new JTextArea();
displayArea.setEditable(false);
//FONT to give graphics (plz help me)
GraphicsEnvironment ge = null;
try {
//ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
/*Font initFont = Font.createFont(Font.TRUETYPE_FONT, Main.class.getClassLoader().getResourceAsStream("/fonts/gameFont.ttf") );
Font fontBase = initFont.deriveFont(Font.PLAIN, 20);*/
Font gameFnt = Font.createFont(Font.TRUETYPE_FONT, Main.class.getClassLoader().getResourceAsStream("fonts/gameFont.ttf")).deriveFont(Font.PLAIN, 12f);
GraphicsEnvironment.getLocalGraphicsEnvironment().registerFont(gameFnt);
displayArea.setFont(gameFnt);
} catch (IOException e) {
e.printStackTrace();
} catch(FontFormatException e) {
e.printStackTrace();
}
So after a really really huge headache, I got it working :)
Here's the code if anyone else is stuck on the same problem:
InputStream fontStream = Main.class.getResourceAsStream("/fonts/gameFont.ttf");
try {
Font gameFont = Font.createFont(Font.TRUETYPE_FONT,fontStream);
gameFont=gameFont.deriveFont(Font.PLAIN, 14);
displayArea.setFont(gameFont);
} catch (FontFormatException | IOException e) {
e.printStackTrace();
}

Setting a custom font to a JLabel

I'm doing a simple Pong game and wanted to add an 8-Bit font but can not figure how.
This is the method I used for JLabels:
public void drawScore()
{
player1 = "Player 1";
player2 = "Player 2";
JLabel leftScore = new JLabel(player1);
JLabel rightScore = new JLabel(player2);
leftScore.setForeground(Color.white);
rightScore.setForeground(Color.white);
leftScore.setLocation(20, 0);
rightScore.setLocation(730, 0);
leftScore.setSize(100, 40);
rightScore.setSize(100, 40);
add(leftScore);
add(rightScore);
}
I tried solutions which I found on here and other web-sites and they didn't work out well either. There is a .TTF file in a folder called 'assets' -which I created- in Java Project Folder named Pong. It would be perfect if the right code not include try and catch blocks.
private static Font fontAwesome;
static {
try (InputStream in = YOURCLASS.class.getClassLoader().getResourceAsStream("assets/fontawesome-webfont.ttf")) {
fontAwesome = Font.createFont(Font.TRUETYPE_FONT, in);
} catch (FontFormatException | IOException e) {
e.printStackTrace();
}
}
Here's an example with fontawesome. Paste that at the top of your class and then simply use
leftScore.setFont(fontAwesome); to set the font.
Unfortunately you're going to need the try/catches. Note that the multicatch block might not work depending on your language level. If it doesn't just split them into two catch blocks.
Please try this:
try {
InputStream is = YourClass.class.getResourceAsStream("path/to/font");
Font font = Font.createFont(Font.TRUETYPE_FONT, is);
Font sizedFont = font.deriveFont(18f);
jLabel.setFont(sizedFont);
} catch (Exception ex) {
System.err.println("Not loaded");}
After you load the font you need to set a size to it!
You will have to use try/catch blocks to do this.

add .ttf file to java project

I have downloaded akshar.ttf file and want to add it to my java project. I have tried the following ways by searching online but nothing worked so far.
Try 1:
Font ttfBase = null;
Font ttfReal = null;
try {
InputStream myStream = new BufferedInputStream(new FileInputStream("akshar.TTF"));
ttfBase = Font.createFont(Font.TRUETYPE_FONT, myStream);
ttfReal = ttfBase.deriveFont(Font.PLAIN, 24);
} catch (Exception ex) {
ex.printStackTrace();
System.err.println("akshar font not loaded.");
}
Try 2:
Font font = new Font("akshar",Font.PLAIN,15);
I have the akshar.ttf file at the following places:-
java/jre/lib/fonts
bin folder of my project
src folder of my project
I am new to java and have tried all these by following various links online. Please help me where am i going wrong.
You can register the created font with the graphics environment , as below :
try {
GraphicsEnvironment ge =
GraphicsEnvironment.getLocalGraphicsEnvironment();
ge.registerFont(Font.createFont(Font.TRUETYPE_FONT, new File("akshar.TTF"));
} catch (IOException|FontFormatException e) {
//Handle exception
}
Refer the Java tutorial.
Put your ttf into the assests folder :)

Java - How to access an image packed in an applet jar

I have created an applet jar. That jar contains an images in the following folder
com\common\images\red.bmp
Now, I want to display this image on the Swing Applet.
private static final ImageIcon redIndicator = new ImageIcon("com\\common\\images\\red.bmp");
After that, I have attached the redIndicator to a JPanel but I am not able to see this image.
Any suggestions?
==================================EDITED=========================================
private static final ImageIcon marker = loadImage("com/common/images/scale.jpg");
#SuppressWarnings("unused")
private static ImageIcon loadImage(String imagePath) {
BufferedInputStream imgStream = new BufferedInputStream(TpcHandler.class.getResourceAsStream(imagePath));
int count = 0;
if (imgStream != null) {
byte buf[] = new byte[2400];
try {
count = imgStream.read(buf);
} catch (java.io.IOException ioe) {
return null;
} finally {
if (imgStream != null)
try {
imgStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (count <= 0) {
LOGGER.warning("Empty image file: " + imagePath);
return null;
}
return new ImageIcon(Toolkit.getDefaultToolkit().createImage(buf));
} else {
LOGGER.warning("Couldn't find image file: " + imagePath);
return null;
}
}
I am getting the following exception
java.io.IOException: Stream closed
at line count = imgStream.read(buf);
This should do the trick (if called from a class loaded from that same jar):
new ImageIcon(getClass().getResource("/com/common/images/red.bmp"))
Use YourPanel.class.getResourceAsStream("/com/common/images/red.bmp"), read the stream to a byte[] and construct the ImageIcon based on that. (and don't use bmps - prefer png or jpeg)
Applets and Images that is a frequently asked questions so, as for Java applets and images, I recommend you read one of my previous answers hope it helps a bit :)
Good luck

How do I open an image in the default image viewer using Java on Windows?

I have a button to view an image attached to a log entry and when the user clicks that button I want it to open the image in the user's default image viewer on a Windows machine?
How do I know which viewer in the default image viewer?
Right now I'm doing something like this but it doesn't work:
String filename = "\""+(String)attachmentsComboBox.getSelectedItem()+"\"";
Runtime.getRuntime().exec("rundll32.exe C:\\WINDOWS\\System32\\shimgvw.dll,ImageView_Fullscreen "+filename);
And by doesn't work I mean it doesn't do anything. I tried to run the command just in the command line and nothing happened. No error, nothing.
Try with the CMD /C START
public class Test2 {
public static void main(String[] args) throws Exception {
String fileName = "c:\\temp\\test.bmp";
String [] commands = {
"cmd.exe" , "/c", "start" , "\"DummyTitle\"", "\"" + fileName + "\""
};
Process p = Runtime.getRuntime().exec(commands);
p.waitFor();
System.out.println("Done.");
}
}
This will start the default photo viewer associated with the file extension.
A better way is to use java.awt.Desktop.
import java.awt.Desktop;
import java.io.File;
public class Test2 {
public static void main(String[] args) throws Exception {
File f = new File("c:\\temp\\test.bmp");
Desktop dt = Desktop.getDesktop();
dt.open(f);
System.out.println("Done.");
}
}
See Launch the application associated with a file extension
You can use the Desktop class which does exactly what you need, to open system associated application.
File file = new File( fileName );
Desktop.getDesktop().open( file );
Another solution that works well on Windows XP/Vista/7 and can open any type of file (url, doc, xml, image, etc.)
Process p;
try {
String command = "rundll32 url.dll,FileProtocolHandler \""+ new File(filename).getAbsolutePath() +"\"";
p = Runtime.getRuntime().exec(command);
p.waitFor();
} catch (IOException e) {
// TODO Auto-generated catch block
} catch (InterruptedException e) {
// TODO Auto-generated catch block
}

Categories