Java: basic construction, drawing a point / point / pixel

I just need a panel inside which I can draw. I want to draw pixel by pixel .

ps: I do not need lines / circles of other primitives. pps: the graphics library doesn't really matter, it can be awt, swing, qt .. whatever. I just want to have something that Bufferedimage usually represents, or something like where you set the colors of single pixels and then display them.

+5
source share
5 answers

represented by Bufferedimage ..

I suggest BufferedImagefor this, displayed ..

.. - , , .

.. JLabel - .

8Biec.png

, BufferedImage, setRGB(..).

+2

, , , , .

BufferedImage.setRGB(..) - , , , RGB ( ). , IE- . , , .

, , RGB BufferedImage, .

Java 7, , , J2D , - , , , , .

+2

:

// Create the new image needed
img = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB );

for ( int rc = 0; rc < height; rc++ ) {
  for ( int cc = 0; cc < width; cc++ ) {
    // Set the pixel colour of the image n.b. x = cc, y = rc
    img.setRGB(cc, rc, Color.BLACK.getRGB() );
  }//for cols
}//for rows


paintComponent (Graphics g)

((Graphics2D)g).drawImage(img, <args>)
+2

- , GraphicsColor drawLine. :

public void paintComponent(Graphics g) {
    super.paintComponent(g);       

    // Set the colour of pixel (x=1, y=2) to black
    g.setColor(Color.BLACK);
    g.drawLine(1, 2, 1, 2);
}

, . BufferedImage.

0

, , Java-, Screen:

public class Screen {

    private int width, height;  

    public int[] pixels;

    public Screen(int width, int height) {
        this.width = width;
        this.height = height;

        pixels = new int[width * height];
    }

    public void render() {
        for(int y = 0; y < height; y++) {
            for(int x = 0; x < width; x++) {
                pixels[x + y * width] = 0xFFFFFF; //make every pixel white
            }
        }
    }

public void clear() {
            for(int i = 0; i < pixels.length; i++) {
                    pixels[i] = 0; //make every pixel black
            }
    }

}

:

    private Screen screen;

    private BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
    private int[] pixels = ((DataBufferInt) image.getRaster().getDataBuffer()).getData();

    public void render() {
         BufferStrategy bs = getBufferStrategy();
        if (bs == null) {
            createBufferStrategy(3);
            return;
        }

        screen.clear();
        screen.render();

         for(int i = 0; i < pixels.length; i++) {
            pixels[i] = screen.pixels[i];
         }

        Graphics g = bs.getDrawGraphics();
        g.drawImage(image, 0, 0, getWidth(), getHeight(), null);
        g.dispose();
        bs.show();
}

, .

0

All Articles