Loading images so that it works in JAR-Files and NetBeans - java

I've got a problem with the jar file that's supposed to run the game i'm trying to create.
It's basicaly a major issue with the loading of Images so that it works in the Jar aswell as Netbeans' environment.
i'm currently using
imgIcon = new ImageIcon(Core.classLoader.getResource("Images/Boss1.png"));
img = imgIcon.getImage();
this works just fine 4 all my enemies the level background and the shots my various object fire. But if I try to use it on my player class the JAR file becomes unexecutablem, even thought it still works perfectly in NetBeans. So did i screw up in the Player or somewhere else because the Images seem to load with this particular code and only if it's also in the player the jar is unusable.
Player class to be seen here(I think it's got to be a problem in here that i overlooked over and over):
package Entity;
import Shots.PlayerShot;
import bullethellreloaded.Core;
import bullethellreloaded.Screen;
import java.awt.Image;
import java.awt.Rectangle;
import java.util.ArrayList;
import javax.swing.ImageIcon;
public class Player extends Entity{
public int x,y; // public used to make an easy mouse controll;
int xDirection, yDirection;
int health;
private Image img;
private ImageIcon imgIcon;
private Rectangle hitbox;
public static ArrayList shots;
public Player(){
x = 250;
y = 400;
shots = new ArrayList();
health = 5;
imgIcon = new ImageIcon(Core.classLoader.getResource("Images/spaceship (Redshrike,Stephen Challener).png"));
img = imgIcon.getImage();
}
#Override
public void move(){
x += xDirection;
y += yDirection;
// Wallcollision detection, needs to be ajusted for the size of the object.
if(x <= 0)
x = 0;
if(x >= Screen.getScreenWidth())
x = Screen.getScreenWidth();
if(y <= 0)
y = 0;
if(y >= Screen.getScreenHeight())
y = Screen.getScreenHeight();
}
public void setXDirection(int xdir){
xDirection = xdir;
}
public void setYDirection(int ydir){
yDirection = ydir;
}
#Override
public Image getImage(){
return img;
}
#Override
public ImageIcon getImageIcon(){
return imgIcon;
}
#Override
public int getX(){
return x;
}
#Override
public int getY(){
return y;
}
#Override
public Rectangle getHitbox(){
return hitbox;
}
public static ArrayList getShots(){
return shots;
}
public void fire(){
PlayerShot shot = new PlayerShot(getX(), getY()-getImageIcon().getIconHeight()/2, 0, 1, 1,Core.classLoader.getResource("Images/PlayerShot.png"));
shots.add(shot);
}
#Override
public void removeHitbox(){
hitbox = null;
}
#Override
public Rectangle setHitbox(){
int width = getImageIcon().getIconWidth();
int height = getImageIcon().getIconHeight();
hitbox = new Rectangle(getX()+width/2-5, getY()+height/2-5, 1, 1);
return hitbox;
}
public void takeDamage(int dmg){
health -= dmg;
}
public int getHealth(){
return health;
}
drawn in my screen class which is an extended JFrame in the paintComponent that's invoked by the paint(doublebuffering and stuff^^)
in the following code segment:
}else{
g.drawImage(testlevel.getImage(),0,0,this);
g.drawImage(player.getImage(),player.getX(),player.getY(),this);
// painting the Score
g.setColor(Color.white);
g.setFont(new Font("Arial",Font.BOLD,14));
g.drawString("Score: "+ Score.getScore(), getScreenWidth()-100, 50);
// painting out the content of the ArrayLists shots, enemies, enemyShots
try{
for (int i = 0; i < Player.shots.size(); i++){
PlayerShot s = (PlayerShot) Player.shots.get(i);
if (s.getDeleted() != true){
g.drawImage(s.getImage(), s.getX(), s.getY(), this);
}
}
for (int i = 0; i < Enemy.enemies.size(); i++){
Enemy e = (Enemy) Enemy.enemies.get(i);
if (e.getDestroied() != true){
g.drawImage(e.getImage(), e.getX(), e.getY(), this);
}
}
for (int i = 0; i < Enemy.enemyShots.size(); i++){
EnemyShot es = (EnemyShot) Enemy.enemyShots.get(i);
if (es.getDeleted() != true){
g.drawImage(es.getImage(), es.getX(), es.getY(), this);
}
}
}catch(Exception e){}
}
repaint();
}
I hope thats enough information, if that's not the case please let me know.
EDIT:
The question is more like is there another way that might work with my programm or what did i screw up to get this useless JAR thats not even starting.
changeing this (this path only works in netbeans the jar can't find it with this path)
imgIcon = new ImageIcon("src/Images/spaceship (Redshrike,Stephen Challener).png");
to this:
imgIcon = new ImageIcon(Core.classLoader.getResource("Images/spaceship (Redshrike,Stephen Challener).png"));
makes the JAR not runnable (not even a process in the background) whereas it worked just fine with the old path except the fact that the player didn't had an image.

You should pack the resources into the final Jar.
For Eclipse there's a plugin called FatJar that does that (in newer Eclipse versions it's embedded as the option Export>Runnable Jar File).
Usually compilers will not pack resources into the bundle.

I found it out myself, its quite the ridiculous thing.
The Image's name seems to be to long 4 the classLoader if it's used in a jar shorting down the name of the Image let's the program run ^^
AnyWays thx to the ones trying to help me and to the JAR file that reminded me of looking into the simple stuff 1.
Snake

Related

How do you solve lagging in Java awt/swing image printing?

I am trying to make a simple game with Java swing/awt.
I am have issue with lagging while printing and moving images on the screen.
Here is my code below:
import java.awt.*;
import java.awt.event.*;
import java.awt.image.*;
import java.io.File;
import java.util.ArrayList;
import javax.imageio.ImageIO;
import javax.swing.*;
public class StarDef extends JFrame implements Runnable, KeyListener{
private BufferedImage back;
private boolean start = false, end = false;
public int w = 1500, h = 800, commandx = 200, commandy = 100, ground = 500, mineral = 100;
private int mineralx = 0, mineraly = commandy + 104;
private int dronecnt = 0;
private ArrayList<Drone> DrList = null;
private ArrayList<Enemy> EnList = null;
private ArrayList<Building> BuildList = null;
private ArrayList<Allies> AlyList= null;
public Image imagearr[] = new Image[10];
private boolean makedrone = false, NeedMinerals = false;
public int picnum = 1;
private int OrderBuild = 0;
public static void main(String[] args){
Thread t = new Thread(new StarDef());
t.start();
}
public StarDef(){
back = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
DrList = new ArrayList<>();
BuildList = new ArrayList<>();
EnList = new ArrayList<>();
AlyList = new ArrayList<>();
this.addKeyListener(this);
this.setSize(w,h);
this.setTitle("Starcraft");
this.setResizable(false);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setVisible(true);
try {
imagearr[0] = ImageIO.read(new File("Char/Command.png"));
imagearr[1] = ImageIO.read(new File("Char/droneleft.png"));
imagearr[2] = ImageIO.read(new File("Char/droneright.png"));
imagearr[3] = ImageIO.read(new File("Char/Mineral.png"));
imagearr[4] = ImageIO.read(new File("Char/barracks.png"));
} catch (Exception e){
e.printStackTrace();
}
}
public void initGame(){
DrList.clear();
mineral = 100;
}
public void draw(){
Graphics gs = back.getGraphics();
gs.setColor(Color.white);
gs.fillRect(0,0,w,h);
gs.setColor(Color.DARK_GRAY);
gs.fillRect(0,ground,w,200);
if (!end) {
gs.drawImage(imagearr[0], commandx, commandy, null); // First Image-Command Center
gs.drawImage(imagearr[3], mineralx,mineraly,null); // Second Image-Mineral
for (int i = 0; i < DrList.size(); i++) { //Printing Drones
Drone m = DrList.get(i);
gs.drawImage(imagearr[m.state], m.x, m.y, null); //Drawing Drones
m.moveDr(); // Moving the Drone
}
for (int i = 0; i < BuildList.size(); i++){ //Printing Building
Building bd = BuildList.get(i);
if(bd.buildingtype == 'R'){
gs.drawImage(imagearr[4], bd.x, bd.y, null); // Drawing Building-Problem starts..?
}
}
gs.drawImage(imagearr[0], commandx, commandy, null);
}
gs.setColor(Color.black);
gs.drawString("mineral : " + mineral, 10,50);
gs.drawString("Drones : " + DrList.size(), 10, 70);
Graphics ge = this.getGraphics();
ge.drawImage(back, 0,0,w,h,this);
}
public void run(){
try{
int timer = 10;
while (true){
Thread.sleep(timer);
if(start){
if (makedrone) {
makedrone();
}
if (OrderBuild>0){
makeBuilding(OrderBuild);
}
}
draw();
}
} catch (Exception e){
e.printStackTrace();
}
}
public void makeBuilding(int buildingnumber){
int bdx, bdy;
char BuildingType;
if(buildingnumber == 1){
bdx = 500;
bdy = 100;
BuildingType = 'R';
Building barracks = new Building(this, bdx, bdy, BuildingType);
BuildList.add(barracks);
}
}
public void makedrone() {
if (mineral >= 50) {
int dronex = commandx;
int droney = commandy+129;
Drone dr = new Drone(this ,dronex, droney);
DrList.add(dr);
dronecnt++;
mineral -= 50;
makedrone = false;
} else if (mineral < 50) {
NeedMinerals = true;
makedrone = false;
}
}
public void keyPressed(KeyEvent ke){
switch (ke.getKeyCode()){
case KeyEvent.VK_ENTER:
start = true;
end = false;
break;
case KeyEvent.VK_D:
makedrone = true;
break;
case KeyEvent.VK_R:
OrderBuild = 1;
break;
}
}
public void keyReleased(KeyEvent ke){
switch ((ke.getKeyCode())){
}
}
public void keyTyped(KeyEvent ke) {
}
}
When you compile the code, the first few stationary images appear fine.
After moving images(Drones) appear nicely, but when you summon the next stationary image(Building), heavy lag starts to appear and the speed of the moving drones decrease visibly.
The building is about 300*150 pixels and the drones are 40*30 pixels.
What is the cause of this problem? Is this because of the code(the way of summoning the image), or the picture's size, or the computer(I am using a notebook(LG Gram 14in)).?
Start by not using Graphics ge = this.getGraphics();.
Because you're also using your own Thread, you're running the risk of thread race conditions which could result in dirty reads/ paints.
Start by understanding how Swing painting actually works and work within the API functionality.
Start by having a look at Performing Custom Painting, Painting in AWT and Swing and Concurrency in Swing
KeyListener is also a poor choice for monitor key input and you should be using the Key Bindings API - see How to use key bindings for more details.
Adding content to the ArrayList can cause the ArrayList to go through a growth cycle, which can consume time and force a longer GC cycle. Consider seeding the ArrayList with initial capacity, it will help reduce the interval between growth cycles.
Focus on separating the "update" logic from the "paint" logic, it can help you find performance issues
You could also have a look at
java what is heavier: Canvas or paintComponent()?
Swing animation running extremely slow
Rotating multiple images causing flickering. Java Graphics2D
Which demonstrate a verity of techniques for improving performance of rendering in Swing.
If these still are't getting your to the level you want, then you will want to explore using a BufferStrategy
Better draw in JPanel and use repaint() method to update your JPanel

Problems with Graphics in MVC structure

I testing to implement graphics into MVC structure but Im a bit stuck. Here is what I got so far. For now I just want to get the red ball to bounce back and forth. And use the button start to start the thread and button stop to stop the thread that runs the GameLoop in the controller.
But I think Im mixing this up a bit. Would very much appreciate some feedback!
Heres what I got so far:
GameModell
suppose to controll the bouncing. If the location of the ball is under 40 px or above 80 px - multiply the locationX with -1 to make the ball change direction
GameView
Here Im putting the labels on a JFrame. I also want to display the buttons start and stop to controll the thread but I guess they are hidden by the JPanel in TheGraphics class
GameController
Starts and stops the thread with ActionListeners. Contains the GameLoop
TheGraphics
Paints the ball and controll the direction
I guess I got a lot of thing that are all wrong but this is the best I can do at the moment. Would very much apreciate some help!
Thanks!
MAIN:
public class MVCgame {
public static void main(String[] args) {
GameModel gm = new GameModel();
GameView gv = new GameView();
GameController gc = new GameController(gm, gv);
}
}
MODEL:
public class GameModel {
private int multi = 1;
public void setMulti(int locX) {
if(locX < 40 || locX > 80) {
multi = multi * -1;
}
}
public int multi() {
return multi;
}
}
VIEW:
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class GameView extends JFrame {
private JPanel jp = new JPanel();
private JButton start = new JButton("Start");
private JButton stop = new JButton("Stop");
TheGraphics gr = new TheGraphics();
public GameView() {
add(jp);
add(gr);
jp.add(start);
jp.add(stop);
setSize(250, 250);
setVisible(true);
}
public void addListener(ActionListener theListener) {
start.addActionListener(theListener);
stop.addActionListener(theListener);
}
public JButton getStart() {
return start;
}
public JButton getStop() {
return stop;
}
// GUESS I SHOULD PUT THIS IN THE VIEW???
public void paintEllipse(Graphics theG) {
Graphics2D g2d = (Graphics2D) theG;
g2d.setColor(new Color(255, 0, 0));
g2d.fillOval(0, 0, 10, 10);
}
}
CONTROLLER:
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class GameController implements Runnable {
GameView gv;
GameModel gm;
private Thread thread;
private boolean running = false;
public GameController(GameModel gm, GameView gv) {
this.gv = gv;
this.gm = gm;
gv.addListener(theListener);
start();
}
ActionListener theListener = new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (e.getSource() == gv.getStart()) {
start();
System.out.println("PLAY = ");
} else if (e.getSource() == gv.getStop()) {
stop();
System.out.println("STOP = ");
}
}
};
public synchronized void start() {
thread = new Thread(this);
thread.start();
running = true;
}
public synchronized void stop() {
thread.interrupt();
running = false;
}
// GameLoop
public void run() {
long lastTime = System.nanoTime();
double amountOfTicks = 60.0;
double ns = 1000000000 / amountOfTicks;
double delta = 0;
long timer = System.currentTimeMillis();
int frames = 0;
while (running) {
long now = System.nanoTime();
delta += (now - lastTime) / ns;
lastTime = now;
while (delta >= 10) {
// tick();
delta--;
// repainting the graphics
gv.gr.drawer();
gm.setMulti(gv.gr.drawer());
System.out.println("gv.gr.drawer() = " + gv.gr.drawer() + " gm.multi() " + gm.multi());
// I want to use this value in the model to change the direction
}
if (running) {
}
frames++;
if (System.currentTimeMillis() - timer > 1000) {
timer += 1000;
System.out.println("FPS: " + frames);
frames = 0;
}
}
}
}
THE GRAPHICS:
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import javax.swing.JPanel;
public class TheGraphics extends JPanel {
private int locX = 40;
public TheGraphics() {
}
public int drawer() {
locX++;
repaint();
return locX;
}
#Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g;
g2d.setColor(new Color(255, 0, 0));
g2d.fillOval(locX, 30, 10, 10);
}
}
GameModell suppose to controll the bouncing. If the location of the ball is under 40 px or above 80 px - multiply the locationX with -1 to make the ball change direction
public void setMulti(int locX) {
if(locX < 40 || locX > 80) {
multi = multi * -1;
}
}
Really bad idea. You should always check position and direction (sign(speed)). Otherwise, your object might get stuck out of bounds always changing direction without moving from place forever.
Apart from this, using the MVC concept is overkill in my eyes and shouldn't be used in such a small project nor in a game. In a game, you should more or less put all three together. Of course you can, but the advantages and disadvantages of the MVC concept don't fit the needs of a game in many ways (except for the GUI, perhaps).
Your main loop might look something like this (you kind of did this already, but why is the tick() commented out in your code?):
while (running) {
update(); // Update all game objects
paint(); // Paint them all
}
Each game object will have its own update() and paint() implementation. You absolutely need to separate the logic of update and paint, even if they are in the same class. So this one:
public int drawer() {
locX++;
repaint();
return locX;
}
is an absolute no-go.
Edit: (Referring your update answer)
You are using the method location() for different purposes. According to the Java name convention, you should rename it getLocation() and setLocation() depending on the use to clarify the code.
(Even if this is not really MVC anymore, I'd let GameFrame implement ActionListener instead of specifying it as variable of GameController.)
One thing you should really change is this one:
private int locX = 0;
public void location(int loc) {
this.locX = (int) loc;
}
Basically, you are duplicating the location value every frame and create unused redundant data. Another problem is, that this might work fine for only one variable, but what if you add more than the position to your model later on? Instead TheGraphics has to render on an instance of the data model, not its values. As long you are using one GameModel
private GameModel model; // set value once at initialisation
and rendering its values in paintComponent will work fine, but if you want to add more than one GameModel (handling GameModel more like a GameObjectModel), you will need to pass it as parameter in the paint method.
public void update() {
repaint();
}
Remove it and try getting around without. A method called from one place forwarding to a different method is a bad idea most of the time, especially if it obfuscates the functionality with a different name.
gv.gr.update();
gv.gr.location(gm.location());
You are first repainting your image and then setting the location? Basically, your game runs one frame behind all the time. Swap that order.
gv.gr.location(gm.location());
gv.gr.repaint();
Will be fine (I already said about location()).

Illegal Argument Exception- name

I have searched for the past few days for a solution to this problem and I am beating my head against the wall. I'm knew to programming in java so bear with me.
I am currently trying to implement a Java Applet into an HTML page of mine for a school project. The Applet runs fine in Eclipse using AppletViewer, as well as in the web browser in a program called Blue Jay. I have exported the program into a jar file in the same directory as my HTML page, and added the necessary code to my HTML file, but whenever I actually run the HTML file the Applet gives me an "Illegal Argument Exception: name" error. The details of the error include the phrase "java.net.MalformedURLException:unknown protocol:e."
This is the relevant code for my HTML file:
<applet code="MovingBoxes.class" archive="E:\WebSystems\WebPages\Animations.jar"
width="350" height="350" >Animation of moving boxes</applet>
When the error occurs the phrase inside of the applet tags is not displayed either if that is significant. I have tried exporting other applets to see if they work and have received the same error every time. I'm also fairly certain that the destination for the file is correct, because when I change the destination name to something incorrect a "Class Not Found" error occurs instead.
And in the off chance that the error is in my applet, here is my applet code.
package theBig;
import java.awt.*;
public class MovingBoxes extends java.applet.Applet implements Runnable
{
Thread runner;
int size = 15;
int x_value = 200;
int y_value = 175;
int rndm_x;
int rndm_y;
int move = 1;
int cntr = 0;
Image dbImage;
Graphics dbg;
int x_value2 = 240;
int y_value2 = 250;
int rndm_x2;
int rndm_y2;
public void start()
{
if (runner == null) {
runner = new Thread(this);
runner.start();
}
}
public void stop()
{
if (runner != null) {
runner.stop();
runner = null;
}
}
public void run()
{
setBackground(Color.white);
while (true) {
rndm_x = (int)(Math.random()*10+1);
rndm_y = (int)(Math.random()*10+1);
if (rndm_x > 5)
x_value += move;
else
x_value -= move;
if (rndm_y > 5)
y_value = 50;
else
y_value = 50;
rndm_x2 = (int)(Math.random()*10+1);
rndm_y2 = (int)(Math.random()*10+1);
if (rndm_x2 > 5)
x_value2 += move;
else
x_value2 -= move;
if (rndm_y2 > 5)
y_value2 = 50;
else
y_value2 = 50;
if (x_value + size > x_value2)
{
cntr = 50;
}
while(cntr > 0)
{
cntr --;
x_value --;
x_value2 ++;
repaint();
try { Thread.sleep(25); }
catch (InterruptedException e) { }
}
repaint();
try { Thread.sleep(25); }
catch (InterruptedException e) { }
}
}
public void update(Graphics g) {
dbImage = createImage(getWidth(),getHeight());
dbg = dbImage.getGraphics();
paint(dbg);
g.drawImage(dbImage,0,0,this);
}
public void paint(Graphics g) {
g.setColor(Color.red);
g.drawRect(x_value, y_value, size, size);
g.fillRect(x_value, y_value, size, size);
g.setColor(Color.blue);
g.drawRect(x_value2, y_value2, size, size);
g.fillRect(x_value2, y_value2, size, size);
}
} `
Like I said, I have searched everywhere for an answer and come up empty handed. Any help you can offer me is greatly appreciated.
Maybe its a typo but you are missing a " after .jar in your HTML code.
If that doesn't help, maybe your archive should be a URL, not just a file path. Can you try this:
<applet code="MovingBoxes.class" archive="file:/E:/WebSystems/WebPages/Animations.jar"
width="350" height="350" >Animation of moving boxes</applet>

java.lang.NullPointerException Issue When Attempting to Run Program [duplicate]

This question already has answers here:
Class.getResource() returns null
(2 answers)
Closed 8 years ago.
This is my first question, I hope it's not too poorly made.
I'm definitely beginner level at java, probably lower. I'm taking most of my code from a tutorial in fact, hoping I'll learn what all the things do soon enough.
Anyway, so far, I have 3 .java files in my program, and it shows the exception to be at all 3 of them, plus one I never made.
Here's the full error:
Exception in thread "main" java.lang.NullPointerException
at javax.swing.ImageIcon.<init>(ImageIcon.java:205)
at Emilia.<init>(Emilia.java:17)
at Board.<init>(Board.java:26)
at TestGame.<init>(TestGame.java:7)
at TestGame.main(TestGame.java:18)
Here's all the code:
TestGame.java
import javax.swing.JFrame;
public class TestGame extends JFrame {
public TestGame() {
add(new Board());
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(400, 300);
setLocationRelativeTo(null);
setTitle("Project Obcasus");
setResizable(false);
setVisible(true);
}
public static void main(String[] args) {
new TestGame();
}
}
Board.java
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Board extends JPanel implements ActionListener {
private Timer timer;
private Emilia emilia;
public Board() {
addKeyListener(new TAdapter());
setFocusable(true);
setBackground(Color.BLACK);
setDoubleBuffered(true);
emilia = new Emilia();
timer = new Timer(5, this);
timer.start();
}
public void paint(Graphics g) {
super.paint(g);
Graphics2D g2d = (Graphics2D)g;
g2d.drawImage(emilia.getImage(), emilia.getX(), emilia.getY(), this);
Toolkit.getDefaultToolkit().sync();
g.dispose();
}
public void actionPerformed(ActionEvent e) {
emilia.move();
repaint();
}
private class TAdapter extends KeyAdapter {
public void keyReleased(KeyEvent e) {
emilia.keyReleased(e);
}
public void keyPressed(KeyEvent e) {
emilia.keyPressed(e);
}
}
}
Emilia.java
import java.awt.Image;
import java.awt.event.KeyEvent;
import javax.swing.ImageIcon;
public class Emilia {
private String emilia = "emiliasprite.png";
private int dx;
private int dy;
private int x;
private int y;
private Image image;
public Emilia() {
ImageIcon ii = new ImageIcon(this.getClass().getResource(emilia));
image = ii.getImage();
x = 40;
y = 60;
}
public void move() {
x += dx;
y += dy;
}
public int getX() {
return x;
}
public int getY() {
return y;
}
public Image getImage() {
return image;
}
public void keyPressed(KeyEvent e) {
int key = e.getKeyCode();
if (key == KeyEvent.VK_A) {
dx = -1;
}
if (key == KeyEvent.VK_D) {
dx = 1;
}
if (key == KeyEvent.VK_W) {
dy = -1;
}
}
public void keyReleased(KeyEvent e) {
int key = e.getKeyCode();
if (key == KeyEvent.VK_A) {
dx = 0;
}
if (key == KeyEvent.VK_D) {
dx = 0;
}
if (key == KeyEvent.VK_W) {
dy = 0;
}
}
}
ImageIcon.java - Line 205
this(location, location.toExternalForm());
Again, I'm beginner level so if you guys could explain it as you would to a newcomer to java (or any programming language for that matter)
Thanks for any help. - Niblexis
path of .png file:
C:\Users\Damon\workspace\TestGame\Resources\Sprites\Player
The .png file is in the player folder. I tried to run the program via the run button in Eclipse. At least, I think it's the run button because it's what showed me the errors in the first place.
Looks like the problem is in this line:
ImageIcon ii = new ImageIcon(this.getClass().getResource(emilia));
which means most likely that you haven't placed your .png file in the right place for Java to find it.
Could you post the exact path of the .png file on disk?
More specifically: a null pointer in this line of ImageIcon.java:
this(location, location.toExternalForm());
would imply that the URL location is null (causing an exception in the method call .toExternalForm(). If you look at the docs for Class.getResource() you will see it says:
Returns: A URL object or null if no resource with this name is found
which implies that Java can't find the resource in question.
For us to help, you will need to describe your runtime environment (are you running your program from .class files or in a .jar? at the command-line or in a debugger in Eclipse / Netbeans?) so we can help you figure out why the resource isn't being found.
You're effectively calling Emilia.class.getResource("emiliasprite.png") with Emilia.java in the default (root) package, which means that you need to tell your IDE / build process to copy this file into the root of the classpath. (in the same directory that Emilia.class ends up) Otherwise, Java has no idea where to find it.
If you want to place the resource somewhere else, you need to change the path accordingly, as well as the mechanism that copies the resource from the source directory to the appropriate place on the classpath.
See this stackoverflow answer: Java in Eclipse: Where do I put files on the filesystem that I want to load using getResource? (e.g. images for an ImageIcon)

Coin flip program

I tried making a program that flips a coin(shows image of heads first and later shows image of tails) and I encountered problems trying to have the image of the coin viewed when I ran the problem; only a blank screen would show. I don't know whether this is from an improper saving method of the jpg images or from an error in the code. I also came across an error before again coding the program where I had the heads image show and tails image not show.
CoinTest.java runs coin runner and Coin.java is the class for the program.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class CoinTest extends JPanel
implements ActionListener
{
private Coin coin;
public CoinTest ()
{
Image heads = (new ImageIcon("quarter-coin-head.jpg")).getImage();
Image tails = (new ImageIcon("Indiana-quarter.jpg")).getImage();
coin = new Coin(heads, tails);
Timer clock = new Timer(2000, this);
clock.start();
}
public void paintComponent(Graphics g)
{
super.paintComponent(g);
int x = getWidth() / 2;
int y = getHeight() / 2;
coin.draw(g, x, y);
}
public void actionPerformed(ActionEvent e)
{
coin.flip();
repaint();
}
public static void main(String[] args)
{
JFrame w = new JFrame("Flipping coin");
w.setSize(300, 300);
w.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
CoinTest panel = new CoinTest();
panel.setBackground(Color.WHITE);
Container c = w.getContentPane();
c.add(panel);
w.setVisible(true);
}
}
Now the actual Coin class.
import java.awt.Image;
import java.awt.Graphics;
public class Coin
{
private Image heads;
private Image tails;
private int side = 1;
public Coin(Image h, Image t)
{
heads = h;
tails = t;
}
//flips the coin
public void flip()
{
if (side == 1)
side = 0;
else
side = 1;
}
//draws the appropriate side of the coin - centered in the JFrame
public void draw(Graphics g, int x, int y)
{
if (side == 1)
g.drawImage(heads, heads.getWidth(null)/3, heads.getHeight(null)/3, null);
else
g.drawImage(heads, tails.getWidth(null)/3, tails.getHeight(null)/3, null);
}
}
Firstly, ensure that both images are in the correct location to load.
Secondly, you have a typo here:
if (side == 1)
g.drawImage(heads, heads.getWidth(null)/3, heads.getHeight(null)/3, null);
else
g.drawImage(heads, tails.getWidth(null)/3, tails.getHeight(null)/3, null);
^^^^
should be tails...
The width and height of the applet are coded in the tag. The code that draws the applet uses the two methods to get these values at run time. So now, different tags can ask for the same applet to paint different sized rectangles. The source code does not need to be recompiled for different sizes.

Categories