Why does my buffered image not display in my JPanel? - java

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();
}
});
}
}

Related

How to stop background graphics in java?

i try to make a simple java game . ıt work fine but i draw a background but i didn't stop square's color , it always change
i write another class for that and i call it in main but i didn't work it
#SuppressWarnings("serial")
class BackPan extends JFrame{
private JLayeredPane layers;
private JPanel down;
static int width = Board.boardWidth;
static int height = Board.boardHeight;
Random rnd = new Random();
public BackPan(){
layers = new JLayeredPane();
rnd =new Random();
down = new JPanel(){
public void paintComponent(Graphics g){
Graphics2D g2d = (Graphics2D)g;
//***************************************************************
int low = 50;
int high = 255;
for(int i = 0; i<= width; i+=50){
g2d.setColor(new Color(rnd.nextInt(high-low)+low,rnd.nextInt(high-low)+low,rnd.nextInt(high-low)+low));
g2d.fillRect(i, 50, 50, 50);
for(int j = 0; j<= height; j += 50 ){
g2d.setColor(new Color(rnd.nextInt(high-low)+low,rnd.nextInt(high-low)+low,rnd.nextInt(high-low)+low));
g2d.fillRect(i, j, 50, 50);
}
}
}
};
//****************************************************************
down.setBounds(0, 0, width, height);
layers.add(down, new Integer(1));
getContentPane().add(layers, BorderLayout.CENTER);
}
}
Better than using a set seed for your randomization, simply fix the random image by one of two ways:
Create an array of colors that you randomize when needed and then use this array when drawing the background
Even better, simply draw your random colors to a BufferedImage and draw that in the paintComponent method. If this needs to be re-randomized, then re-create the image.
For an example of the latter, note that the image re-randomizes only when the button is pressed (by calling the createBackground() method):
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.event.ActionEvent;
import java.awt.image.BufferedImage;
import javax.swing.*;
#SuppressWarnings("serial")
public class ColorSquares extends JPanel {
public static final int SQR_SIDE = 50;
public static final int COLUMNS = 20;
public static final int ROWS = 16;
private int columns;
private int rows;
private int sqrSide;
private Image backgroundImg;
public ColorSquares(int columns, int rows, int sqrSide) {
this.columns = columns;
this.rows = rows;
this.sqrSide = sqrSide;
backgroundImg = createBackground();
add(new JButton(new AbstractAction("New Background") {
#Override
public void actionPerformed(ActionEvent arg0) {
backgroundImg = createBackground();
repaint();
}
}));
}
public Image createBackground() {
int w = columns * sqrSide;
int h = rows * sqrSide;
BufferedImage img = new BufferedImage(w, h, BufferedImage.TYPE_INT_ARGB);
Graphics g = img.getGraphics();
for (int r = 0; r < rows; r++) {
for (int c = 0; c < columns; c++) {
float hue = (float) Math.random();
float saturation = (float) (Math.random() * 0.5 + 0.5);
float brightness = (float) (Math.random() * 0.5 + 0.5);
Color randColor = Color.getHSBColor(hue, saturation, brightness);
g.setColor(randColor);
int x = c * sqrSide;
int y = r * sqrSide;
g.fillRect(x, y, sqrSide, sqrSide);
}
}
g.dispose();
return img;
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
if (backgroundImg != null) {
g.drawImage(backgroundImg, 0, 0, this);
}
}
#Override
public Dimension getPreferredSize() {
if (isPreferredSizeSet()) {
return super.getPreferredSize();
}
return new Dimension(columns * sqrSide, rows * sqrSide);
}
private static void createAndShowGui() {
JFrame frame = new JFrame("Colors");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(new ColorSquares(COLUMNS, ROWS, SQR_SIDE));
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> createAndShowGui());
}
}
An additional benefit of using a BufferedImage is that it's quicker to draw this than as you're doing it.
The simplest solution would be to remember a constant random seed and set it via rnd.setSeed() each time paintComponent is called. For example:
private final static int SEED = 1000;
rnd.setSeed(SEED);

3D Java programming tutorial isn't working

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.

How to stop one drawImage from overlapping another? - Java

I'm trying to make a tiled background for an RPG using 2D arrays of one drawImage. But for some reason, Java automatically puts the background overlapping the player, I try painting the player before the background, but no difference, Code:
Map code:
Tiles[][] t;
public Map()
{
t = new Tiles[640 / 32][480 / 32];
for (int x = 0; x < 640 / 32; x++)
{
for (int y = 0; y < 480 / 32; y++)
{
t[x][y] = new Tiles(x, y, 32, 32, "./res/grass.png");
}
}
}
public void paint(Graphics g)
{
super.paint(g);
for (int x = 0; x < 640 / 32; x++)
{
for (int y = 0; y < 480 / 32; y++)
{
t[x][y].paint(g);
}
}
this.repaint();
}
Paint code(Which is in other class that extends JPanel):
public void paint(Graphics g)
{
super.paint(g);
p.paint(g);
m.paint(g);
this.repaint();
}
Note: The class which the code above is in extends JPanel, so I made aother class called Window that would add it to the JFrame and then in the static void main, I did all the initializing.
It's hard to tell what you're ding wrong without complete code. I can point somethings out though
Looks like you Map is a JPanel also, since you're calling super.paint. You shouldn't need to make Map a JPanel just make it a regular model class with a drawTiles method that you pass the Graphics context to.
Don't explicitly call the paint method from a component class.
Don't call repaint() from inside the paint method.
Override paintComponent instead for a JPanel
Here's an example I came up with, using some of your code principles while fixing the above mentioned
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.imageio.ImageIO;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
public class PaintTiles extends JPanel {
BufferedImage playerImg;
BufferedImage tileImg;
Map map;
Player player;
int playerX, playerY;
public PaintTiles() throws MalformedURLException, IOException {
playerImg = ImageIO.read(new URL("http://th05.deviantart.net/fs71/PRE/f/2013/055/0/d/super_mario_by_tachin-d5w51ob.png"));
tileImg = ImageIO.read(new URL("https://encrypted-tbn1.gstatic.com/images?q=tbn:ANd9GcTc0ep9G8CyvdJSpBbn8AFdZDlimas7Hcc6jqiVVxBe4nfWJYQy7A"));
map = new Map(tileImg);
playerX = 250;
playerY = 250;
player = new Player(playerX, playerY, 100, 100, playerImg);
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
if (map != null && player != null) {
map.paintTiles(g);
player.paintPlayer(g);
}
}
#Override
public Dimension getPreferredSize() {
return new Dimension(640, 480);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
JFrame frame = new JFrame("Test");
try {
frame.add(new PaintTiles());
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
} catch (IOException ex) {
Logger.getLogger(PaintTiles.class.getName()).log(Level.SEVERE, null, ex);
}
}
});
}
}
class Map {
Image img;
Tile[][] tiles;
int tileSize = 32;
private static final int SCREEN_W = 640;
private static final int SCREEN_H = 480;
int xInc = SCREEN_W / tileSize;
int yInc = SCREEN_H / tileSize;
public Map(Image img) {
this.img = img;
tiles = new Tile[xInc][yInc];
for (int x = 0; x < xInc; x++) {
for (int y = 0; y < yInc; y++) {
tiles[x][y] = new Tile(x * tileSize, y * tileSize, tileSize, tileSize, img);
}
}
}
public void paintTiles(Graphics g) {
if (tiles != null) {
for (Tile[] tile : tiles) {
for (Tile t : tile) {
t.drawTile(g);
}
}
}
}
}
class Player {
int x, y, w, h;
Image player;
public Player(int x, int y, int w, int h, Image player) {
this.x = x;
this.y = y;
this.h = h;
this.w = w;
this.player = player;
}
public void paintPlayer(Graphics g) {
g.drawImage(player, x, y, w, h, null);
}
}
class Tile {
int x, y, w, h;
Image img;
public Tile(int x, int y, int w, int h, Image img) {
this.x = x;
this.y = y;
this.h = h;
this.w = w;
this.img = img;
}
public void drawTile(Graphics g) {
g.drawImage(img, x, y, w, h, null);
}
}

Java 3d game random pixels not appearing

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?

Image of random pixels

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);
}
}

Categories

Resources