package mm.display;

import mm.structures.ColorField;
import mm.structures.ColorPixel;

import javax.swing.*;
import java.awt.*;

public class FieldPanel extends JPanel {

    private ColorField field;
    private ColorPixel[] colors;

    public FieldPanel(ColorField field) {
        this.field = field;
        this.colors = field.getColors();
    }

    @Override
    public void paintComponent(Graphics g) {
        super.paintComponent(g);
        Rectangle bounds = g.getClipBounds();
        int n = field.getN();
        int elementSize = bounds.height / n;
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < n; j++) {
                ColorPixel pixel = colors[field.getElement2D(i, j)];
                g.setColor(pixel.getColor());
                g.fillRect(j * elementSize, i * elementSize, elementSize, elementSize);
            }
        }
    }

    public void setField(ColorField field) {
        this.field = field;
    }

    public void saveAsJPEG(String filename) {
        Dimension size = this.getSize();
        BufferedImage myImage = new BufferedImage(size.width, size.height, BufferedImage.TYPE_INT_RGB);
        Graphics2D g2 = myImage.createGraphics();
        this.paint(g2);
        try {
            OutputStream out = new FileOutputStream(filename);
            JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
            encoder.encode(myImage);
            out.close();
        } catch (Exception e) {
            System.out.println(e);
        }
    }
}

@@ -996,24 +996,26 @@
 filename) %7B%0A
+//
         Dime
@@ -1039,24 +1039,26 @@
 .getSize();%0A
+//
         Buff
@@ -1149,16 +1149,18 @@
 T_RGB);%0A
+//
         
@@ -1197,24 +1197,26 @@
 Graphics();%0A
+//
         this
@@ -1227,16 +1227,18 @@
 nt(g2);%0A
+//
         
@@ -1243,16 +1243,18 @@
   try %7B%0A
+//
         
@@ -1304,24 +1304,26 @@
 (filename);%0A
+//
             
@@ -1383,16 +1383,18 @@
 r(out);%0A
+//
         
@@ -1418,24 +1418,26 @@
 e(myImage);%0A
+//
             
@@ -1445,24 +1445,26 @@
 ut.close();%0A
+//
         %7D ca
@@ -1479,24 +1479,26 @@
 eption e) %7B%0A
+//
             
@@ -1516,24 +1516,26 @@
 println(e);%0A
+//
         %7D%0A  

comment saveAsJPEG method of FieldPanel