http://www.youtube.com/watch?v=iH1xpfOBN6M I've followed this tutorial up to episode four and where his window has pixels in it, mine is completely blank. I want to know whether anyone with experience with 3d programming in eclipse can see if there is something that doesn't look right to you.
Display:
package com.mine.minefrost;
import java.awt.Canvas;
import java.awt.Graphics;
import java.awt.image.BufferStrategy;
import java.awt.image.BufferedImage;
import java.awt.image.DataBufferInt;
import javax.swing.JFrame;
import com.minefrost.graphics.Render;
import com.minefrost.graphics.Screen;
public class Display extends Canvas {
private static final long serialVersionUID = 1L;
public static final int WIDTH = 800;
public static final int HEIGHT = 600;
public static final String TITLE = "Minefrost Pre-Alpha 0.01";
private Thread thread;
private Screen screen;
private BufferedImage img;
private Render render;
private boolean running = false;
private int[] pixels;
public Display() {
screen = new Screen(WIDTH, HEIGHT);
img = new BufferedImage(WIDTH, HEIGHT, BufferedImage.TYPE_INT_RGB);
pixels = ((DataBufferInt)img.getRaster().getDataBuffer()).getData();
}
private void start() {
if (running)
return;
running = true;
thread = new Thread();
thread.start();
}
private void stop() {
if (!running) return;
running = false;
try {
thread.join();
} catch (Exception e) {
e.printStackTrace();
System.exit(0);
}
}
private void run() {
while (running) {
tick();
render();
}
}
private void tick() {
}
private void render() {
BufferStrategy bs = this.getBufferStrategy();
if (bs == null) {
createBufferStrategy(3);
return;
}
screen.render();
for (int i = 0; i<WIDTH * HEIGHT; i++) {
pixels[i] = screen.pixels[i];
}
Graphics g = bs.getDrawGraphics();
g.drawImage(img, 0, 0, WIDTH, HEIGHT, null);
g.dispose();
bs.show();
}
public static void main(String[] args) {
Display game = new Display();
JFrame frame = new JFrame();
frame.add(game);
frame.pack();
frame.setTitle(TITLE);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationRelativeTo(null);
frame.setSize(WIDTH, HEIGHT);
frame.setResizable(false);
frame.setVisible(true);
game.start();
}
}
Render:
package com.minefrost.graphics;
public class Render {
public final int width;
public final int height;
public final int[] pixels;
public Render(int width,int height) {
this.width = width;
this.height = height;
pixels = new int[width * height];
}
public void draw(Render render, int xOffset, int yOffset) {
for (int y = 0; y < render.height; y++) {
int yPix = y + yOffset;
for (int x = 0; x < render.width; x++) {
int xPix = x + xOffset;
pixels[xPix+yPix*width] = render.pixels[x+y*render.width];
}
}
}
}
Screen:
package com.minefrost.graphics;
import java.util.Random;
public class Screen extends Render {
private Render test;
public Screen(int width, int height) {
super(width, height);
Random random = new Random();
test = new Render(256, 256);
for (int i = 0; i <256*256; i++) {
test.pixels[i] = random.nextInt();
}
}
public void render() {
draw(test, 0, 0);
}
}
Thanks in advance!
Your main method in the Display class needs to call game.run(). With that in, you get a display of some random pixel 'snow' in the top left corner. I'm not sure if that's what you wanted, but it's what happens!
Another minor point is that the reference to the Render class in Display is unused. Also, it's odd that stop() and run() are private.
Related
I am writing a Crazy Eights game and trying to have mouse control added in. I just starting writing it but I can't verify if it's working or not. I've added System.out.println() to the pressed and released event calls but no output happens. I just need to get it working and be able to see an output of some kind for debugging. I've also tried to use another example on stackoverflow to help me out but I'm still having issues. The below code is what I'm working with. Let me know if you need to see another class.
Thanks
MouseControl.java
package crazyeightscountdown.CoreClasses;
import java.awt.Canvas;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
public class MouseControl extends MouseAdapter {
public Canvas canvas;
public MouseControl (Canvas c){
this.canvas = c;
}
#Override
public void mouseReleased (MouseEvent e){
System.out.println("Mouse Released.\n");
}
#Override
public void mousePressed (MouseEvent e){
System.out.println("Mouse Pressed.\n");
}
#Override
public void mouseClicked (MouseEvent e){
}
#Override
public void mouseEntered (MouseEvent e){
}
#Override
public void mouseExited (MouseEvent e){
}
}//class
Game.java
package crazyeightscountdown;
import static com.sun.java.accessibility.util.AWTEventMonitor.addMouseListener;
import static crazyeightscountdown.CoreClasses.Constants.CARDPICX;
import crazyeightscountdown.CoreClasses.Deck;
import crazyeightscountdown.CoreClasses.MouseControl;
import crazyeightscountdown.CoreClasses.Player;
import java.awt.Graphics;
import java.awt.image.BufferStrategy;
//Sets up parameters for the game window
public class Game implements Runnable {
private Display display;
public int width, height;
public Game(String title, int width, int height) {
this.width = width;
this.height = height;
display = new Display(title, width, height);
StartGame();
}
//create the game decks
//Deck maindeck = new Deck();
public Deck faceupdeck = new Deck();
public Deck facedowndeck = new Deck();
Deck tempdeck = new Deck();
public int deckindex = 0;
public Player playerone = new Player();
public Player playertwo = new Player();
private BufferStrategy bs;
private Graphics g;
private boolean running = false;
private Thread thread;
public void StartGame() {
//setup mouse
addMouseListener (new MouseControl(display.getCanvas()));
//set players
playerone.SetPlayer(1);
playertwo.SetPlayer(2);
//set values to main deck
facedowndeck = facedowndeck.SetDeck(facedowndeck);
//shuffle the deck
facedowndeck = facedowndeck.ShuffleDeck(facedowndeck);
//hand out first deal
FirstDeal();
}
public void FirstDeal() {
int playerindex = 1;
deckindex = 1;
//deal each player 8 cards to start
for (int h = 0; h < 8; h++) {
playerone.hand.card[playerindex] = facedowndeck.card[deckindex];
facedowndeck.card[deckindex].present = false;
playerone.hand.card[playerindex].present = true;
deckindex++;
playertwo.hand.card[playerindex] = facedowndeck.card[deckindex];
facedowndeck.card[deckindex].present = false;
playerone.hand.card[playerindex].present = true;
deckindex++;
playerindex++;
//facedowndeck.Truncate(facedowndeck);
}
//put card face up
faceupdeck.card[1] = facedowndeck.card[deckindex];
deckindex++;
}
private void render() {
bs = display.getCanvas().getBufferStrategy();
if (bs == null) {
display.getCanvas().createBufferStrategy(3);
return;
}
g = bs.getDrawGraphics();
//Clear Screen
g.clearRect(0, 0, width, height);
/******* START DRAWING HERE **********/
//draw player1 deck
for (int f = 1; f < 9; f++) {
g.drawImage(playerone.hand.card[f].pic, (CARDPICX * (f - 1)) + (f * 5), 5, null);
g.drawImage(playertwo.hand.card[f].pic, (CARDPICX * (f - 1)) + (f * 5), 450, null);
}
g.drawImage(faceupdeck.card[1].pic,400, 200, null);
/*********** END DRAWING HERE ***********/
bs.show();
g.dispose();
}
private void tick() {
}
public void run() {
//init();
while (running) {
tick();
render();
}
stop();
}
public synchronized void start() {
if (running) {
return;
}
running = true;
thread = new Thread(this);
thread.start();
}
public synchronized void stop() {
if (!running) {
return;
}
running = false;
try {
thread.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}//class
Display.java
package crazyeightscountdown;
import java.awt.Canvas;
import java.awt.Dimension;
import javax.swing.JFrame;
//display parameters for the window
public class Display {
public JFrame frame;
public Canvas canvas;
public String title;
public int width, height;
public Display(String title, int width, int height){
this.title = title;
this.width = width;
this.height = height;
createDisplay();
}
private void createDisplay(){
frame = new JFrame(title);
frame.setSize(width, height);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setResizable(false);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
canvas = new Canvas();
canvas.setPreferredSize(new Dimension(width, height));
canvas.setMaximumSize(new Dimension(width, height));
canvas.setMinimumSize(new Dimension(width, height));
frame.add(canvas);
frame.pack();
}
public Canvas getCanvas(){
return canvas;
}
}
You have to add the MouseListener to a component: frame.addMouseListener(...)
I am trying to use some sort of draw method to draw a sprite image to my subclass of JPanel called AnimationPanel. I have created a Spritesheet class which can generate a BufferedImage[] that contains all of the sprites in the sheet. In my AnimationPanel class, which implements Runnable, I am getting that BufferedImage[] from the spritesheet instantiated in the AnimationPanel constructor. I want to be able to loop through this array and display each sprite to the screen. How would I do this? Here are my AnimationPanel and Spritesheet classes.
AnimationPanel
package com.kahl.animation;
import javax.swing.JPanel;
public class AnimationPanel extends JPanel implements Runnable {
//Instance Variables
private Spritesheet sheet;
private int currentFrame;
private Thread animationThread;
private BufferedImage image;
public AnimationPanel(Spritesheet aSheet) {
super();
sheet = aSheet;
setPreferredSize(new Dimension(128,128));
setFocusable(true);
requestFocus();
}
public void run() {
BufferedImage[] frames = sheet.getAllSprites();
currentFrame = 0;
while (true) {
frames[currentFrame].draw(); //some implementation still necessary here
currentFrame++;
if (currentFrame >= frames.length) {
currentFrame = 0;
}
}
}
public void addNotify() {
super.addNotify();
if (animationThread == null) {
animationThread = new Thread(this);
animationThread.start();
}
}
}
Spritesheet
package com.kahl.animation;
import java.awt.image.BufferedImage;
import java.imageio.ImageIO;
import java.io.IOException;
import java.io.File;
public class Spritesheet {
//Instance Variables
private String path;
private int frameWidth;
private int frameHeight;
private int framesPerRow;
private int frames;
private BufferedImage sheet = null;
//Constructors
public Spritesheet(String aPath,int width,int height,int fpr, int numOfFrames) {
path = aPath;
frameWidth = width;
frameHeight = height;
framesPerRow = fpr;
frames = numOfFrames;
try {
sheet = ImageIO.read(getClass().getResourceAsStream());
} catch (IOException e) {
e.printStackTrace();
}
}
//Methods
public int getHeight() {
return frameWidth;
}
public int getWidth() {
return frameWidth;
}
public int getFramesPerRow() {
return framesPerRow;
}
private BufferedImage getSprite(int x, int y, int h, int w) {
BufferedImage sprite = sheet.getSubimage(x,y,h,w);
}
public BufferedImage[] getAllSprites() {
BufferedImage[] sprites = new BufferedImage[frames];
int y = 0;
for (int i = 0; i < frames; i++) {
x = i * frameWidth;
currentSprite = sheet.getSprite(x,y,frameHeight,frameWidth);
sprites.add(currentSprite);
}
return sprites;
}
}
I'd encourage the use of a javax.swing.Timer to control the frame rate, rather than an uncontrolled loop
Once the timer "ticks", you need to increment the current frame, get the current image to be rendered and call repaint on the JPanel
Use Graphics#drawImage to render the image.
See...
Painting in AWT and Swing
Performing Custom Painting
How to use Swing Timers
Graphics#drawImage(Image, int, int, ImageObserver)
for more details
There is a cascading series of issues with your Spritesheet class, apart from the fact that it won't actually compile, there are issues with you returning the wrong values from some methods and relying on values which are better calculated...
I had to modify your code so much, I can't remember most of them
public int getHeight() {
return frameWidth;
}
and
public BufferedImage[] getAllSprites() {
BufferedImage[] sprites = new BufferedImage[frames];
int y = 0;
for (int i = 0; i < frames; i++) {
x = i * frameWidth;
currentSprite = sheet.getSprite(x,y,frameHeight,frameWidth);
sprites.add(currentSprite);
}
return sprites;
}
Stand out as two main examples...
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.Timer;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class TestSpriteSheet {
public static void main(String[] args) {
new TestSpriteSheet();
}
public TestSpriteSheet() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
}
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class TestPane extends JPanel {
private Spritesheet spritesheet;
private BufferedImage currentFrame;
private int frame;
public TestPane() {
spritesheet = new Spritesheet("/Sheet02.gif", 240, 220);
Timer timer = new Timer(100, new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
currentFrame = spritesheet.getSprite(frame % spritesheet.getFrameCount());
repaint();
frame++;
}
});
timer.start();
}
#Override
public Dimension getPreferredSize() {
return new Dimension(240, 220);
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
if (currentFrame != null) {
Graphics2D g2d = (Graphics2D) g.create();
int x = (getWidth() - currentFrame.getWidth()) / 2;
int y = (getHeight() - currentFrame.getHeight()) / 2;
g2d.drawImage(currentFrame, x, y, this);
g2d.dispose();
}
}
}
public class Spritesheet {
//Instance Variables
private String path;
private int frameWidth;
private int frameHeight;
private BufferedImage sheet = null;
private BufferedImage[] frameImages;
//Constructors
public Spritesheet(String aPath, int width, int height) {
path = aPath;
frameWidth = width;
frameHeight = height;
try {
sheet = ImageIO.read(getClass().getResourceAsStream(path));
frameImages = getAllSprites();
} catch (IOException e) {
e.printStackTrace();
}
}
public BufferedImage getSprite(int frame) {
return frameImages[frame];
}
//Methods
public int getHeight() {
return frameHeight;
}
public int getWidth() {
return frameWidth;
}
public int getColumnCount() {
return sheet.getWidth() / getWidth();
}
public int getRowCount() {
return sheet.getHeight() / getHeight();
}
public int getFrameCount() {
int cols = getColumnCount();
int rows = getRowCount();
return cols * rows;
}
private BufferedImage getSprite(int x, int y, int h, int w) {
BufferedImage sprite = sheet.getSubimage(x, y, h, w);
return sprite;
}
public BufferedImage[] getAllSprites() {
int cols = getColumnCount();
int rows = getRowCount();
int frameCount = getFrameCount();
BufferedImage[] sprites = new BufferedImage[frameCount];
int index = 0;
System.out.println("cols = " + cols);
System.out.println("rows = " + rows);
System.out.println("frameCount = " + frameCount);
for (int row = 0; row < getRowCount(); row++) {
for (int col = 0; col < getColumnCount(); col++) {
int x = col * getWidth();
int y = row * getHeight();
System.out.println(index + " " + x + "x" + y);
BufferedImage currentSprite = getSprite(x, y, getWidth(), getHeight());
sprites[index] = currentSprite;
index++;
}
}
return sprites;
}
}
}
Remember, animation is the illusion of change over time. You need to provide a delay between each frame of the animation, long enough for the user to recognise it, but short enough to make the animation look smooth.
In the above example, I've used 100 milliseconds, simply as an arbitrary value. It could be possible to use something more like 1000 / spritesheet.getFrameCount(), which will allow a full second for the entire animation (all the frames within one second).
You might need to use different values, for longer or short animations, depending on your needs
Here's some generic code for drawing an image to a JPanel. This method is called to paint your JPanel component.
public void paintComponent (Graphics g)
{
super.paintComponent(g);
//I would have image be a class variable that gets updated in your run() method
g.drawImage(image, 0, 0, this);
}
I may also modify run() to look something like this:
public void run() {
BufferedImage[] frames = sheet.getAllSprites();
currentFrame = 0;
while (true) {
image = frames[currentFrame];
this.repaint(); //explicitly added "this" for clarity, not necessary.
currentFrame++;
if (currentFrame >= frames.length) {
currentFrame = 0;
}
}
}
In regards to only repainting part of the component, it gets a little more complicated
public void run() {
BufferedImage[] frames = sheet.getAllSprites();
currentFrame = 0;
while (true) {
image = frames[currentFrame];
Rectangle r = this.getDirtyRect();
this.repaint(r);
currentFrame++;
if (currentFrame >= frames.length) {
currentFrame = 0;
}
}
}
public Rectangle getDirtyRect() {
int minX=0; //calculate smallest x value affected
int maxX=0; //calculate largest x value affected
int minY=0; //calculate smallest y value affected
int maxY=0; //calculate largest y value affected
return new Rectangle(minX,minY,maxX,maxY);
}
I've been getting this error when I run my game, not debug it for some reason :/ If anyone can help me with this bug than I'd greatly appreciate it, here's the error: (I'm new to the website)
Exception in thread "Display" java.lang.ArrayIndexOutOfBoundsException: 48600
at com.cmnatic.IndieFirstStudios.Game.render(Game.java:78)
at com.cmnatic.IndieFirstStudios.Game.run(Game.java:60)
at java.lang.Thread.run(Unknown Source)
Here is my code :
package com.cmnatic.IndieFirstStudios;
import java.awt.Canvas;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.image.BufferStrategy;
import java.awt.image.BufferedImage;
import java.awt.image.DataBufferInt;
import javax.swing.JFrame;
import com.cmnatic.IndieFirstStudios.graphics.Screen;
public class Game extends Canvas implements Runnable {
/**
*
*/
private static final long serialVersionUID = 1L;
public static int width = 300;
public static int height = width / 16 * 9;
public static int scale = 3;
private Thread thread;
private JFrame frame;
private boolean running = false;
private Screen screen;
private BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
private int[] pixels = ((DataBufferInt)image.getRaster().getDataBuffer()).getData();
public Game() {
Dimension size = new Dimension(width * scale, height * scale);
setPreferredSize(size);
screen = new Screen(width, height);
frame = new JFrame();
}
public synchronized void start() {
running = true;
thread = new Thread(this, "Display");
thread.start();
}
public synchronized void stop() {
running = false;
try {
thread.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public void run() {
while (running == true) {
update();
render();
}
}
public void update() {
}
public void render() {
BufferStrategy bs = getBufferStrategy();
if (bs == null) {
createBufferStrategy(3);
return;
}
screen.render();
for (int i = 0; 1 < pixels.length; i++) {
pixels[i] = screen.pixels[i];
}
Graphics g = bs.getDrawGraphics();
g.setColor(Color.BLACK);
g.fillRect(0, 0, getWidth(), getHeight());
g.drawImage(image, 0, 0, getWidth(), getHeight(), null);
g.dispose();
bs.show();
}
public static void main(String[] args) {
Game game = new Game();
game.frame.setResizable(false);
game.frame.setTitle("Fallen Humanity");
game.frame.add(game);
game.frame.pack();
game.frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
game.frame.setLocationRelativeTo(null);
game.frame.setVisible(true);
game.start();
}
}
You have an infinite loop at line 78. Your saying run through the for loop if 1(one) < pixel.length. So eventually i will be > pixel.length
Just change the loop to:
for (int i = 0; i < pixels.length; i++) {
pixels[i] = screen.pixels[i];
}
I have been watching tutorials on how to make a 3D game in Java using Eclipse. I have copied all the code word for word and am not getting the same result and it is very frustrating. At the moment all I am trying to do is create a small square of randomly generated pixels and all I'm getting is a blank window. This is the code and classes I am using.
Class1 = Display
package com.mime.testgame2;
import java.awt.Canvas;
import java.awt.Graphics;
import java.awt.image.BufferStrategy;
import java.awt.image.BufferedImage;
import java.awt.image.DataBufferInt;
import javax.swing.JFrame;
import com.mime.testgame2.graphics.Render;
import com.mime.testgame2.graphics.Screen;
public class Display extends Canvas implements Runnable {
private static final long serialVersionUID = 1L;
public static final int width = 800;
public static final int height = 600;
public static String title = "3D Game Pre-Alpha 0.0.1";
private Thread thread;
private boolean running = false;
private Render render;
private Screen screen;
private BufferedImage img;
private int[] pixels;
public Display() {
screen = new Screen(width, height);
img = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
pixels = ((DataBufferInt) img.getRaster().getDataBuffer()).getData();
}
private void start() {
if (running)
return;
running = true;
thread = new Thread(this);
thread.start();
}
private void stop() {
if(!running) return;
running = false;
try {
thread.join();
} catch (Exception e) {
e.printStackTrace();
System.exit(0);
}
}
public void run() {
while (running) {
tick();
render();
}
}
private void tick() {
}
private void render() {
BufferStrategy bs = this.getBufferStrategy();
if (bs == null) {
createBufferStrategy(3);
return;
}
screen.render();
for (int i = 0; i < width * height; i++) {
pixels[i] = screen.pixels[i];
}
Graphics g = bs.getDrawGraphics();
g.drawImage(img, 0, 0, width, height, null);
g.dispose();
bs.show();
}
public static void main(String[] args) {
Display game = new Display();
JFrame frame = new JFrame();
frame.add(game);
frame.setResizable(false);
frame.setVisible(true);
frame.setSize(width, height);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationRelativeTo(null);
frame.setTitle(title);
}
}
Class2 = Render
package com.mime.testgame2.graphics;
public class Render {
public final int Width;
public final int Height;
public final int[] pixels;
public Render(int Width, int Height) {
this.Width = Width;
this.Height = Height;
pixels = new int[Width * Height];
}
public void draw(Render render, int xOffset, int yOffset) {
for(int y = 0; y < render.Height; y++) {
int yPix = y + yOffset;
for(int x = 0; x < render.Width; x++) {
int xPix = x + xOffset;
pixels[xPix + yPix * Width] = render.pixels[x + y * rend er.Width];
}
}
}
}
Class3 = Screen
package com.mime.testgame2.graphics;
import java.util.Random;
public class Screen extends Render {
private Render test;
public Screen(int Width, int Height) {
super(Width, Height);
Random random = new Random();
test = new Render(256, 256);
for (int i = 0; i < 256 * 256; i++) {
test.pixels[i] = random.nextInt();
}
}
public void render() {
draw(test, 0, 0);
}
}
Can anyone help me?
I'm trying to make an image of random pixels. I wrote this code, but no usefulness
LadderSnack.java
import java.awt.*;
import java.awt.image.BufferStrategy;
import java.awt.image.BufferedImage;
import java.awt.image.DataBufferInt;
import javax.swing.*;
public class LadderSnack extends Canvas implements Runnable {
public static JFrame frame = new JFrame("EmiloLadderSnack v. 1.0");
public static int width = Toolkit.getDefaultToolkit().getScreenSize().width, height = Toolkit.getDefaultToolkit().getScreenSize().height;
public boolean run = false;
public Thread thread;
public BufferedImage img;
public int[] pixels;
public Screen screen;
public LadderSnack() {
screen = new Screen(width, height);
img = new BufferedImage(width, height, BufferedImage.TYPE_INT_BGR);
pixels = ((DataBufferInt) img.getRaster().getDataBuffer()).getData();
}
public void start() {
if (run)
return;
run = true;
thread = new Thread(this);
thread.start();
}
public void stop() {
if (!run)
return;
try {
thread.join();
} catch (Exception e) {
e.printStackTrace();
System.exit(0);
}
}
public void run() {
while (run) {
trick();
render();
}
}
private void trick() {
}
private void render() {
screen = new Screen(width, height);
BufferStrategy bs = this.getBufferStrategy();
if (bs == null) {
createBufferStrategy(3);
return;
}
for (int i = 0; i < width * height; i++)
pixels[i] = screen.pixels[i];
Graphics g = bs.getDrawGraphics();
g.drawImage(img, 0, 0, width, height, null);
g.dispose();
bs.show();
}
public static void main(String[] args) {
LadderSnack ladderSnack = new LadderSnack();
frame.setSize(width, height);
frame.setDefaultCloseOperation(frame.EXIT_ON_CLOSE);
frame.add(ladderSnack);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
ladderSnack.start();
}
}
Render.java
public class Render {
public int width, height;
public int[] pixels;
public Render(int width, int height) {
this.width = width;
this.height = height;
pixels = new int[width * height];
}
public void draw(Render render, int xOffset, int yOffset) {
int xPixel, yPixel, y, x;
for (x = 0; x < width; x++) {
xPixel = x + xOffset;
for (y = 0; y < height; y++) {
yPixel = y + yOffset;
pixels[xPixel + yPixel * width] = render.pixels[xPixel + yPixel * width];
}
}
}
}
Screen.java
import java.awt.Toolkit;
import java.util.Random;
public class Screen extends Render {
private Render test;
public Screen(int width, int height) {
super(width, height);
int i;
Random rand = new Random();
test = new Render(Toolkit.getDefaultToolkit().getScreenSize().width, Toolkit.getDefaultToolkit().getScreenSize().height);
for (i = 0; i < width * height; i++)
pixels[i] = rand.nextInt();
}
public void render() {
draw(test, 0, 0);
}
}
At runtime
public void render() {
draw(test, 50, 50);
}
in Screen.java
is never executed to move the image
I want the image to move through the frame, as a step to make animation and an animated random pixels image. Please,Help me.
You may want to use my api: http://www.threadox.com/projects/random-image-api/
You receive a buffered image and then you just have to draw it to the canvas.
Your code is a total mess. Here is something you might want to look out : Painting pixels images in Java
And here are the problems :
private void LadderSnack() I think this should be the constructor so should be written private LadderSnack()
Your Runnable implementation should be thought again. Avoid using while(true){} but rather use while(true) {Thread.sleep(xxx)} to avoid your application to freeze.
You create a pixels array of random values but then use pixels = ((DataBufferInt) img.getRaster().getDataBuffer()).getData(); which override your values with whatever is in the databuffer.
You never use your pixels array.
I think you should review the whole concept.
LadderSnack.java
import java.awt.*;
import java.awt.image.BufferStrategy;
import java.awt.image.BufferedImage;
import java.awt.image.DataBufferInt;
import javax.swing.*;
public class LadderSnack extends Canvas implements Runnable {
public static JFrame frame = new JFrame("EmiloLadderSnack v. 1.0");
public static int width = Toolkit.getDefaultToolkit().getScreenSize().width, height = Toolkit.getDefaultToolkit().getScreenSize().height;
public boolean run = false;
public Thread thread;
public BufferedImage img;
public int[] pixels;
public Screen screen;
public LadderSnack() {
screen = new Screen(width, height);
img = new BufferedImage(width, height, BufferedImage.TYPE_INT_BGR);
pixels = ((DataBufferInt) img.getRaster().getDataBuffer()).getData();
}
public void start() {
if (run)
return;
run = true;
thread = new Thread(this);
thread.start();
}
public void stop() {
if (!run)
return;
try {
thread.join();
} catch (Exception e) {
e.printStackTrace();
System.exit(0);
}
}
public void run() {
while (run) {
trick();
render();
}
}
private void trick() {
}
private void render() {
BufferStrategy bs = this.getBufferStrategy();
if (bs == null) {
createBufferStrategy(3);
return;
}
for (int i = 0; i < width * height; i++)
pixels[i] = screen.pixels[i];
Graphics g = bs.getDrawGraphics();
g.drawImage(img, 0, 0, width, height, null);
g.dispose();
bs.show();
}
public static void main(String[] args) {
LadderSnack ladderSnack = new LadderSnack();
frame.setSize(width, height);
frame.setDefaultCloseOperation(frame.EXIT_ON_CLOSE);
frame.add(ladderSnack);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
ladderSnack.start();
}
}
Render.java
public class Render {
public int width, height;
public int[] pixels;
public Render(int width, int height) {
this.width = width;
this.height = height;
pixels = new int[width * height];
}
public void draw(Render render, int xOffset, int yOffset) {
int xPixel, yPixel, y, x;
for (x = 0; x < render.width; x++) {
xPixel = x + xOffset;
for (y = 0; y < render.height; y++) {
yPixel = y + yOffset;
pixels[xPixel + yPixel * width] = render.pixels[xPixel-xOffset + (yPixel-yOffset) * render.width];
}
}
}
}
Screen.java
import java.awt.Toolkit;
import java.util.Random;
public class Screen extends Render {
private Render test;
public Screen(int width, int height) {
super(width, height);
int i;
Random rand = new Random();
test = new Render(333,333);//Toolkit.getDefaultToolkit().getScreenSize().width, Toolkit.getDefaultToolkit().getScreenSize().height);
for (i = 0; i < 333 * 333; i++)
test.pixels[i] = rand.nextInt();
render();
}
public void render() {
draw(test, 50, 50);
}
}