Ivan Cern
Ivan Cern

Reputation: 41

Creating images with a java

Hello) Help solve the problem: We need to create a green square image and display it.

I could draw a square, but I need to create it using java. Please help me to do this) That's what I tried to do:

import java.awt.Canvas;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import javax.swing.JFrame;

public class Game extends Canvas {

    private static final long serialVersionUID = 1L;

    private static final int WIDTH = 400;
    private static final int HEIGHT = 400;


    @Override
    public void paint(Graphics g) {
        super.paint(g);

        int w = 10;
        int h = 10;
        int type = BufferedImage.TYPE_INT_ARGB;

        BufferedImage image = new BufferedImage(w, h, type);

        int color = 257; // RGBA value, each component in a byte

        for (int x = 1; x < w; x++) {
            for (int y = 1; y < h; y++) {
                image.setRGB(x, y, color);

                g.drawImage(image, 0, 0, getWidth(), getHeight(), null);
            }
        }
    }

    public static void main(String[] args) {
        JFrame frame = new JFrame();

        frame.setSize(WIDTH, HEIGHT);
        frame.add(new Game());

        frame.setVisible(true);
    }
}

But nothing is displayed (

Let me remind the goal - to create a picture in the form of green squares, help to make it)

Upvotes: 0

Views: 1853

Answers (3)

Sage
Sage

Reputation: 15438

if you want to create an Image with rectangle containing it, first create the image, draw on it using it's graphics. I am writing code snippets for you:

BufferedImage image = new BufferedImage(w, h, BufferedImage.TYPE_INT_ARGB);
Graphics g = image.getGraphics();
g.setColor(Color.blue);
g.fillRect(0, 0, image.getWidth(), image.getHeight());

This will produce an image with Blue rectangle.

Upvotes: 0

MadProgrammer
MadProgrammer

Reputation: 347332

The simplest approach would be to simply use the graphics API...

@Override
public void paint(Graphics g) {
    super.paint(g);

    int w = 10;
    int h = 10;
    g.setColor(Color.GREEN);
    g.fillRect(0, 0, width, height);
}

But something tells me this isn't what you want, but it does form the basics for what you need to achieve your result.

Start by making image a instance field...

private BufferedImage image;

Then you need to create the image...

int type = BufferedImage.TYPE_INT_ARGB;
image = new BufferedImage(w, h, type);
Graphics2D g2d = image.createGraphics();
g2d.setColor(Color.GREEN);
g2d.fillRect(0, 0, w, h);
g2d.dispoe();

Then in you paint method, you need to draw the image...

g.drawImage(image, x, y, this);

Take a look at the 2D Graphics trail for mor details

Upvotes: 1

Related Questions