Eclipse exported jar file just shows a black Jpanel - java

I am working on a java game and the game works perfectly in eclipse, but when I exported is as a runnable jar file it did not work. Only a black window showed up.
My game has a splash screen which changes to menu screen after few seconds. the splash screen sconsists of an BufferedImage (in jpg) but the menu screen also consists of a Graphics2D writing. Few seconds after running the jar file the writing doesn't show up, so I think image formats and such might not be the issue.
I'm quite confused and frustrated so any help would be appriciated.
It turned out the problem is in my use of Timer, this is my source of the splashscreen
package GameState;
import java.awt.Graphics2D;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.Timer;
import Main.GamePanel;
public class SplashState extends GameState implements ActionListener{
private BufferedImage image;
private Timer timer;
public SplashState(GameStateManager gsm) {
this.gsm = gsm;
try {
image = ImageIO.read(new File("Resources/Backgrounds/block.jpg"));
timer = new Timer(2000, this);
timer.setRepeats(false);
timer.start();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void init() {
}
public void update() {
}
public void draw(Graphics2D g) {
g.drawImage(image, (GamePanel.WIDTH-image.getWidth())/2, (GamePanel.HEIGHT-image.getHeight())/2, null);
}
public void keyPressed(int k) {
}
public void keyReleased(int k) {}
public void actionPerformed(ActionEvent arg0) {
// TODO Auto-generated method stub
gsm.setState(GameStateManager.MENUSTATE);
timer.stop();
}
}
I still don't know what's wrong so any help would be appriciated

I've had a similar problem in the past, and it was due to the way Eclipse was packaging the required libraries into the jar. I would bet you have it set to "Extract required libraries into generated jar", and you should set it to "Package required libraries into generated jar". To do this, right click on project -> Export -> Java -> Runnable Jar File. Then click next, and select the radio button for "Package required libraries into generated jar". This should fix your problem.
If you are writing to an image, the image must be outside of the jar file, because you cannot edit a jar file while it is running. If this is the case, you may want to make a folder that contains your jar and the images it will write to.

Related

Swing JMenuItem - Icons not showing up [duplicate]

I am having a error for my GUI. Trying to set title bar icon then be included in a Runnable JAR.
BufferedImage image = null;
try {
image = ImageIO.read(getClass().getClassLoader().getResource("resources/icon.gif"));
}
catch (IOException e) {
e.printStackTrace();
}
frame.setIconImage(image);
Here is the error I am getting:
Exception in thread "main" java.lang.IllegalArgumentException: input == null!
at javax.imageio.ImageIO.read(Unknown Source)
at GUI.<init>(GUI.java:39)
at GUI.main(GUI.java:351)
The image is in the correct directory which "resources" folder is the root of the
project file
First of all, change this line :
image = ImageIO.read(getClass().getClassLoader().getResource("resources/icon.gif"));
to this :
image = ImageIO.read(getClass().getResource("/resources/icon.gif"));
More info, on as to where lies the difference between the two approaches, can be found on this thread - Different ways of loading a Resource
For Eclipse:
How to add Images to your Resource Folder in the Project
For NetBeans:
Handling Images in a Java GUI Application
How to add Images to the Project
For IntelliJ IDEA:
Right-Click the src Folder of the Project. Select New -> Package
Under New Package Dialog, type name of the package, say resources. Click OK
Right Click resources package. Select New -> Package
Under New Package Dialog, type name of the package, say images. Click OK
Now select the image that you want to add to the project, copy it. Right click resources.images package, inside the IDE, and select Paste
Use the last link to check how to access this file now in Java code. Though for this example, one would be using
getClass().getResource("/resources/images/myImage.imageExtension");
Press Shift + F10, to make and run the project. The resources and images folders, will be created automatically inside the out folder.
If you are doing it manually :
How to add Images to your Project
How to Use Icons
A Little extra clarification, as given in this answer's first
code example.
QUICK REFERENCE CODE EXAMPLE(though for more detail consider, A little extra clarification link):
package swingtest;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.*;
/**
* Created with IntelliJ IDEA.
* User: Gagandeep Bali
* Date: 7/1/14
* Time: 9:44 AM
* To change this template use File | Settings | File Templates.
*/
public class ImageExample {
private MyPanel contentPane;
private void displayGUI() {
JFrame frame = new JFrame("Image Example");
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
contentPane = new MyPanel();
frame.setContentPane(contentPane);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
private class MyPanel extends JPanel {
private BufferedImage image;
public MyPanel() {
try {
image = ImageIO.read(MyPanel.class.getResource("/resources/images/planetbackground.jpg"));
} catch (IOException ioe) {
ioe.printStackTrace();
}
}
#Override
public Dimension getPreferredSize() {
return image == null ? new Dimension(400, 300): new Dimension(image.getWidth(), image.getHeight());
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawImage(image, 0, 0, this);
}
}
public static void main(String[] args) {
Runnable runnable = new Runnable() {
#Override
public void run() {
new ImageExample().displayGUI();
}
};
EventQueue.invokeLater(runnable);
}
}
There's a much easier way to load and set an image as a frame icon:
frame.setIconImage(
new ImageIcon(getClass().getResource("/resources/icon.gif")).getImage());
And thats all :)! You don't even have to use a try-catch block because ImageIcon does not throw any declared exceptions. And due to getClass().getResource(), it works both from file system and from a jar depending how you run your application.
If you need to check whether the image is available, you can check if the URL returned by getResource() is null:
URL url = getClass().getResource("/resources/icon.gif");
if (url == null)
System.out.println( "Could not find image!" );
else
frame.setIconImage(new ImageIcon(url).getImage());
The image files must be in the directory resources/ in your JAR, as shown in How to Use Icons and this example for the directory named images/.

Easily print image on the screen for debug purposes in a blocking manner

I am working on a computer vision project and somewhere in a process an endless loop happens. It seems that my image data is being corrupted.
In past, I used to save debug results on the disk using this method:
public static boolean saveToPath(String path, BufferedImage image) {
File img = new File(path);
try {
ImageIO.write(image, "png", new File(path));
} catch (IOException ex) {
System.err.println("Failed to save image as '"+path+"'. Error:"+ex);
return false;
}
return true;
}
The problem is that once loops are used and the error is somewhere inbetween, I need to see many images. So basically, I'd like a method that would be defined like this:
/** Displays image on the screen and stops the execution until the window with image is closed.
*
* #param image image to be displayed
*/
public static void printImage(BufferedImage image) {
???
}
And could be called in a loop or any function to show be the actual image, effectively behaving like a break point. Because while multithreading is very good in production code, blocking functions are much better for debugging.
You can code something like this. In this example, the image file has to be in the same directory as the source code.
Here's the image displayed in a dialog. You left click the OK button to continue processing.
If the image is bigger than your screen, scroll bars will appear to let you see the whole image.
In your code, since you already have the Image, you can just copy and paste the displayImage method.
package com.ggl.testing;
import java.awt.Image;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
public class DisplayImage {
public DisplayImage() {
displayImage(getImage());
}
private Image getImage() {
try {
return ImageIO.read(getClass().getResourceAsStream(
"StockMarket.png"));
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
public void displayImage(Image image) {
JLabel label = new JLabel(new ImageIcon(image));
JPanel panel = new JPanel();
panel.add(label);
JScrollPane scrollPane = new JScrollPane(panel);
JOptionPane.showMessageDialog(null, scrollPane);
}
public static void main(String[] args) {
new DisplayImage();
}
}

How to place image in source folder and use it in Eclipse

I am teaching myself how to use images in Eclipse.
I am trying to get my code implementing images to compile:
import java.awt.*;
import javax.swing.JFrame;
import java.io.File;
import javax.imageio.ImageIO;
public class ImageDemo extends Canvas
{
Image coolFace;
public ImageDemo() throws Exception
{
coolFace = ImageIO.read( new File("jesus.png") );
}
public void paint( Graphics g )
{
// Image , x, y, this
g.drawImage(coolFace,100,100,this);
g.setColor( Color.yellow );
g.drawOval(88,88,70,25);
}
public static void main(String[] args) throws Exception
{
JFrame win = new JFrame("Image Demo");
win.setSize(1024,768);
win.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
win.add( new ImageDemo() );
win.setVisible(true);
}
}
The problem is that I do not know how to get my image in the same source folder of my code in Eclipse.
I think I created one but I do not know how to put an image from my Desktop there.
Any help would be appreciated.
Generally eclipse starts jvm with current directory from base of the project so place it on base of the project to read it with existing code

unable to view the bufferedimage

I am new to swing. I was trying the game tutorial by wilchit sombat on making of packman. I cannot view the BufferedImage. Here is the code which overrides some methods from the game engine.
package game.packman;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import org.Game.Engine.Game;
import org.Game.Engine.GameApplication;
public class PackMan extends Game {
public static void main(String args[]) {
GameApplication.start(new PackMan());
}
BufferedImage packman;
public PackMan() {
title = "PACKMAN";
width = height = 400;
try {
packman = ImageIO.read(new File("images/pacmanimg.xcf"));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
#Override
public void init() {
// TODO Auto-generated method stub
}
#Override
public void update() {
// TODO Auto-generated method stub
}
#Override
public void draw(Graphics g) {
g.drawImage(packman, 100, 100, null);
}
}
Image I/O has built-in support for GIF, PNG, JPEG, BMP, and WBMP. Image I/O is also extensible so that developers or administrators can "plug-in" support for additional formats. For example, plug-ins for TIFF and JPEG 2000 are separately available.
So, it seems that XCF: native image format of the GIMP image-editing program, is not supported by ImageIO.
Reference:
Reading/Loading an Image
Check size of the image packman after loaing
packman = ImageIO.read(new File("images/pacmanimg.xcf"));
It's 0 width/height if the image is not loaded.
Anyway it's better to place the image in your classpath and use getResourceAsStream() to load it through ImageIO. In opposite case when you pack your code in a jar you need to resolve working with files and relative paths problem.

I want to use Robot class in java applet for web browser to move and click mouse

I have created this applet, It moves mouse to 1000 pos on screen. It works as application but it does not work in applet. I have created signed applet but still it wont move mouse. What should I do to make my Robot class work from browser? My code is as below:
import java.applet.Applet;
import java.awt.Graphics;
import java.awt.Robot;
import java.awt.AWTException;
public class s extends Applet {
public void paint(Graphics g) {
g.drawString("Test1", 10, 10);
}
public void init() {
try {
Robot robot = new Robot();
robot.mouseMove(1000,50);
System.out.println("code executes");
} catch (Exception ex) {
System.out.println("code failed");
};
}
}
Signing alone won't give your Applet any permissions. You need to grant the createRobot permission to your Applet.
Check the security tutorials for more details.
I've checked the source-code from Robot. And I think you have to add in the constructor a ScreenDevice.

Categories

Resources