How do you work with packages? [closed] - java

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
Okay, I'm just a greenhorn here and I'm trying some various codes. Now this game GUI src I found have some image files inside a folder and its a necessity for the whole game to work.
I tried some methods, but I just can't understand how can I make the src connected to the folder. The program runs now but it only displays black screen because it can't connect to the images. Please, I need help.
What I just wanted is how can I make the program recognize the files I'm using as background images and such. The code line is there, but it displays an exception...
Am I still unclear? ._.
Well it goes like this:
package moon_lander;
import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.Point;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.net.URL;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.imageio.ImageIO;
/**
* Actual game.
*
* #author www.gametutorial.net
*/
public class Game {
/**
* The space rocket with which player will have to land.
*/
private PlayerRocket playerRocket;
/**
* Landing area on which rocket will have to land.
*/
private LandingArea landingArea;
/**
* Game background image.
*/
private BufferedImage backgroundImg;
/**
* Red border of the frame. It is used when player crash the rocket.
*/
private BufferedImage redBorderImg;
public Game()
{
Framework.gameState = Framework.GameState.GAME_CONTENT_LOADING;
Thread threadForInitGame = new Thread() {
#Override
public void run(){
// Sets variables and objects for the game.
Initialize();
// Load game files (images, sounds, ...)
LoadContent();
Framework.gameState = Framework.GameState.PLAYING;
}
};
threadForInitGame.start();
}
/**
* Set variables and objects for the game.
*/
private void Initialize()
{
playerRocket = new PlayerRocket();
landingArea = new LandingArea();
}
/**
* Load game files - images, sounds, ...
*/
private void LoadContent()
{
try
{
URL backgroundImgUrl = this.getClass().getResource("/moon_lander/resources/images/background.jpg");
backgroundImg = ImageIO.read(backgroundImgUrl);
URL redBorderImgUrl = this.getClass().getResource("/moon_lander/resources/images/red_border.png");
redBorderImg = ImageIO.read(redBorderImgUrl);
}
catch (IOException ex) {
Logger.getLogger(Game.class.getName()).log(Level.SEVERE, null, ex);
}
}
/**
* Restart game - reset some variables.
*/
public void RestartGame()
{
playerRocket.ResetPlayer();
}
/**
* Update game logic.
*
* #param gameTime gameTime of the game.
* #param mousePosition current mouse position.
*/
public void UpdateGame(long gameTime, Point mousePosition)
{
// Move the rocket
playerRocket.Update();
// Checks where the player rocket is. Is it still in the space or is it landed or crashed?
// First we check bottom y coordinate of the rocket if is it near the landing area.
if(playerRocket.y + playerRocket.rocketImgHeight - 10 > landingArea.y)
{
// Here we check if the rocket is over landing area.
if((playerRocket.x > landingArea.x) && (playerRocket.x < landingArea.x + landingArea.landingAreaImgWidth - playerRocket.rocketImgWidth))
{
// Here we check if the rocket speed isn't too high.
if(playerRocket.speedY <= playerRocket.topLandingSpeed)
playerRocket.landed = true;
else
playerRocket.crashed = true;
}
else
playerRocket.crashed = true;
Framework.gameState = Framework.GameState.GAMEOVER;
}
}
/**
* Draw the game to the screen.
*
* #param g2d Graphics2D
* #param mousePosition current mouse position.
*/
public void Draw(Graphics2D g2d, Point mousePosition)
{
g2d.drawImage(backgroundImg, 0, 0, Framework.frameWidth, Framework.frameHeight, null);
landingArea.Draw(g2d);
playerRocket.Draw(g2d);
}
/**
* Draw the game over screen.
*
* #param g2d Graphics2D
* #param mousePosition Current mouse position.
* #param gameTime Game time in nanoseconds.
*/
public void DrawGameOver(Graphics2D g2d, Point mousePosition, long gameTime)
{
Draw(g2d, mousePosition);
g2d.drawString("Press space or enter to restart.", Framework.frameWidth / 2 - 100, Framework.frameHeight / 3 + 70);
if(playerRocket.landed)
{
g2d.drawString("You have successfully landed!", Framework.frameWidth / 2 - 100, Framework.frameHeight / 3);
g2d.drawString("You have landed in " + gameTime / Framework.secInNanosec + " seconds.", Framework.frameWidth / 2 - 100, Framework.frameHeight / 3 + 20);
}
else
{
g2d.setColor(Color.red);
g2d.drawString("You have crashed the rocket!", Framework.frameWidth / 2 - 95, Framework.frameHeight / 3);
g2d.drawImage(redBorderImg, 0, 0, Framework.frameWidth, Framework.frameHeight, null);
}
}
}
And this is the Exception:
Exception in thread "Thread-2" java.lang.IllegalArgumentException: input == null!
at javax.imageio.ImageIO.read(ImageIO.java:1362)
at moon_lander.Framework.LoadContent(Framework.java:115)
at moon_lander.Framework.GameLoop(Framework.java:162)
at moon_lander.Framework.access$000(Framework.java:21)
at moon_lander.Framework$1.run(Framework.java:90)
Process completed.

How you load imagines doesn't have anything to do with packages.
Normally you find an image as a resource via class path. This can be arranged any way you wish.
I tried some methods, but I just can't understand how can I make the src connected to the folder.
Usually you build an application. When you run it, you use the build, not the src. i.e. you don't use the source when you run the program. Usually the images are copied with the same relative path you used in your source and this relative path is what you use to find and load your images.
I can't be more specific, as there is not enough detail in the questions such as what you directory structure is and which IDE or build system you are using.

Related

Initialize an Image

I'm trying to make top and bottom walls for my Pong game. I think I have everything right but it will not run because it says "The local variable wall may not have been initialized". How do I initialize an Image?
import java.awt.Graphics;
import java.awt.Image;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
public class Wall extends Block
{
/**
* Constructs a Wall with position and dimensions
* #param x the x position
* #param y the y position
* #param wdt the width
* #param hgt the height
*/
public Wall(int x, int y, int wdt, int hgt)
{super(x, y, wdt, hgt);}
/**
* Draws the wall
* #param window the graphics object
*/
public void draw(Graphics window)
{
Image wall;
try
{wall = ImageIO.read(new File("C:/eclipse/projects/Pong/wall.png"));}
catch (IOException e)
{e.printStackTrace();}
window.drawImage(wall, getX(), getY(), getWidth(), getHeight(), null);
}
}
Thanks to everyone who answered I've figured it out. I didn't realize I just needed to set wall = null.
Your image is indeed initialised with the statement
wall = ImageIO.read(new File("C:/eclipse/projects/Pong/wall.png"));
However, the compiler is complaining because that statement could possibly fail, as it is in a try/catch block. A possible way to just "satisfy" the compiler is to set the Image variable to null:
Image wall = null;
You are initializing the Image correctly. The reason Java is complaining is you have it in a try block. Try blocks are not guaranteed to run and you don't compensate for the possibility of the code failing in the catch block, so it you (and more importantly, Java) can't be sure that wall will exist when you call window.drawImage(). A possible fix would be (cutting out the imports but with a bit of code for reference):
public class Wall extends Block
{
/**
* Constructs a Wall with position and dimensions
* #param x the x position
* #param y the y position
* #param wdt the width
* #param hgt the height
*/
public Wall(int x, int y, int wdt, int hgt)
{super(x, y, wdt, hgt);}
/**
* Draws the wall
* #param window the graphics object
*/
public void draw(Graphics window)
{
Image wall;
try
{wall = ImageIO.read(new File("C:/eclipse/projects/Pong/wall.png"));}
catch (IOException e)
{
e.printStackTrace();
wall = new BufferedWindow(getWidth(), getHeight(), <Correct Image Type>);
}
window.drawImage(wall, getX(), getY(), getWidth(), getHeight(), null);
}
}
Always initialization of the variable declared to class is important
Image wall = null;

Moving a Pacman

This is a program I wrote for creating a pacman. I now want the Pacman to move in a straight line from a random start point to a random goal point.
Could you please suggest how to do it.
import javax.swing.JFrame;
/**
* Main class for pacman example. All it does is create a frame and put
* the pacman panel in it.
*/
public class PacmanGUI extends JFrame{
private Pacman pc;
public PacmanGUI(){
super("Pacman");
pc = new Pacman();
this.getContentPane().add(pc);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.pack();
this.setVisible(true);
}
public static void main(String[] args) {
new PacmanGUI();
}
}
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
/**
* Pacman class that extends JPanel and paints a pacman animation.
* It uses Timers and Actionlistener to do the Animation.
*
*/
public class Pacman extends JPanel implements ActionListener{
private int figureSize = 50;
private static final int DELAY = 200;
private double mouthOpenPercentages[] = {.1,.5};
private Timer animationTimer;
private int mouthState = 0;
private Point pacManPosition;
/**
* No args constructor that starts the animation.
*/
public Pacman(){
startAnimation();
}
/**
* Overriden paintComponent method that paints pacman.
*/
public void paintComponent(Graphics g) {
super.paintComponent(g);
pacManPosition = new Point(this.getWidth()/2 - figureSize/2,
this.getHeight()/2 - figureSize/2);
g.fillRect(0,0,this.getWidth(), this.getHeight());
drawPacMan(g);
mouthState = (++mouthState) % mouthOpenPercentages.length;
}
/**
* Stops the animation by stopping the animation timer.
*/
public void stopAnimation(){ animationTimer.stop(); }
/**
* Method do deal with actionevents that are triggered. In this
* case we only have actionevents being triggered from our timer
* and by the more usual case of a button click.
*/
public void actionPerformed(ActionEvent e){ repaint(); }
/**
* Gets the size that this component would like to be.
*/
public Dimension getPreferredSize(){ return new Dimension(400,400); }
/**
* Gets the minimum size for this component.
*/
public Dimension getMinimumSize(){ return new Dimension(200,200); }
/**
* Starts the animation by setting a timer. When this timer goes
* off the actionPerformed method will be triggered, which in
* turn triggers the painting.
*/
private void startAnimation(){
if (animationTimer == null){
mouthState = 0;
animationTimer = new Timer(DELAY, this);
animationTimer.start();
} else { //continue animating..
if (!animationTimer.isRunning())
animationTimer.restart();
}
}
/**
* Draws our little pacman on the given graphics canvas.
* #param g
*/
private void drawPacMan(Graphics g){
Color c = g.getColor();
g.setColor(Color.yellow);
g.fillOval(pacManPosition.x, pacManPosition.y, figureSize, figureSize);
//Change color back to original and draw pacman's mouth
g.setColor(c);
//calculate mouth offsets
int yOffset = (int)((figureSize/2)*mouthOpenPercentages[mouthState]);
//draw the mouth cutout.
int x[] = {pacManPosition.x + figureSize/2, pacManPosition.x + figureSize, pacManPosition.x + figureSize};
int y[] = {pacManPosition.y + figureSize/2,
pacManPosition.y + figureSize/2 + yOffset,
pacManPosition.y + figureSize/2 - yOffset};
g.fillPolygon(x, y, x.length);
}
}
Inside the Pacman class you would need to create 2 more values to store the start and end points. You already have private Point pacManPosition; declared so I would also declare these as Points. You'll want to set pacManPosition initially to the start point.
Point start = // random start point
Point end = // random end point
Point pacManPoint = new Point(start);
Now you'll want to determine the speed you want your Pacman to move at, let's say 2 pixels per frame.
int speed = 2;
To determine how much to move the Pacman each frame, we'll need to do some calculations. First, get the distance of the line -
double distance = Math.sqrt(Math.pow(end.x - start.x, 2) +
Math.pow(end.y - start.y, 2));
Then we calculate how many frames it will take to go that distance at the speed we want.
int totalFrames= (int)Math.round(distance / speed);
And add a frame counter -
int frame = 0;
Now, look inside your paintComponent method. Right now you're setting pacManPosition to the same point (the center of the panel) each time it paints. What you want to do here instead is to update pacManPosition each frame until it gets to the end position. You're doing something similar lower in paintComponent where you're updating mouthState each time to get the mouth to animate. For animating position it will look like -
if (frame < totalFrames) {
pacManPosition.x = start.x + frame * (end.x - start.x) / totalFrames;
pacManPosition.y = start.y + frame * (end.y - start.y) / totalFrames;
frame++;
}
This is only one way to do movement animation, and it assumes several things - constant speed, no need to avoid obstacles, no player control. The calculation in totalFrames isn't exact - it moves pacMan close to the end point, but there's no guarantee it will end exactly there. It is also tied to the frame rate, which has drawbacks. There are many, many other ways to do this depending on the situation.
Problem
You have to manage two animations at the same time.
The first, which you've already coded, opens and closes the Pacman's mouth.
The second animation is responsible for moving the Pacman from one location to another.
Solution - Sprite class
I suggest you create a Sprite class. The Sprite class would be responsible for holding the current position of the sprite, the next position of the sprite, and the speed at which the sprite moves.
You would extend Sprite to get one Pacman class, and a Chaser class with 4 instances.
Pacman class
The Pacman class would be responsible for the mouth animation.
Chaser class
The Chaser class would be responsible for determining whether to chase the Pacman, or run away from the Pacman.
Swing Tips
You should not extend Java Swing components, unless you are overriding one or more of the component classes. You should use Swing components.
You should always start your Swing GUI on the Event Dispatch Thread (EDT). You do this by executing the invokeLater method of SwingUtilities.
You should have a GUI model, separate from your GUI components. The three classes I defined would be part of your GUI model. You also need to lay out a maze.

Programmatically determine if 2 images look the same using Java [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 5 years ago.
Improve this question
In JAVA I am trying to programmatically tell if 2 images are equal when displayed on the screen (AKA same image even though they have different color spaces. Is there a piece of code that will return a boolean when presented 2 images?
One of the examples I have is a RGB PNG that I converted to a greyscale PNG. Both images look the same and I would like to prove this programmatically. Another example is two images where they display the exact same color pixels to the screen but the color used for 100% transparent pixels has changed.
I looked at all of the solutions and determined that they could tell you how different the images were or worked for some types of images, but not all of them. Here is the solution I came up with...
package image.utils;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.Toolkit;
import java.awt.color.ColorSpace;
import java.awt.image.BufferedImage;
import java.awt.image.ColorConvertOp;
import java.awt.image.PixelGrabber;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.imageio.ImageReader;
import javax.imageio.stream.ImageInputStream;
import javax.swing.ImageIcon;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Utility methods used to interact with images.
*/
public class ImageUtils {
private final static Logger logger = LoggerFactory.getLogger(ImageUtils.class);
private static final boolean equals(final int[] data1, final int[] data2) {
final int length = data1.length;
if (length != data2.length) {
logger.debug("File lengths are different.");
return false;
}
for(int i = 0; i < length; i++) {
if(data1[i] != data2[i]) {
//If the alpha is 0 for both that means that the pixels are 100%
//transparent and the color does not matter. Return false if
//only 1 is 100% transparent.
if((((data1[i] >> 24) & 0xff) == 0) && (((data2[i] >> 24) & 0xff) == 0)) {
logger.debug("Both pixles at spot {} are different but 100% transparent.", Integer.valueOf(i));
} else {
logger.debug("The pixel {} is different.", Integer.valueOf(i));
return false;
}
}
}
logger.debug("Both groups of pixels are the same.");
return true;
}
private static final int[] getPixels(final BufferedImage img, final File file) {
final int width = img.getWidth();
final int height = img.getHeight();
int[] pixelData = new int[width * height];
final Image pixelImg;
if (img.getColorModel().getColorSpace() == ColorSpace.getInstance(ColorSpace.CS_sRGB)) {
pixelImg = img;
} else {
pixelImg = new ColorConvertOp(ColorSpace.getInstance(ColorSpace.CS_sRGB), null).filter(img, null);
}
final PixelGrabber pg = new PixelGrabber(pixelImg, 0, 0, width, height, pixelData, 0, width);
try {
if(!pg.grabPixels()) {
throw new RuntimeException();
}
} catch (final InterruptedException ie) {
throw new RuntimeException(file.getPath(), ie);
}
return pixelData;
}
/**
* Gets the {#link BufferedImage} from the passed in {#link File}.
*
* #param file The <code>File</code> to use.
* #return The resulting <code>BufferedImage</code>
*/
#SuppressWarnings("unused")
final static BufferedImage getBufferedImage(final File file) {
Image image;
try (final FileInputStream inputStream = new FileInputStream(file)) {
// ImageIO.read(file) is broken for some images so I went this
// route
image = Toolkit.getDefaultToolkit().createImage(file.getCanonicalPath());
//forces the image to be rendered
new ImageIcon(image);
} catch(final Exception e2) {
throw new RuntimeException(file.getPath(), e2);
}
final BufferedImage converted = new BufferedImage(image.getWidth(null), image.getHeight(null), BufferedImage.TYPE_INT_ARGB);
final Graphics2D g2d = converted.createGraphics();
g2d.drawImage(image, 0, 0, null);
g2d.dispose();
return converted;
}
/**
* Compares file1 to file2 to see if they are the same based on a visual
* pixel by pixel comparison. This has issues with marking images different
* when they are not. Works perfectly for all images.
*
* #param file1 First file to compare
* #param file2 Second image to compare
* #return <code>true</code> if they are equal, otherwise
* <code>false</code>.
*/
private final static boolean visuallyCompareJava(final File file1, final File file2) {
return equals(getPixels(getBufferedImage(file1), file1), getPixels(getBufferedImage(file2), file2));
}
/**
* Compares file1 to file2 to see if they are the same based on a visual
* pixel by pixel comparison. This has issues with marking images different
* when they are not. Works perfectly for all images.
*
* #param file1 Image 1 to compare
* #param file2 Image 2 to compare
* #return <code>true</code> if both images are visually the same.
*/
public final static boolean visuallyCompare(final File file1, final File file2) {
logger.debug("Start comparing \"{}\" and \"{}\".", file1.getPath(), file2.getPath());
if(file1 == file2) {
return true;
}
boolean answer = visuallyCompareJava(file1, file2);
if(!answer) {
logger.info("The files \"{}\" and \"{}\" are not pixel by pixel the same image. Manual comparison required.", file1.getPath(), file2.getPath());
}
logger.debug("Finish comparing \"{}\" and \"{}\".", file1.getPath(), file2.getPath());
return answer;
}
/**
* #param file The image to check
* #return <code>true</code> if the image contains one or more pixels with
* some percentage of transparency (Alpha)
*/
public final static boolean containsAlphaTransparency(final File file) {
logger.debug("Start Alpha pixel check for {}.", file.getPath());
boolean answer = false;
for(final int pixel : getPixels(getBufferedImage(file), file)) {
//If the alpha is 0 for both that means that the pixels are 100%
//transparent and the color does not matter. Return false if
//only 1 is 100% transparent.
if(((pixel >> 24) & 0xff) != 255) {
logger.debug("The image contains Aplha Transparency.");
return true;
}
}
logger.debug("The image does not contain Aplha Transparency.");
logger.debug("End Alpha pixel check for {}.", file.getPath());
return answer;
}
}
For grayscale images I've used Mean Square Error as a measure of how different two images are before. Just plug the corresponding pixels from each image into the formula.
Not only can this tell you if they are exactly the same, but also it can tell you how different two images are, albeit in a rather crude manner.
https://en.wikipedia.org/wiki/Mean_squared_error
EDIT:
Note: This is C# code not Java (apologies but that's what I wrote it in originally), however it should be easily transferable.
//Calculates the MSE between two images
private double MSE(Bitmap original, Bitmap enhanced)
{
Size imgSize = original.Size;
double total = 0;
for (int y = 0; y < imgSize.Height; y++)
{
for (int x = 0; x < imgSize.Width; x++)
{
total += System.Math.Pow(original.GetPixel(x, y).R - enhanced.GetPixel(x, y).R, 2);
}
}
return (total / (imgSize.Width * imgSize.Height));
}
You can try this
Example
Wayback Machine to the rescue here
They explain how to compare two images
If you mean exactly the same, compare each pixel.
If you mean compare a RGB image and a greyscale image, you need to convert the RGB to greyscale first, for doing this, you need to know how you did RGB->Greyscale before, there're different ways of doing this and you could get different results.
Edit, if the method it used in RGB->Greyscale is liner, you could work out a,b,c in the formula grey = a*R + b*G + c*B by comparing 3 pixels.
One of the easiest approach I tried is getting the pixel array of both images and comparing them with Arrays.equals method.
Code sample :
package image_processing;
import java.awt.image.BufferedImage;
import java.awt.image.DataBufferByte;
import java.io.File;
import java.io.IOException;
import java.util.Arrays;
import javax.imageio.ImageIO;
public class CheckPixels {
public static void main(String args[]) throws IOException {
File pic1 = new File("D:\\ani\\img1.png");
File pic2 = new File("D:\\ani\\img2.png");
if (Arrays.equals(returnPixelVal(pic1), returnPixelVal(pic2))) {
System.out.println("Match");
} else {
System.out.println("No match");
}
}
public static byte[] returnPixelVal(File in) {
BufferedImage img = null;
File f = null;
byte[] pixels = null;
// read image
try {
f = in;
img = ImageIO.read(f);
pixels = ((DataBufferByte) img.getRaster().getDataBuffer()).getData();
} catch (IOException e) {
System.out.println(e);
}
return pixels;
}
}

Appropriate way to draw to a JPanel for 2D Game development?

I am wanting to make a 2D Game but I am having trouble finding the best and most efficient way to draw to a 2D Surface/Canvas using a BufferStrategy. I will be using a JFrame as the main window and want to draw to the surface of that. I would love to see some example code of how this is done (if this is a good way to do it) aswell as other examples. It would be great if someone could also explain some advantages and disadvantages of doing so.
I am currently adding my drawing class to my JFrame using 'frame.add(new Painter());' and then overriding the paintComponent method. The only problem I have found with this is it seems to only call this method once.
this is my Painter class:
public class Painter extends JPanel{
public static Player player;
public Painter() {
player = new Player(300, 300);
}
public void paint(Graphics g) {
player.x++;
g.setColor(Color.white);
g.fillRect(player.x, player.y, 32, 32);
}
}
In the simplest case, where your game needs to update the screen based on user actions only, you will need to call repaint() (on the JFrame for instance) when you update something.
In other cases, you need to construct a so called Game Loop, where you update the game state and render updated game state in a timely manner. A nice tutorial on a simple Game Loop with Java code can be found here: http://obviam.net/index.php/the-android-game-loop/
In case you develop a serious game, you should stick with a game engine for managing the game loop and other routine game development aspects. A good Java game engine can be found here: http://code.google.com/p/playn/
For a game loop and an efficient way to printing to the screen for game objects and others(images, explosions, etc), you need a timing mechanism and a JFrame to print to over and over again, while at the same time, getting updates from the player and the game state itself.
First, you need a main method, and im going to guess that you are pretty new to this type of field in java so I will break it down for you as fast and clearly as possible.
public static main(String[] args)
{
yourClassName game = new yourClassName();
game.run();
System.exit(0);
}
This main method is doing 2 things first, creating an object to your run method (because static references are not recommended for game loops) and then calling that method with your newly created object. When that run method is done, the system will exit the program.
Now im not going into full detail here but once you have the run method running you need an init method that will only run once. In this method, you are going to create your JFrame that you are rendering to. That is fairly simple to do so, so i will not go any farther in creating a JFrame class. However your Run method should look something like this...
void Run()
{
init();
while(isRunning)
{
update();
draw();
time = (1000 / fps) - (System.currentTimeMillis() - time);
if (time > 0)
{
try
{
Thread.sleep(time);
}
catch(Exception e){}
}
}
}
This method will slow the computing speed to a certain fps that you desire(in this case the fps variable is named fps for show).
Now in your update method, you will have your keyBinding and other stuff to look for changes with the keyboard or mouse(and in my case currently, a server). Most people dont know how to print or draw to the JFrame without taking in a paramitor that the Repaint method requires, so we are going to override that by adding double buffering.
BufferedImage backBuffer;
In the initialize method you will add
backBuffer = new BufferedImage(getWidth(),getHeight(),
BufferedImage.TYPE_INT_RGB)
In the draw method you will have...
Graphics g = getGraphics();
Graphics bbg = backBuffer.getGraphics();
And with those you have the ability to draw to the JFrame created by the init class(also, by doing this, you have the ability to draw from any class or thread to decrease the processing load).
To see if it works, go ahead and use the bbg.fillRect(updateX,updateY,5,5)
The updateX and updateY represent variables that you use to update the location of the rectangle. Save them as a global variable or a public variable saved in a character class.
And if all else fails, here is sample code that i have used for creating my own game engine...
import input.InputHandler;
import java.awt.*;
import java.awt.event.KeyEvent;
import java.awt.image.BufferedImage;
import javax.swing.JFrame;
/**
* Main class for the game
*/
public class GameTutorial extends JFrame
{
boolean isRunning = true;
int fps = 30;
int windowWidth = 500;
int windowHeight = 500;
BufferedImage backBuffer;
Insets insets;
InputHandler input;
int x = 0;
public static void main(String[] args)
{
GameTutorial game = new GameTutorial();
game.run();
System.exit(0);
}
/**
* This method starts the game and runs it in a loop
*/
public void run()
{
initialize();
while(isRunning)
{
long time = System.currentTimeMillis();
update();
draw();
// delay for each frame - time it took for one frame
time = (1000 / fps) - (System.currentTimeMillis()- time);
if (time > 0)
{
try
{
Thread.sleep(time);
}
catch(Exception e){}
}
}
setVisible(false);
}
/**
* This method will set up everything need for the game to run
*/
void initialize()
{
setTitle("Game Tutorial");
setSize(windowWidth, windowHeight);
setResizable(false);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setVisible(true);
insets = getInsets();
setSize(insets.left + windowWidth + insets.right,
insets.top + windowHeight + insets.bottom);
backBuffer = new BufferedImage(windowWidth, windowHeight, BufferedImage.TYPE_INT_RGB);
input = new InputHandler(this);
}
/**
* This method will check for input, move things
* around and check for win conditions, etc
*/
void update()
{
if (input.isKeyDown(KeyEvent.VK_RIGHT))
{
x += 5;
}
if (input.isKeyDown(KeyEvent.VK_LEFT))
{
x -= 5;
}
}
/**
* This method will draw everything
*/
void draw()
{
Graphics g = getGraphics();
Graphics bbg = backBuffer.getGraphics();
bbg.setColor(Color.WHITE);
bbg.fillRect(0, 0, windowWidth, windowHeight);
bbg.setColor(Color.BLACK);
bbg.drawOval(x, 10, 20, 20);
g.drawImage(backBuffer, insets.left, insets.top, this);
}
}
I hope this helps and I know this may be a VERY late answer but i have yet to see one decent java game engine that was simple to understand and use and fun to work with. Hope you stay with it and happy programming!!!

Moving mouse cursor when station is locked (java)

I have the need at my workstation to disable a long idle.
I've been using a piece of code that moves the mouse on the screen once a while, which worked pretty well.
Lately, our security department applied a smart-card&biometric login policy,
which requires my card to be present inside the keyboard (special slot).
Since then the troubles began.
The process works fine as long as I'm logged in, meaning my card is present, but not working if my card is removed.
(I've been logging the process activity, and everything works fine, but the mouse cursor doesn't move.)
Can someone suggest me a way (or link) so I can solve this matter?
Edit
OS: Windows XP
Here's the code that is resposible for moving the mouse.
Notice that I have logged its operation, and tested it: The results outcome logged entries (as if the code was ran) but the mouse cursor wasn't moved on the locked session.
Thanks again
package AntiIdle;
import java.awt.*;
import java.util.Calendar;
import java.text.SimpleDateFormat;
class SimulateMouseAction implements Runnable {
/**
* Robot object used to move the mouse.
*/
private Robot iRobot;
/**
* Bed object, so thread could notify sleeping objects.
*/
private Bed bed;
/**
* Default constructor is neutralized.
*/
#SuppressWarnings("unused")
private SimulateMouseAction () { }
/**
* Constructs class with bed object.
*
* #param bed Bed object to notify the sleepers.
* #throws AWTException if Robot creation fails.
*/
public SimulateMouseAction (Bed bed) throws AWTException {
this.bed = bed;
iRobot = new Robot();
}
/**
* Activates tread.
*/
public void run() {
System.out.println(new SimpleDateFormat("d/M/yy hh:mm").format(Calendar.getInstance().getTime()) +
"Mouse start");
Dimension scrSize = Toolkit.getDefaultToolkit().getScreenSize();
int x, y;
for (int prcnt=0; prcnt<100; prcnt++) {
x = (int) scrSize.getWidth() * prcnt / 100;
y = (int) scrSize.getHeight() * prcnt / 100;
moveMouse(x, y);
}
y = (int) scrSize.getHeight() - 20;
for (int prcnt=100; prcnt>0; prcnt--) {
x = (int) scrSize.getWidth() * prcnt / 100;
moveMouse(x, y);
}
for (int prcnt=0; prcnt<100; prcnt++) {
x = (int) scrSize.getWidth() * prcnt / 100;
y = (int) scrSize.getHeight() * (100-prcnt) / 100;
moveMouse(x, y);
}
iRobot.mouseMove((int) scrSize.getWidth()/2, (int) scrSize.getHeight()/2);
System.out.println(new SimpleDateFormat("d/M/yy hh:mm").format(Calendar.getInstance().getTime()) +
"Mouse end");
bed.awakeTheSleepers();
}
/**
* Moves mouse cursor to given coordinates.
*
* #param x X coordinate.
* #param y Y coordinate.
*/
private void moveMouse(int x, int y) {
iRobot.mouseMove(x, y);
try {
Thread.sleep(10);
} catch(InterruptedException ie) {
ie.printStackTrace();
}
}
}
Edit
#Mark Peters: Thanks for repling. As funny as it seems, they gave me this solution... I've built a java application which launches some vb script that loads Excel and performs some tasks and create reports. The problem is that it stops launching Excel after a day of idle on my station. Everything else seem to be working (The java application keeps working-I've been logging its activity as well as the mouse mover activity in the attached code above). So as you can see, the security problem you suggested isn't solved either way. As a rule at my country, I'm forced to have 1 week of vacation in a row at least once a year. Ironically, this what's preventing me from fulfilling this duty.
Any suggestion?

Categories

Resources