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

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)

Related

Java 2d Game: Why is the variable not changing outside of KeyReleased?

I am attempting to create my own version of the well known game Space invaders. I am using zetcode as a point of reference (not a direct copy and paste) http://zetcode.com/tutorials/javagamestutorial/spaceinvaders/
However I seem to be a bit stuck. Namely on the use of KeyAdapters and the MVC design pattern. According to zetcode tutorial, the protected int dx changes when KeyPressed is pressed and once again when it is released, however I not seeing any movement nor value change outside of the KeyPressed and Keyreleased methods.
I carried out some simple checks
1: Does the "player" graphics move without key input at all (basically do graphic updates work)? - Yes, I changed the "move()" method within player to simply do a "x--; " and visibly see movement on screen
2: Does the value "dx" change at all? - Kinda, from Keypressed method, I can use System.out.println(""+dx); to return the value and visibly see, from within the method that dx changes, but not outside of this method, suggesting that the value changes are only occurring local to this method, which in my opinion is bizarre.
My ask from the community is the following:
Is this an issue with concurrency (or should I say, 2 references to the "dx" value stored in memory but only 1 reference is getting updated or there something else funky going on in my code that I am missing?
package spaceInvaders;
import java.awt.event.KeyEvent;
public class Player extends IngameObjects implements Commons {
private int startX = 250;
private final int startY = 150;
public Player(){
initPlayer();
}
public void initPlayer(){
this.setX(startX);
this.setY(startY);
}
public int getX() {
return x;
}
public void setX(int x) {
this.x = x;
}
public void move(){
this.x += dx;
if (x <= 2) {
x = 2;
}
if (x >= 400 - 2 * 10) {
x = 400 - 2 * 10;
}
}
public void keyPressed(KeyEvent e) {
int key = e.getKeyCode();
if(key == KeyEvent.VK_LEFT){
dx = -1;
System.out.println(""+dx);
}
if(key == KeyEvent.VK_RIGHT){}
if(key == KeyEvent.VK_ESCAPE){
System.exit(0);
}
}
public void keyReleased(KeyEvent e) {
int key = e.getKeyCode();
if(key == KeyEvent.VK_LEFT){
this.x = -1;
}
if(key == KeyEvent.VK_RIGHT){}
}
}
package spaceInvaders;
public class IngameObjects {
protected int x;
private int y;
protected int dx;
public int getY() {
return y;
}
public void setY(int y) {
this.y = y;
}
}
package spaceInvaders;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Toolkit;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import javax.swing.JPanel;
public class GamePanel extends JPanel implements Runnable{
private Player player;
private Thread animator;
private boolean isRunning;
public GamePanel(){
this.setBackground(Color.BLACK);
this.setDoubleBuffered(true);
addKeyListener(new TAdapter());
setFocusable(true);
}
public void paintComponent(Graphics g){
super.paintComponent(g);
drawPlayer(g);
Toolkit.getDefaultToolkit().sync();
g.dispose();
}
public void drawPlayer(Graphics g){
g.setColor(Color.GREEN);
g.fillRect(player.getX(), player.getY(), 50, 50);
}
#Override
public void run() {
isRunning = true;
long startTime, timeDiff, sleepTime;
startTime = System.currentTimeMillis();
while(isRunning){
repaint();
gameUpdate();
timeDiff = System.currentTimeMillis() - startTime;
sleepTime = 5 - timeDiff;
try{
Thread.sleep(sleepTime);
}
catch(InterruptedException ex){
System.exit(0);
}
startTime = System.currentTimeMillis();
}
}
#Override
public void addNotify(){
super.addNotify();
startGame();
}
public void startGame(){
player = new Player();
if(animator == null || !isRunning){
animator = new Thread(this);
animator.start();
}
}
public void gameUpdate(){
player.move();
}
private class TAdapter extends KeyAdapter{
#Override
public void keyPressed(KeyEvent e) {
System.out.println(""+player.getX());
player.keyPressed(e);
}
#Override
public void keyReleased(KeyEvent e) {
player.keyReleased(e);
}
}
}
thanks for the swift responses, much appreciated. After x amount of time (leaving it as x due to embarrassment) I have actually found a problem, quite a serious one actually.
1: Duplicated TAdapter on another class which extended the JFrame
2: 2 classes (GamePanel (which extends JPanel) and class (poorly named) Main (which extends JFrame) both have setFocusable(true);
Regarding Vince's reply, yes you are correct, as an attempt to debug my own code I actually replaced what was originally dx, for x. Obviously neither worked which led me to suspect there was a coding issue elsewhere.
Regarding MadProgrammer's reply, thanks, I am not familiar with Key bindings, I have not been programming in a very long time, which is the reason why I am making my own version of space invaders, so I can not only get back into programming but improve my knowledge, I will look at key bindings, even though you don't specify what is wrong with KeyListeners, I will study the differences. Regarding dispose, yep once again, not very familiar with the uses, i thought it was another way of refreshing the graphics, I will look into this.
in summary, where did I go wrong:
Duplicated TAdapter in a dedicated class for JFrame and another one
in JPanel
Duplicated requests for "focus" setFocusable(true);
Use KeyListener instead of key bindings (not sure why: research required)
Use of the dispose() method
Changing value of x rather than dx
This question can be considered resolved at this point, thanks

Error using method from another class

I think this might be a scope issue but it's been bugging me for a while. Whenever I try to add ReplayData to the frame I recieve a null pointer error, nor can I use my add data method without it throwing a null pointer error. p.Setx is defintely setting the right values, but once it hits "replaydata.add" an error gets thrown and the loop cannot continue.
public ReplayData replayData;
frame = new JFrame();
frame.setBounds(100, 100, 1920, 1080);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);
// ERROR HERE WHEN ADDING TO FRAME, APPLICATION RUNS FINE IF COMMENTED
//frame.add(replayData); // Add replay data to jframe
JButton button_KMeans = new JButton("View K-Means");
button_KMeans.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
kMeans.initialize();
kMeans.kMeanCluster();
kMeans.PrintResults();
//for (Point p : kMeans.getPoints() )
Point temp = new Point();
for (int i = 0; i < kMeans.TOTAL_DATA; i++)
{
//JOptionPane.showMessageDialog(new JFrame(),kMeans.TOTAL_DATA, "Dialog",
// JOptionPane.ERROR_MESSAGE);;
p.setX((int)TrackerData.getRecordNumber(i).getEyeX());
p.setY((int)TrackerData.getRecordNumber(i).getEyeY());
JOptionPane.showMessageDialog(new JFrame(),p.getX(), "Dialog",
JOptionPane.ERROR_MESSAGE);
JOptionPane.showMessageDialog(new JFrame(),p.getY(), "Dialog",
JOptionPane.ERROR_MESSAGE);
// GET ERROR HERE when adding these points to replayData. everything look fine in that class unless i'm missing something
// java.lang.NullPointerException at MainWindow$3.actionPerformed(MainWindow.java:189)
replayData.addPoint(p); // Add points to JPanel
}
//replayData.draw();
}
});
That is my button class, I get errors whenever I try to add data using my replaydata class
Heres the other 2 ReplayData + DataPoint class
import java.awt.Graphics;
import java.awt.Point;
import java.util.ArrayList;
import javax.swing.JPanel;
public class ReplayData extends JPanel {
public ArrayList<DataPoint> points;
// Initialise records
public ReplayData()
{
points = new ArrayList<DataPoint>();
}
public void ReplaceData() {
points = new ArrayList<DataPoint>();
}
public void addPoint(DataPoint point) {
points.add(point);
}
#Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
for (DataPoint p : points)
g.fillRect(p.x, p.y, 2, 2);
}
public void draw() {
repaint();
}
}
public class DataPoint{
public DataPoint(int X, int Y)
{
x = X;
y = Y;
}
public int getX() {
return x;
}
public void setX(int x) {
this.x = x;
}
public int getY() {
return y;
}
public void setY(int y) {
this.y = y;
}
int x,y;
}
Any help would be much appreciated.
Copy of my project if anyone wants to open it on eclipse (I've included the .csv you will need to get it working aswell in the zip) : http://www.filedropper.com/eyetrackeranalysis_1
You declare the variable:
public ReplayData replayData;
but never initialize it. Your line above is equivalent to this:
public ReplayData replayData = null;
You need to assign an object to the variable for it to be non-null.
public ReplayData replayData = new ReplayData();
More importantly, you need to learn the general concepts of how to debug a NPE (NullPointerException). You should critically read your exception's stacktrace to find the line of code at fault, the line that throws the exception, and then inspect that line carefully, find out which variable is null, and then trace back into your code to see why. You will run into these again and again, trust me.

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

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

Java IO can't read input file?

I have just started learning java and I've been working on this code for a moving object with keyboard input. I am now trying to add in a background, but it keeps erroring with:
javax.imageio.IIOException: Can't read input file!
at javax.imageio.ImageIO.read(Unknown Source)
at game.GameLoop.run(GameLoop.java:24)
at java.lang.Thread.run(Unknown Source)
The code I have in Game.java is:
package game;
import java.applet.*;
import java.awt.*;
public class Game extends GameLoop{
public void init(){
setSize(864,480);
Thread th = new Thread(this);
th.start();
offscreen = createImage(864,480);
d = offscreen.getGraphics();
addKeyListener(this);
}
public void paint(Graphics g){
d.clearRect(0, 0, 864, 480);
d.drawImage(background, 0, 0, this);
d.drawRect(x, y, 20, 20);
g.drawImage(offscreen, 0, 0, this);
}
public void update(Graphics g){
paint(g);
}
}
And here is my GameLoop.java:
package game;
import java.applet.*;
import java.awt.*;
import java.awt.event.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
public class GameLoop extends Applet implements Runnable, KeyListener{
public int x, y;
public Image offscreen;
public Graphics d;
public boolean up, down, left, right;
public BufferedImage background;
public void run(){
x = 100;
y = 100;
try {
background = ImageIO.read(new File("background.png"));
} catch (IOException e1) {
e1.printStackTrace();
}
while(true){
x = 100;
y = 100;
while(true){
if (left == true){
x-=4;
}
if (right == true){
x+=4;
}
if (up == true){
y-=4;
}
if (down == true){
y+=4;
}
if ( x <= 0 ){
x = 0;
}
if ( y <= 0 ){
y = 0;
}
if ( x >= 843 ){
x = 843;
}
if ( y >= 460 ){
y = 459;
}
repaint();
try{
Thread.sleep(20);
} catch(InterruptedException e){
e.printStackTrace();
}
}
}
}
//#Override
public void keyPressed(KeyEvent e) {
if(e.getKeyCode() == 37){
left = true;
}
if(e.getKeyCode() == 38){
up = true;
}
if(e.getKeyCode() == 39){
right = true;
}
if(e.getKeyCode() == 40){
down = true;
}
}
//#Override
public void keyReleased(KeyEvent e) {
if(e.getKeyCode() == 37){
left = false;
}
if(e.getKeyCode() == 38){
up = false;
}
if(e.getKeyCode() == 39){
right = false;
}
if(e.getKeyCode() == 40){
down = false;
}
}
//#Override
public void keyTyped(KeyEvent e) {
}
}
Sorry about the editing I can't seem to get it all in the ``, and I will also fix the messy code, but do you guys have any ideas what is causing this error, there is a file in the src dir called background.png, it is very basic and made in MS paint, if that helps.
Thanks.
There are two places a simple, sand-boxed applet can obtain images.
Where
A loose file on the same server the applet was supplied from. E.G. This might be used for a sand-boxed 'image slideshow' where the image names are supplied in applet parameters.
A Jar on the run-time class-path of the applet. Best for resources which would not typically change (barring localized images, where it becomes more complicated). E.G. This might be used for button/menu icons, or BG images.
"background.png" strongly indicates the 2nd scenario - 'part of the app. itself'.
How to find
Both types of resources should identified by URL (do not try to establish a File as it will fail when the applet is deployed).
The way to obtain an URL for the 2nd case is something along the lines of:
URL urlToBG = this.getClass().getResource("/path/to/the/background.png");
..where /path/to/the/ might simply be /resources/ or /images/. It is the path within a Jar on the classpath, where the image can be found.
How to load
Most methods that will load a File are overloaded to accept an URL. This notably applies to ImageIO.read(URL).
While the Applet class has inbuilt methods to load images, I recommend sticking with ImageIO since it provides more comprehensive feed-back on failure.
Further tips
Tip 1
Thread.sleep(20);
Don't block the EDT (Event Dispatch Thread) - the GUI will 'freeze' when that happens. Instead of calling Thread.sleep(n) implement a Swing Timer for repeating tasks or a SwingWorker for long running tasks. See Concurrency in Swing for more details.
Tip 2
It is the third millennium, time to start using Swing instead of AWT. That would mean extending JApplet instead of Applet. Then you might shift the logic of painting into a JPanel that is double-buffered by default, and could be used in either the applet or a frame (or a window or a dialog..).
Tip 3
setSize(864,480);
The size of an applet is set in HTML, and the applet should accept whatever size it is assigned and work within that. Taking that into account, statements like:
d.clearRect(0, 0, 864, 480);
..should read more like:
d.clearRect(0, 0, getWidth(), getHeight());
#Patricia Shanahan Your comment actually helped me to solve the same problem.
I've used that code:
File here = new File(".");
try {
System.out.println(here.getCanonicalPath());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
and from there you can figure out the correct path to use.

Compiling Java Applets

I recently started making a Java applet game for the java4k game contest but I'm new with applets and I have some questions about them.
I have an applet written in eclipse and I can run it in eclipse using applet viewer but how do I compile it? There doesn't seem a option for compiling applets..
..and what is a jar archive?
Thanks.
Also here's my source in case you need it:
import java.applet.*;
import java.awt.*;
import java.awt.event.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.*;
import javax.imageio.ImageIO;
public class game extends Applet implements KeyListener{
private static final long serialVersionUID = 1L;
public int x = 50,y = 50;
public boolean right, left, down, up, lt = false, rt = true;
public Image buffer;
BufferedImage img = null;
BufferedImage imgl = null;
Graphics bg;
public void init(){
try {
img = ImageIO.read(new File("C:/player.png"));
} catch (IOException e){}
try {
imgl = ImageIO.read(new File("C:/playerl.png"));
} catch (IOException e){}
addKeyListener(this);
setSize(400,200);
setBackground(Color.cyan);
Timer t = new Timer();
t.schedule(new TimerTask(){public void run(){
if (right == true){x++;}
if (left == true){x--;}
if (up == true){y--;}
if (down == true){y++;}
repaint();
}},10,10);
buffer = createImage(400,200);
bg = buffer.getGraphics();
}
public void paint(Graphics g){
bg.setColor(Color.WHITE);
//bg.clearRect(0, 0, 400, 200);
if (rt == true){
bg.drawImage(img,x,y, this);
}
if (lt == true){
bg.drawImage(imgl,x,y, this);
}
g.drawImage(buffer,0,0,this);
}
public void keyTyped(KeyEvent e){}
public void keyPressed(KeyEvent e){
if (e.getKeyCode() == 37){
left = true;
lt = true;
rt = false;
}
if (e.getKeyCode() == 39){
right = true;
rt = true;
lt = false;
}
if (e.getKeyCode() == 38){
up = true;
}
if (e.getKeyCode() == 40){
down = true;
}
}
public void keyReleased(KeyEvent e){
if (e.getKeyCode() == 37){
left = false;
}
if (e.getKeyCode() == 39){
right = false;
}
if (e.getKeyCode() == 38){
up = false;
}
if (e.getKeyCode() == 40){
down = false;
}
}
public void update(Graphics g){
paint(g);
}
}
You will need to export as a JAR file. To do this you will need to right-click the project > export.
Select Java > JAR file
In the JAR Export Dialog, select what parts you want to export (Export generated class files and resources) for your project. Probably want to specify the output folder as well. The rest of the options can be left as default and go to Finish.
You can run the JAR in a applet viewer or from a webpage in an APPLET tag, make sure to set the archive="jar file name".
In Eclipse, right click the project, click export, and export as a jar.
Then you can embed this jar in your webpage to be run as an applet, or externally with appletviewer.
There's no difference between a JAR and an Archive Jar. JAR stands for "Java ARchive".
You cant create self executive jar without main method.
Fortunately it's quite simple to do it.
You can create method called public static void main(String[] args) within your main class.
and then do something like this:
yourmainclassname yourname = new yourmainclassname(); //create new object
yourname.init(); //invoke the applet's init() method
yourname.start(); //starts the applet
// Create a window (JFrame) and make applet the content pane.
JFrame window = new JFrame("Put something here");
window.setSize(640, 480); //size in pixels
window.setContentPane(theApplet); //
window.setVisible(true);
window.setDefaultCloseOperation(javax.swing.JFrame.EXIT_ON_CLOSE);
That's all. Next you can just export project to self executive JAR.

Categories