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);
}
}
Related
I am trying to edit the pixels of a new buffered image but when I use the constructor for a new BufferedImage it does not display, when I load an image and set the pixels it does. Why does it not display?
public void paintComponent(Graphics g) {
super.paintComponent(g);
int w = 1000;
int h = 1000;
BufferedImage image = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
//ImageIO.read(new File("/Users/george/Documents/Ali.png"));
int color = Color.BLACK.getRGB();
for(int x = 0; x < w; x++) {
for(int y = 0; y < h; y++) {
image.setRGB(x, y, color);
}
}
g.drawImage(image, 0, 0, null);
}
Again, don't edit the BufferedImage from within paintComponent -- do it elsewhere. For example:
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import javax.swing.*;
public class ImageEdit extends JPanel {
private static final int PREF_W = 400;
private static final int PREF_H = PREF_W;
private static final int COLOR = Color.BLACK.getRGB();
private BufferedImage image = null;
public ImageEdit() {
image = new BufferedImage(PREF_W, PREF_H, BufferedImage.TYPE_INT_RGB);
for(int x = 0; x < PREF_H; x++) {
for(int y = 0; y < PREF_W; y++) {
image.setRGB(x, y, COLOR);
}
}
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
if (image != null) {
g.drawImage(image, 0, 0, this);
}
}
#Override
public Dimension getPreferredSize() {
if (isPreferredSizeSet()) {
return super.getPreferredSize();
}
return new Dimension(PREF_W, PREF_H);
}
private static void createAndShowGui() {
ImageEdit mainPanel = new ImageEdit();
JFrame frame = new JFrame("ImageEdit");
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.getContentPane().add(mainPanel);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}
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);
}
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.
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 completely stuck on a problem i'm having with this program where I have to draw a city with swing. Basically what i'm trying to do is make it so that the windows don't change every frame. I've tried just about everything I can think of and nothing has worked yet.
Here is the main class that draws everything
import java.applet.Applet;
import java.awt.*;
import java.util.*;
import javax.swing.JFrame;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionListener;
public class Skyline extends JFrame implements MouseMotionListener
{
private int mX, mY; //Mouse cooddinates
private Image mImage; //Image buffer
//private Image mImage2; //Image buffer
private int num = 0;
private Building bldg1 = new Building(305, 110, 30);
private Building bldg2 = new Building(380, 125, 170);
private Building bldg3 = new Building(245, 200, 325);
private Building bldg4 = new Building(470, 170, 555);
private Building bldg5 = new Building(395, 200, 755);
private Background bg = new Background();
public void init ()
{
}
public static void main(String []args)
{
Skyline f = new Skyline();
f.setSize(1017, 661); //Sets size of window
f.setTitle("Skyline"); //Sets title of window
f.show();
}
public void paintOffscreen(Graphics page)
{
//Draws the background
bg.draw(page);
//Moving square
num++;
if (num > 1200)
num = 0;
page.setColor(Color.yellow);
page.fillRect(num,100,100,100);
//Draws the buildings
bldg1.draw(page);
bldg2.draw(page);
bldg3.draw(page);
bldg4.draw(page);
bldg5.draw(page);
//Mouse move square
int s = 100;
page.setColor(Color.yellow);
page.fillRect(mX - s / 2, mY - s / 2, s, s);
repaint();
}
//====================================BUFFER CODE========================================
public void paint(Graphics g)
{
//Clear the buffer
Dimension d = getSize();
checkOffscreenImage();
Graphics offG = mImage.getGraphics();
offG.setColor(getBackground());
offG.fillRect(0, 0, d.width, d.height);
//Save frame to buffer
paintOffscreen(mImage.getGraphics());
//Draw the buffer
g.drawImage(mImage, 0, 0, null);
}
private void checkOffscreenImage()
{
Dimension d = getSize();
if (mImage == null || mImage.getWidth(null) != d.width || mImage.getHeight(null) != d.height)
mImage = createImage(d.width, d.height);
}
//=======================================================================================
//==================================MOUSE MOVE CODE======================================
public Skyline()
{
addMouseMotionListener(this);
setVisible(true);
}
public void mouseMoved(MouseEvent me)
{
Graphics g = getGraphics();
mX = (int) me.getPoint().getX();
mY = (int) me.getPoint().getY();
update(g);
//repaint();
}
public void mouseDragged(MouseEvent me)
{
mouseMoved(me);
}
//=======================================================================================
}
And here is the window class that might be able to be fixed somehow.
import java.applet.Applet;
import java.awt.*;
import java.util.Random;
import javax.swing.JFrame;
public class Windows extends JFrame
{
private Random gen = new Random();
private int height, width, locX;
private int onOff = 0;
public Windows()
{
height = 305;
width = 110;
locX = 30;
}
public Windows(int height, int width, int locX)
{
this.height = height;
this.width= width;
this.locX = locX;
}
public void draw(Graphics page)
{
page.setColor (Color.darkGray);
page.fillRect (locX, 550 - height, width, height);
for (int i = 550 - height + 5; i < 550; i += 15)
{
for (int x = locX + 5; x < locX + width; x += 15)
{
onOff = gen.nextInt(2);
if(onOff == 0)
page.setColor(Color.black);
else
page.setColor(Color.yellow);
page.fillRect (x,i,10,10);
}
}
}
}
Heres the building class just in case.
import java.applet.Applet;
import java.awt.*;
import javax.swing.JFrame;
public class Building extends JFrame
{
private int height, width, locX;
private int onOff;
private Windows windows1;// = new Windows(height, width, locX);
public Building()
{
height = 305;
width = 110;
locX = 30;
windows1 = new Windows(height, width, locX);
}
public Building(int height, int width, int locX)
{
this.width = width;
this.height = height;
this.locX = locX;
windows1 = new Windows(height, width, locX);
}
public void draw(Graphics page)
{
page.setColor (Color.darkGray);
page.fillRect (locX, 550 - height, width, height);
windows1.draw(page);
}
}
And the bg class just to be safe
import java.applet.Applet;
import java.awt.*;
public class Background extends Applet
{
private int height, width;
public Background()
{
height = 400;
width = 2000;
}
public Background(int height, int width)
{
this.height = height;
this.width = width;
}
public void draw(Graphics page)
{
//Draws the sky
page.setColor(Color.cyan);
page.fillRect(0,0,2000,2000);
//Draws the grass
page.setColor (Color.green);
page.fillRect (0,500,width,height);
}
}
A number of things jump out at me immediately...
You're trying to use a off screen buffer, but you're recreating it each time you paint to the screen...
public void paintOffscreen(Graphics page)
{
//Draws the background
bg.draw(page);
//Moving square
num++;
if (num > 1200)
num = 0;
page.setColor(Color.yellow);
page.fillRect(num,100,100,100);
//Draws the buildings
bldg1.draw(page);
bldg2.draw(page);
bldg3.draw(page);
bldg4.draw(page);
bldg5.draw(page);
//Mouse move square
int s = 100;
page.setColor(Color.yellow);
page.fillRect(mX - s / 2, mY - s / 2, s, s);
repaint();
}
Additionally, the last call in the method is to repaint. This is a bad idea. This could cause you paint method to be recalled, again and again and again...
You would be better of rendering the backing buffer only when it needs to change...
public void paint(Graphics g)
{
super.paint(g); // YOU MUST CALL super.paint!!!!
//Clear the buffer
Dimension d = getSize();
checkOffscreenImage();
//Draw the buffer
g.drawImage(mImage, 0, 0, null);
}
private void checkOffscreenImage()
{
Dimension d = getSize();
if (mImage == null || mImage.getWidth(null) != d.width || mImage.getHeight(null) != d.height) {
mImage = createImage(d.width, d.height);
Graphics offG = mImage.getGraphics();
offG.setColor(getBackground());
offG.fillRect(0, 0, d.width, d.height);
//Save frame to buffer
paintOffscreen(offG);
offG.dispose(); // If you create it, you must dispose of it...
}
}
Now, this is going to raise some issues with invalidating the buffer. This can be achieved by overriding invalidate and setting the mImage to null
public void invalidate() {
mImage = null;
super.invalidate();
}
You're extending most of your components from JFrame???
Building, Window and Background do no painting of there own (from the content of Swing), you are simply calling the draw method. There is no need to extend from JFrame or JApplet, they're adding no benefit to your program and are simply confusing the issues.
You should, only very rarely, need to override paint on a top level container like JFrame. You are better off using something like JPanel and override the paintComponent method, if for no other reason, they (top level containers) aren't double buffered.
I would move the logic for Skyline into a JPanel and then add it to a JFrame for displaying - IMHO
UPDATED
I've gone through the code and updated it to work the (basic) way I think it should and found a couple of other things along the way...
This this is a bad idea...
public void mouseMoved(MouseEvent me) {
Graphics g = getGraphics();
mX = (int) me.getPoint().getX();
mY = (int) me.getPoint().getY();
update(g);
//repaint();
}
There should never be any need for you to call update(Graphics), besides, the Graphics context you got is simply a snap shot of the last repaint. This will drastically slow you painting process any way, as it is repeatedly calling paint.
So, this is my take...
public class Skyline extends JFrame {
private int num = 0;
private Building bldg1 = new Building(305, 110, 30);
private Building bldg2 = new Building(380, 125, 170);
private Building bldg3 = new Building(245, 200, 325);
private Building bldg4 = new Building(470, 170, 555);
private Building bldg5 = new Building(395, 200, 755);
private Background bg = new Background();
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException ex) {
} catch (InstantiationException ex) {
} catch (IllegalAccessException ex) {
} catch (UnsupportedLookAndFeelException ex) {
}
Skyline f = new Skyline();
f.setSize(1017, 661); //Sets size of window
f.setTitle("Skyline"); //Sets title of window
f.setVisible(true);
}
});
}
public Skyline() {
setLayout(new BorderLayout());
add(new SkyLinePane());
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
public class SkyLinePane extends JPanel {
private Image mImage; //Image buffer
private boolean painting = false;
private int mX, mY; //Mouse cooddinates
public SkyLinePane() {
addMouseMotionListener(new MouseAdapter() {
#Override
public void mouseMoved(MouseEvent me) {
mX = (int) me.getPoint().getX();
mY = (int) me.getPoint().getY();
repaint();
}
});
}
protected void updateBuffer() {
if (!painting && mImage == null) {
painting = true;
new BackgroundPainter(this).execute();
}
}
//====================================BUFFER CODE========================================
#Override
public void paintComponent(Graphics g) {
Dimension d = getSize();
if (mImage != null) {
g.drawImage(mImage, 0, 0, null);
} else {
updateBuffer();
}
g.setColor(Color.RED);
g.drawOval(mX - 5, mY - 5, 10, 10);
}
//=======================================================================================
protected void setBackground(Image image) {
mImage = image;
painting = false;
repaint();
}
}
public class BackgroundPainter extends SwingWorker<Image, Image> {
private SkyLinePane skyLinePane;
public BackgroundPainter(SkyLinePane skyLinePane) {
this.skyLinePane = skyLinePane;
}
#Override
protected Image doInBackground() throws Exception {
Dimension d = skyLinePane.getSize();
Image backgroundBuffer = null;
if (d.width > 0 && d.height > 0) {
System.out.println("Paint offscreen...");
backgroundBuffer = createImage(d.width, d.height);
Graphics offG = backgroundBuffer.getGraphics();
offG.setColor(getBackground());
offG.fillRect(0, 0, d.width, d.height);
//Save frame to buffer
paintOffscreen(offG);
offG.dispose();
System.out.println("Done Paint offscreen...");
}
return backgroundBuffer;
}
#Override
protected void done() {
try {
skyLinePane.setBackground(get());
} catch (ExecutionException exp) {
exp.printStackTrace();
} catch (InterruptedException exp) {
exp.printStackTrace();
}
}
public void paintOffscreen(Graphics page) {
//Draws the background
bg.draw(page);
//Moving square
num++;
if (num > 1200) {
num = 0;
}
page.setColor(Color.yellow);
page.fillRect(num, 100, 100, 100);
//Draws the buildings
bldg1.draw(page);
bldg2.draw(page);
bldg3.draw(page);
bldg4.draw(page);
bldg5.draw(page);
}
}
//=======================================================================================
public class Windows {
private Random gen = new Random();
private int height, width, locX;
private int onOff = 0;
public Windows() {
height = 305;
width = 110;
locX = 30;
}
public Windows(int height, int width, int locX) {
this.height = height;
this.width = width;
this.locX = locX;
}
public void draw(Graphics page) {
page.setColor(Color.darkGray);
page.fillRect(locX, 550 - height, width, height);
for (int i = 550 - height + 5; i < 550; i += 15) {
for (int x = locX + 5; x < locX + width; x += 15) {
onOff = gen.nextInt(2);
if (onOff == 0) {
page.setColor(Color.black);
} else {
page.setColor(Color.yellow);
}
page.fillRect(x, i, 10, 10);
}
}
}
}
public class Building {
private int height, width, locX;
private int onOff;
private Windows windows1;// = new Windows(height, width, locX);
public Building() {
height = 305;
width = 110;
locX = 30;
windows1 = new Windows(height, width, locX);
}
public Building(int height, int width, int locX) {
this.width = width;
this.height = height;
this.locX = locX;
windows1 = new Windows(height, width, locX);
}
public void draw(Graphics page) {
page.setColor(Color.darkGray);
page.fillRect(locX, 550 - height, width, height);
windows1.draw(page);
}
}
public class Background {
private int height, width;
public Background() {
height = 400;
width = 2000;
}
public Background(int height, int width) {
this.height = height;
this.width = width;
}
public void draw(Graphics page) {
//Draws the sky
page.setColor(Color.cyan);
page.fillRect(0, 0, 2000, 2000);
//Draws the grass
page.setColor(Color.green);
page.fillRect(0, 500, width, height);
}
}
}
Basically, I moved the core rendering of the skyling to it's own panel and used JComponent#paintComponent to render the skyline.
I employed a SwingWorker to off load the rendering of the backing buffer to another thread, allowing the UI to remain responsive while the backing buffer was rendered.