Package com.vst.webapp.util

Source Code of com.vst.webapp.util.PainterApplet

package com.vst.webapp.util;


import com.vst.model.*;
import org.hibernate.Hibernate;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.springframework.orm.ObjectRetrievalFailureException;

import javax.imageio.IIOImage;
import javax.imageio.ImageIO;
import javax.imageio.ImageWriteParam;
import javax.imageio.ImageWriter;
import javax.imageio.plugins.jpeg.JPEGImageWriteParam;
import javax.imageio.stream.ImageOutputStream;
import javax.swing.*;
import java.applet.Applet;
import java.awt.*;
import java.awt.event.*;
import java.awt.image.BufferedImage;
import java.awt.image.RenderedImage;
import java.io.*;
import java.sql.Blob;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.Properties;


/**
* Created by IntelliJ IDEA.
* User: ALEXEI
* Date: 29.02.2008
* Time: 1:17:00
* To change this template use File | Settings | File Templates.
*/


public class PainterApplet extends Applet implements MouseListener, MouseMotionListener, KeyListener {

    //constructionDefect
    //constructionExample detailSymbol levelPlan   objectConstruction


    boolean sizeLineFlag = false;
    int sizeLinePoiuntCount = 0;

   SizeLine[] sizeLineList;
   TextLine[] textLineList;

    MyPoint firstPointInSizeLine=new MyPoint();
    MyPoint secondPointInSizeLine=new MyPoint();

    JFrame sizeLineCountFrame;
    JTextField[] textFieldSizeLineValues;

    int RIGHT_MOUSE_X = 0;
    int RIGHT_MOUSE_Y = 0;

    JPopupMenu popupMenu = new JPopupMenu();

    JMenuItem menuCopy = new JMenuItem("Копировать");
    JMenuItem menuInsert = new JMenuItem("Вставить");
    JMenuItem menuMove = new JMenuItem("Переместить элемент");
    JMenuItem menuUnGroup = new JMenuItem("Разгруппировать");
    JMenuItem menuGroup = new JMenuItem("Сгруппировать");
    JMenuItem menuDelete = new JMenuItem("Удалить");
    JMenuItem menuUpdateDefect = new JMenuItem("Изменить данные дефекта");
    JMenuItem menuUpdatePoint = new JMenuItem("Изменить точку замера");


    int SCREEN_HEIGHT = (int) Toolkit.getDefaultToolkit().getScreenSize().getHeight();

    int SCREEN_WEIGHT = (int) Toolkit.getDefaultToolkit().getScreenSize().getWidth();


    JFrame defectFrame;
    JFrame textFrame;


    JFrame pointFrame;
    JPanel paramPanel = new JPanel();

    private int baseCountX = 0;
    private int baseCountY = 0;

    private int minCountForDiapazoneX = 0;
    private int minCountForDiapazoneY = 0;
    private int maxCountForDiapazoneX = 0;
    private int maxCountForDiapazoneY = 0;


    private int IMAGE_SIZE_VERT = 839;
    private int IMAGE_SIZE_HORZ = 1727;


    private int stilusControl = 0;
    private boolean ctrlPressed = false;
    private int HISTORY_STEP = 15;

    private int lastHistory = 0;
    private int nowHistory = 0;


    private Session session = null;
    private Strength strength;
    private ObjectPicture objectPicture = new ObjectPicture();
    private double mashtab = 1;
    private int sizeLinePosition = 0;
    private int paperX = 0;
    private int paperY = 0;

    private int paperScrollX = 0;
    private int paperScrollY = 0;
    private int x1;
    private int oldX;
    private int oldY;
    private Brush brush = new Brush();
    private SizeLine sizeLine = new SizeLine();
    private boolean pressed;
    private int x2;
    private int y1;
    private int y2;
    private boolean selected;
    private boolean loaded = false;
    private GlobalPicture nowObject = null;

    java.util.List listDefectType = new ArrayList();
    java.util.List listDefectZones = new ArrayList();
    java.util.List listDefVar = new ArrayList();
    java.util.List listReason = new ArrayList();
    java.util.List listDanger = new ArrayList();

    private java.util.List detailList = new ArrayList();
    private java.util.List defectList = new ArrayList();

    private java.util.List defctParamList = new ArrayList();
    private java.util.List constExmpList = new ArrayList();


    private final int appletWidth = 800;
    private final int appletWidthWitPanel = 1000;
    private final int appletHeight = 400;


    JTextField textField = new JTextField();


    private String loadPath;
    private String historyPath;
    private String historyFile;
    private String savePath;
    private String savePathImage;
    private String fullPath;
    private Image image;


    BufferedImage realBI;
    private int strengthPointNum = 0;
    private int defectNum = 0;

    private Color backColor = Color.WHITE;

    private Cursor tmpCursor;


    private Color toolColors[] = {
            //    Color.WHITE,
            Color.RED,
            Color.ORANGE,
            //   Color.YELLOW,
            Color.GREEN,
            Color.BLUE,
            Color.MAGENTA,
            Color.BLACK,

    };

    private Button colorButton[] = new Button[toolColors.length];


    /*  private Button copyButton = new Button("C");
        private Button insertButton = new Button("I");
    */
    private Button prewHistory = new Button("<<");
    private Button nextHistory = new Button(">>");

    private String previousImageName = "";

    private Panel panel;
    private Panel vertScrollPanel;
    private Panel horisScrollPanel;
    //private Panel panelFooter;


    private int IMAGE_HORZ = 705;
    private int IMAGE_VERT = 450;

    private Scrollbar vertScroll = new Scrollbar(Scrollbar.VERTICAL, 0, 60, 0, IMAGE_SIZE_VERT - IMAGE_VERT - 60);
    private Scrollbar horisScroll = new Scrollbar(Scrollbar.HORIZONTAL, 0, 90, 0, IMAGE_SIZE_HORZ - IMAGE_HORZ - 90);


    // TOOL MODES
    private final int ERASE = 0;
    private final int PEN = 1;
    private final int LINE = 2;
    private final int RECT = 3;
    private final int ELLIPSE = 4;
    private final int SIZELINE = 5;
    private final int TEXT = 6;
    private final int SELECT = 8;


    private final int MOVE = 0;
    private final int CHANGE_SIZE1 = 1;
    private final int CHANGE_SIZE2 = 2;
    private final int CHANGE_SIZE3 = 3;
    private final int CHANGE_SIZE4 = 4;
    private final int ROTATE = 5;
    private final int MOVEPAPER = 7;

    private final int NOTHING = -1;
    private int objectAction = NOTHING;

    private int toolMode = SELECT; // default tool
    private Color toolColor = Color.BLACK;
    private Label selectedColorLabel = new Label("<-");


    private boolean rotFlag = false;
    private double tmpRoteteRadius = 0;


    Button pen = new Button("Кисть");
    Button line = new Button("Линия");
    Button rect = new Button("Прям-к");
    Button ellipse = new Button("Эллипс");
    Button sizeline = new Button("Размеры");
    Button text = new Button("Текст");

    Choice choiceEskizDetail = new Choice();
    Label labelForEskizDetail = new Label("Конструкции");
    Button buttonForEskizDetail = new Button("+");


    Button buttonAddDataDefect = new Button("+");

    TextField textForMashtab = new TextField("100");
    TextField unVisibleText = new TextField("");
    Label labelForMashtab = new Label("Масштаб");

    Button buttonPoint = new Button("Добавить точку замера ");


    JTextField texPoint = new JTextField("");
    JLabel labelPoint = new JLabel("Прочность в этой точке");
    JButton buttonAddPoit = new JButton("Добавить");
    JButton buttonAddPoitUpdate = new JButton("Изменить");


    Choice choiceEskizDefect = new Choice();
    Label labelForEskizDefect = new Label("Дефект");


    JButton buttonForEskizDefect = new JButton("Добавить дефект");
    JButton buttonForEskizDefectUpdate = new JButton("Изменить дефект");

    JComboBox choiceConstZone = new JComboBox();


    JComboBox choiceDanger = new JComboBox();

    JComboBox choiceDefType = new JComboBox();

    JComboBox choiceDefVar = new JComboBox();

    JComboBox choiceReason = new JComboBox();


    JTextField textDiffReason = new JTextField("");

    JTextField[] paramText = new JTextField[10];
    JLabel[] paramLabel = new JLabel[10];

    JComboBox examplesCheck = new JComboBox();


    JLabel labeName = new JLabel("Привязка экземпляра к оси");
    JTextField textName = new JTextField("");


    //  Button refreshButton = new Button("Обновить");
    Button saveButton = new Button("Сохранить");
    /*  Button select = new Button("Переместить");
        Button delete = new Button("Удалить");
        Button group = new Button("Сгруппировать");
        Button unGroup = new Button("Разгруппировать");
    */

    private final Color unPressedColor = Color.lightGray;
    private final Color pressedColor = Color.GREEN;


    private void unPaintAllButtons() {
        pen.setBackground(unPressedColor);
        line.setBackground(unPressedColor);
        rect.setBackground(unPressedColor);
        ellipse.setBackground(unPressedColor);
        sizeline.setBackground(unPressedColor);
        text.setBackground(unPressedColor);
    }

    //TODO get better way for interracting with dao methods from applet

    private String getPointNumberByObjectConstructionId(Integer objectConstructionId) {
        try {
            Integer number = (Integer) (((Integer) session.createQuery("select max(pointRelativeNumber) from Strength where exampleId in (select exampleId from ConstructionExample where objectConstructionId=?)").setInteger(0, objectConstructionId.intValue()).uniqueResult()).intValue() + 1);
            return number.toString();
        } catch (Exception e) {
            return "0";
        }

    }

    private String getDefectNumberByObjectConstructionId(Integer objectConstructionId) {
        try {
            Integer number = (Integer) (((Integer) session.createQuery("select max(pointRelativeNumber) from ConstructionDefect where exampleId in (select exampleId from ConstructionExample where objectConstructionId=?)").setLong(0, objectConstructionId.longValue()).uniqueResult()).intValue() + 1);
            return number.toString();
        } catch (Exception e) {
            return "0";
        }

    }


    public class JPEGWriter {

        public void write(RenderedImage image, float quality, File file) throws IOException {
            ImageWriter writer = null;
            Iterator iter = ImageIO.getImageWritersByFormatName("JPEG");
            if (!iter.hasNext())
                throw new IOException("No Writers Available");
            writer = (ImageWriter) iter.next();
            if (file.exists())
                file.delete();
            ImageOutputStream ios = ImageIO.createImageOutputStream(file);
            writer.setOutput(ios);
            JPEGImageWriteParam iwp = new JPEGImageWriteParam(null);
            iwp.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
            iwp.setCompressionQuality(quality);
            writer.write(null, new IIOImage(image, null, null), iwp);
            ios.flush();
            writer.dispose();
            ios.close();
        }

    }

    JPEGWriter jpegWriter = new JPEGWriter();


    public Cursor getTmpCursor() {
        return tmpCursor;
    }

    public void setTmpCursor(Cursor tmpCursor) {
        this.tmpCursor = tmpCursor;
    }


    public boolean isPressed() {
        return pressed;
    }

    public void setPressed(boolean pressed) {
        this.pressed = pressed;
    }

    public String getSavePath() {
        return savePath;
    }

    public String getFullPath() {
        return fullPath;
    }

    public void setFullPath(String fullPath) {
        this.fullPath = fullPath;
    }

    public void setSavePath(String savePath) {
        this.savePath = savePath;
    }

    public String getLoadPath() {
        return loadPath;
    }

    public void setLoadPath(String loadPath) {
        this.loadPath = loadPath;
    }

    public Image getImage() {
        return image;
    }

    public void setImage(Image image) {
        this.image = image;
    }


    public int getX1() {
        return x1;
    }

    public void setX1(int x1) {
        this.x1 = x1;
    }

    public int getX2() {
        return x2;
    }

    public void setX2(int x2) {
        this.x2 = x2;
    }

    public int getY1() {
        return y1;
    }

    public void setY1(int y1) {
        this.y1 = y1;
    }

    public int getY2() {
        return y2;
    }

    public void setY2(int y2) {
        this.y2 = y2;
    }

    public boolean isSelected() {
        return selected;
    }

    public void setSelected(boolean selected) {
        this.selected = selected;
    }


    public void init() {

        System.out.println("SCREEN_HEIGHT = " + SCREEN_HEIGHT);
        System.out.println("SCREEN_WEIGHT = " + SCREEN_WEIGHT);

        prewHistory.setEnabled(false);
        nextHistory.setEnabled(false);

        unPaintAllButtons();

        session = getSession().openSession();

        detailList = session.createQuery("from DetailSymbol detailSymbol where detailSymbol.type=?").setString(0, String.valueOf("detail")).list();
        setValuesDetail(detailList, choiceEskizDetail);

        if (getParameter("constructionId") != null && !getParameter("constructionId").trim().equals("")) {


            defectList = session.createQuery("from DetailSymbol detailSymbol where detailSymbol.type=? and detailSymbol.defectType.defectTypeId in (select defectType.defectTypeId from DefectType defectType where defectType.constructionTypes.constructionTypeId=" + getParameter("constructionId") + ")").setString(0, String.valueOf("defect")).list();
            if (getParameter("objectConstructionId") != null && !getParameter("objectConstructionId").trim().equals("")) {
                constExmpList = getConstructionExample(Long.valueOf(getParameter("objectConstructionId")));
                setChoice(constExmpList, examplesCheck);
            }
            setValuesDetail(defectList,
                    choiceEskizDefect);
            textName.setText("");


        } else {
            labelForEskizDefect.setVisible(false);
            choiceEskizDefect.setVisible(false);
            buttonAddDataDefect.setVisible(false);
            buttonPoint.setVisible(false);
        }


        addMouseListener(this);
        addMouseMotionListener(this);
        addKeyListener(this);

        fullPath = getParameter("fullPath");
        loadPath = fullPath + "blank.jpg";
        historyPath = fullPath + "history\\";
        historyFile = "step.JPG";
        savePath = fullPath + getParameter("savePath");
        savePathImage = fullPath + getParameter("savePathImage");
        previousImageName = getParameter("user") + "_prev.jpg";


        for (int i = 0; i < HISTORY_STEP; i++) {
            ObjectOutputStream out = null;
            try {
                out = new ObjectOutputStream(new FileOutputStream(historyPath + i + historyFile));
                out.writeObject(new ObjectPicture());
                out.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }


        clearImage();


        try {
            System.out.println("savePath = " + savePath);
            ObjectInputStream in = new ObjectInputStream(new FileInputStream(savePath));
            try {
                objectPicture = (ObjectPicture) in.readObject();
                if (objectPicture != null) {
                    objectPicture.drawObjects(image.getGraphics(), paperScrollX, paperScrollY);
                    getGraphics().drawImage(image, 0, 0, null);
                    save();
                }
            } catch (ClassNotFoundException e) {
                System.out.println("ClassNotFoundException");
            }
            in.close();
        } catch (IOException e) {
            System.out.println("IOException");
        }


        if (getParameter("type") != null && getParameter("type").equals("level")) {
            createDialog1();
        }


        this.setSize(appletWidth, appletHeight);
        this.setLayout(null);


        saveButton.setBounds(5, 5, 70, 20);

        prewHistory.setBounds(5, 30, 30, 20);
        nextHistory.setBounds(40, 30, 30, 20);

        int boundy = 55;
        int dbound = 25;

        pen.setBounds(5, boundy, 70, 20);
        line.setBounds(5, boundy += dbound, 70, 20);
        rect.setBounds(5, boundy += dbound, 70, 20);
        ellipse.setBounds(5, boundy += dbound, 70, 20);
        sizeline.setBounds(5, boundy += dbound, 70, 20);
        text.setBounds(5, boundy += dbound, 70, 20);


        panel = new Panel();
        panel.setLayout(null);
        panel.setBackground(SystemColor.control);


        panel.setBounds(0, 0, 75, 600);
        panel.add(saveButton);
        panel.add(prewHistory);
        panel.add(nextHistory);

        panel.add(pen);
        panel.add(line);

        panel.add(rect);
        panel.add(ellipse);
        panel.add(sizeline);
        panel.add(text);

        boundy += 10;

        int h = 0;
        for (int i = 0; i < toolColors.length - 1; i += 2) {
            colorButton[i] = new Button();
            colorButton[i].setSize(25, 25);
            colorButton[i].setBounds(5, boundy + ((i + 1) / 2) * 30 + 50, 25, 25);
            colorButton[i].setBackground(toolColors[i]);
            panel.add(colorButton[i]);
            colorButton[i + 1] = new Button();
            colorButton[i + 1].setSize(25, 25);
            colorButton[i + 1].setBounds(35, boundy + ((i + 1) / 2) * 30 + 50, 25, 25);
            colorButton[i + 1].setBackground(toolColors[i + 1]);
            panel.add(colorButton[i + 1]);
            h++;
        }

        selectedColorLabel.setBackground(Color.BLACK);
        panel.add(selectedColorLabel);

        vertScrollPanel = new Panel();
        vertScrollPanel.setLayout(null);
        vertScrollPanel.setBackground(SystemColor.control);
        vertScrollPanel.setBounds(appletWidth - 20, 0, 250, 650);


        vertScroll.setBounds(0, 0, 20, this.appletHeight);

        labelForMashtab.setBounds(35, 10, 70, 20);
        unVisibleText.setBounds(110, 10, 50, 20);
        textForMashtab.setBounds(110, 10, 50, 20);
        unVisibleText.setFocusable(true);
        unVisibleText.requestFocus();

        labelForEskizDetail.setBounds(35, 35, 100, 20);
        choiceEskizDetail.setBounds(35, 60, 100, 20);
        buttonForEskizDetail.setBounds(140, 60, 30, 20);

        labelForEskizDefect.setBounds(35, 80, 100, 20);
        choiceEskizDefect.setBounds(35, 105, 100, 20);
        buttonAddDataDefect.setBounds(140, 105, 30, 20);

        buttonPoint.setBounds(35, 135, 150, 20);

        vertScrollPanel.add(textForMashtab);
        vertScrollPanel.add(unVisibleText);
        vertScrollPanel.add(labelForMashtab);
        vertScrollPanel.add(choiceEskizDetail);
        vertScrollPanel.add(labelForEskizDetail);
        vertScrollPanel.add(buttonForEskizDetail);
        vertScrollPanel.add(buttonAddDataDefect);
        vertScrollPanel.add(choiceEskizDefect);
        vertScrollPanel.add(labelForEskizDefect);
        vertScrollPanel.add(buttonPoint);


        vertScroll.addMouseListener(new MouseListener() {
            public void mouseClicked(MouseEvent e) {
            }

            public void mousePressed(MouseEvent e) {
            }

            public void mouseReleased(MouseEvent e) {
                objectPicture.drawObjects(image.getGraphics(), paperScrollX, paperScrollY);
                getGraphics().drawImage(image, paperX, paperY, null);
            }

            public void mouseEntered(MouseEvent e) {
            }

            public void mouseExited(MouseEvent e) {
            }
        });

        horisScroll.addMouseListener(new MouseListener() {
            public void mouseClicked(MouseEvent e) {
            }

            public void mousePressed(MouseEvent e) {
            }

            public void mouseReleased(MouseEvent e) {
                objectPicture.drawObjects(image.getGraphics(), paperScrollX, paperScrollY);
                getGraphics().drawImage(image, paperX, paperY, null);
            }

            public void mouseEntered(MouseEvent e) {
            }

            public void mouseExited(MouseEvent e) {
            }
        });


        vertScroll.addAdjustmentListener(new AdjustmentListener() {
            public void adjustmentValueChanged(AdjustmentEvent e) {
                paperScrollY = e.getValue();
            }
        });

        vertScrollPanel.add(vertScroll);
        horisScrollPanel = new Panel();
        horisScrollPanel.setLayout(null);
        horisScrollPanel.setBackground(SystemColor.control);
        horisScrollPanel.setBounds(panel.getWidth(), this.appletHeight, appletWidth - panel.getWidth() - 20, 150);
        horisScroll.setBounds(0, 0, horisScrollPanel.getWidth(), 20);

        horisScroll.addAdjustmentListener(new AdjustmentListener() {
            public void adjustmentValueChanged(AdjustmentEvent e) {
                paperScrollX = e.getValue();
            }
        });


        horisScrollPanel.add(horisScroll);


        System.out.println(getParameter("appletName"));

        Label l = new Label(getParameter("appletName"));
        l.setBounds(15, 55, 300, 40);
        horisScrollPanel.add(l);

        //PopUpMenu!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!

        menuCopy.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                try {
                    copy();
                } catch (IOException e1) {
                    e1.printStackTrace()//To change body of catch statement use File | Settings | File Templates.
                }
            }
        });


        menuInsert.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                try {
                    insert(RIGHT_MOUSE_X, RIGHT_MOUSE_Y);
                } catch (IOException e1) {
                    e1.printStackTrace()//To change body of catch statement use File | Settings | File Templates.
                }
            }
        });

        menuMove.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                try {
                    copy();
                } catch (IOException e1) {
                    e1.printStackTrace()//To change body of catch statement use File | Settings | File Templates.
                }
            }
        });

        menuUnGroup.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                if (nowObject != null && (nowObject instanceof Symbols)) {
                    Symbols symbols = (Symbols) nowObject;
                    if (symbols.getType().equals("detail")) {

                        objectPicture.deleteObject(symbols);
                        java.util.List list = symbols.list;
                        for (int i = 0; i < list.size(); i++) {
                            objectPicture.addObject((GlobalPicture) list.get(i));
                        }

                        menuUnGroup.setEnabled(false);
                        menuGroup.setEnabled(false);

                        for (int i = 0; i < objectPicture.getObjectList().size(); i++) {
                            GlobalPicture globalPicture = (GlobalPicture) objectPicture.getObjectList().get(i);
                            globalPicture.setUnSelectPosition();
                        }

                        nowObject = null;
                        objectPicture.drawObjects(image.getGraphics(), paperScrollX, paperScrollY);
                        getGraphics().drawImage(image, paperX, paperY, null);

                    }

                }
            }
        });

        menuGroup.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                objectPicture.moveObjectInSymbol();

                menuUnGroup.setEnabled(false);
                menuGroup.setEnabled(false);


                for (int i = 0; i < objectPicture.getObjectList().size(); i++) {
                    GlobalPicture globalPicture = (GlobalPicture) objectPicture.getObjectList().get(i);
                    globalPicture.setUnSelectPosition();
                }

                objectPicture.drawObjects(image.getGraphics(), paperScrollX, paperScrollY);
                getGraphics().drawImage(image, paperX, paperY, null);

            }
        });

        menuDelete.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                deleteObject();

            }
        });


        menuUpdateDefect.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                createDefectFrame((Symbols) nowObject);
            }
        });

        menuUpdatePoint.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                showPointDialog((Symbols) nowObject);
            }
        });


        popupMenu.add(menuCopy);
        popupMenu.add(menuInsert);
        popupMenu.add(menuMove);
        popupMenu.add(menuGroup);
        popupMenu.add(menuUnGroup);
        popupMenu.add(menuDelete);
        popupMenu.add(menuUpdateDefect);
        popupMenu.add(menuUpdatePoint);

        /*textField = new TextField();
        textField.setBounds(80, 5, this.appletWidth - 200, 20);
        textField.setVisible(true);*/

        //  panelFooter.add(textField);


        this.add(panel);
        this.add(vertScrollPanel);
        this.add(horisScrollPanel);


        for (int i = 0; i < toolColors.length; i++) {
            final int k = i;
            colorButton[i].addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent event) {
                    toolColor = colorButton[k].getBackground();

                    selectedColorLabel.setBounds(
                            (int) colorButton[k].getLocation().getX() - 2,
                            (int) colorButton[k].getLocation().getY() - 2,
                            colorButton[k].getWidth() + 4,
                            colorButton[k].getHeight() + 4);

                    if (nowObject != null) {
                        nowObject.setColor(colorButton[k].getBackground());
                        objectPicture.drawObjects(image.getGraphics(), paperScrollX, paperScrollY);
                        getGraphics().drawImage(image, paperX, paperY, null);
                        if (nowObject.getPosition() == 0) {
                            nowObject.paintSelect(getGraphics(), paperScrollX, paperScrollY);
                        } else if (nowObject.getPosition() == 1) {
                            nowObject.paintRotate(getGraphics(), paperScrollX, paperScrollY);
                        }

                    }

                }
            }
            );
        }

        /* refreshButton.addActionListener(new

                        ActionListener() {
                            public void actionPerformed(ActionEvent event) {
                                getGraphics().drawImage(image, paperX, paperY, null);
                            }
                        }
                );
        */
        saveButton.addActionListener(new

                ActionListener() {
                    public void actionPerformed(ActionEvent event) {

                        saveImage();

                    }
                }
        );

        buttonPoint.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                /* showStrengthPanel(true);
                texPoint.setEnabled(true);
                labelPoint.setEnabled(true);
                buttonAddPoit.setEnabled(true);*/


                if (getParameter("objectConstructionId") != null && !getParameter("objectConstructionId").trim().equals("")) {
                    showPointDialog(null);
                }


            }
        });

        /* group.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {


                objectPicture.moveObjectInSymbol();

                unGroup.setEnabled(false);
                group.setEnabled(false);


                for (int i = 0; i < objectPicture.getObjectList().size(); i++) {
                    GlobalPicture globalPicture = (GlobalPicture) objectPicture.getObjectList().get(i);
                    globalPicture.setUnSelectPosition();
                }

                objectPicture.drawObjects(image.getGraphics(), paperScrollX, paperScrollY);
                getGraphics().drawImage(image, paperX, paperY, null);

            }
        });


        unGroup.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {


                if (nowObject != null && (nowObject instanceof Symbols)) {
                    Symbols symbols = (Symbols) nowObject;
                    if (symbols.getType().equals("detail")) {

                        objectPicture.deleteObject(symbols);
                        java.util.List list = symbols.list;
                        for (int i = 0; i < list.size(); i++) {
                            objectPicture.addObject((GlobalPicture) list.get(i));
                        }
                        unGroup.setEnabled(false);
                        group.setEnabled(false);

                        for (int i = 0; i < objectPicture.getObjectList().size(); i++) {
                            GlobalPicture globalPicture = (GlobalPicture) objectPicture.getObjectList().get(i);
                            globalPicture.setUnSelectPosition();
                        }

                        nowObject = null;
                        objectPicture.drawObjects(image.getGraphics(), paperScrollX, paperScrollY);
                        getGraphics().drawImage(image, paperX, paperY, null);

                    }

                }

            }
        });*/

        buttonAddPoit.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {

                if (texPoint.getText().equals("") || texPoint.getText().equals("Введите значение")) {
                    texPoint.setText("Введите значение");
                } else {

                    int j = examplesCheck.getSelectedIndex();
                    if (j >= 0 && j <= constExmpList.size()) {

                        ConstructionExample constructionExample = createStrengthAndTakeConstructionExample(j);

                        Symbols symbols = createStrength();

                        symbols.setExample(constructionExample);
                        symbols.setStrength(strength);
                        symbols.setActivity("new");
                        symbols.setType("point");

                        objectPicture.addObject(symbols);
                        objectPicture.drawObjects(image.getGraphics(), paperScrollX, paperScrollY);
                        getGraphics().drawImage(image, paperX, paperY, null);

                        save();


                        nowObject = symbols;
                        symbols.paintSelect(getGraphics(), paperScrollX, paperScrollY);


                        texPoint.setText("");
                        pointFrame.dispose();


                    } else {
                    }


                }


            }
        });

        buttonAddPoitUpdate.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {

                if (texPoint.getText().equals("") || texPoint.getText().equals("Введите значение")) {
                    texPoint.setText("Введите значение");
                } else {

                    int j = examplesCheck.getSelectedIndex();
                    if (j >= 0 && j <= constExmpList.size()) {

                        deleteObject();

                        ConstructionExample constructionExample = createStrengthAndTakeConstructionExample(j);


                        Symbols symbols = updateStrength(constructionExample);
                        objectPicture.addObject(symbols);
                        objectPicture.drawObjects(image.getGraphics(), paperScrollX, paperScrollY);
                        getGraphics().drawImage(image, paperX, paperY, null);
                        save();

                        nowObject = symbols;
                        symbols.paintSelect(getGraphics(), paperScrollX, paperScrollY);

                        texPoint.setText("");

                        JOptionPane.showMessageDialog(defectFrame, "Данные по точке завмера изменены");

                        pointFrame.dispose();


                    }

                }


            }
        });


        nextHistory.addActionListener(new ActionListener() {


            public void actionPerformed(ActionEvent e) {

                nowHistory = (nowHistory + 1) % HISTORY_STEP;

                returnPicture();
            }
        });

        prewHistory.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {

                nowHistory = (nowHistory - 1);
                if (nowHistory < 0) {
                    nowHistory += HISTORY_STEP;
                }
                returnPicture();
            }
        });

        textForMashtab.addKeyListener(new KeyListener() {

            public void keyTyped(KeyEvent e) {
            }

            public void keyPressed(KeyEvent e) {
            }

            public void keyReleased(KeyEvent e) {

                if (e.getKeyCode() == 10) {
                    String s = textForMashtab.getText();

                    System.out.println("s = " + s);

                    if (testText(s)) {

                        objectPicture.setScale(Double.valueOf(textForMashtab.getText()).doubleValue() / 100);
                        mashtab = Double.valueOf(textForMashtab.getText()).doubleValue() / 100;
                        vertScroll = new Scrollbar(Scrollbar.VERTICAL, paperScrollY, 60, 0, (IMAGE_SIZE_VERT - (int) (IMAGE_VERT / mashtab) - 60));
                        horisScroll = new Scrollbar(Scrollbar.HORIZONTAL, paperScrollX, 90, 0, (IMAGE_SIZE_HORZ - (int) (IMAGE_HORZ / mashtab) - 90));
                        objectPicture.drawObjects(image.getGraphics(), paperScrollX, paperScrollY);
                        getGraphics().drawImage(image, paperX, paperY, null);

                    } else {

                        textForMashtab.setText("Введите число!!!");

                    }

                }
            }
        });


        unVisibleText.addKeyListener(new KeyListener() {

            public void keyTyped(KeyEvent e) {


                if (ctrlPressed && e.getKeyChar() == 'z') {


                    nowHistory = (nowHistory - 1);
                    if (nowHistory < 0) {
                        nowHistory += HISTORY_STEP;
                    }
                    returnPicture();
                }
                if (ctrlPressed && e.getKeyChar() == 'c') {

                    try {
                        copy();
                    } catch (IOException e1) {
                        e1.printStackTrace()//To change body of catch statement use File | Settings | File Templates.
                    }

                }
                if (ctrlPressed && e.getKeyChar() == 'v') {

                    try {
                        insert();
                    } catch (IOException e1) {
                        e1.printStackTrace()//To change body of catch statement use File | Settings | File Templates.
                    }

                }


            }

            public void keyPressed(KeyEvent e) {

                if (e.getKeyCode() == 17) {
                    ctrlPressed = true;
                }

                if (e.getKeyCode() == 127) {
                    deleteObject();
                }


            }

            public void keyReleased(KeyEvent e) {
                if (e.getKeyCode() == 17) {
                    ctrlPressed = false;
                }
            }
        });


        buttonForEskizDefectUpdate.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                System.out.println("Update!!!");


                int select = choiceEskizDefect.getSelectedIndex();
                if (select >= 0 && select < defectList.size()) {
                    boolean ok = true;
                    for (int i = 0; i < 10; i++) {
                        if (paramText[i] != null && paramText[i].getText().trim().equals("")) {
                            paramText[i].setText("Введите значение!");
                            ok = false;
                        }
                    }

                    if (ok) {

                        Symbols symbols = (Symbols) nowObject;

                        deleteObject();


                        Symbols s = new Symbols();
                        s.list = symbols.list;

                        int j = examplesCheck.getSelectedIndex();
                        if (j >= 0 && j <= constExmpList.size()) {

                            ConstructionExample constructionExample = createConstructionExample(j);
                            ConstructionDefect constructionDefect = createConstructionDefect(constructionExample);

                            updateDefect(constructionDefect, constructionExample, s);
                            textName.setText("");
                            JOptionPane.showMessageDialog(defectFrame, "Дефект изменен");
                            defectFrame.dispose();

                        } else {
                            System.out.println("smth wrong");
                        }


                    }
                }


            }
        });


        buttonForEskizDefect.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent event) {
                int select = choiceEskizDefect.getSelectedIndex();
                if (select >= 0 && select < defectList.size()) {
                    boolean ok = true;
                    for (int i = 0; i < 10; i++) {
                        if (paramText[i] != null && paramText[i].getText().trim().equals("")) {
                            paramText[i].setText("Введите значение!");
                            ok = false;
                        }
                    }

                    if (ok) {
                        int j = examplesCheck.getSelectedIndex();
                        if (j >= 0 && j <= constExmpList.size()) {

                            ConstructionExample constructionExample = createConstructionExample(j);
                            ConstructionDefect constructionDefect = createConstructionDefect(constructionExample);

                            addDetailSymbol((DetailSymbol) defectList.get(select), fullPath, constructionDefect, constructionExample, "defect");
                            textName.setText("");
                            defectFrame.dispose();

                        } else {
                            System.out.println("smth wrong");
                        }
                    }
                }
            }
        }
        );


        buttonAddDataDefect.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent event) {

                createDefectFrame(null);


            }
        }
        );


        choiceConstZone.addItemListener(new ItemListener() {

            public void itemStateChanged(ItemEvent e) {


                changeReasonList();

            }
        });


        examplesCheck.addItemListener(new ItemListener() {

            public void itemStateChanged(ItemEvent e) {


                if (examplesCheck.getSelectedIndex() < constExmpList.size() && examplesCheck.getSelectedIndex() >= 0) {
                    ConstructionExample constructionExample = (ConstructionExample) constExmpList.get(examplesCheck.getSelectedIndex());
                    if (constructionExample.getExampleNumber() != null) {
                        textName.setText(constructionExample.getExampleName());
                    }

                } else if (examplesCheck.getSelectedIndex() == constExmpList.size()) {
                    textName.setText("");
                }


            }
        });


        textName.addKeyListener(new KeyListener() {

            public void keyTyped(KeyEvent e) {
                //To change body of implemented methods use File | Settings | File Templates.
            }

            public void keyPressed(KeyEvent e) {
                //To change body of implemented methods use File | Settings | File Templates.
            }

            public void keyReleased(KeyEvent e) {
                int i = examplesCheck.getSelectedIndex();
                if (e.getKeyCode() == 10 && i != constExmpList.size()) {
                    ConstructionExample constructionExample = (ConstructionExample) constExmpList.get(i);
                    constructionExample.setExampleName(textName.getText());

                    if (getParameter("objectConstructionId") != null && !getParameter("objectConstructionId").trim().equals("")) {
                        ObjectConstruction objectConstruction = (ObjectConstruction) session.get(ObjectConstruction.class, new Long(getParameter("objectConstructionId")));

                        constructionExample.setBuildObjectId(objectConstruction.getObjectId());
                    }


                    session.clear();

                    session.update(constructionExample);
                    session.flush();

                    ConstructionExample constExOne = (ConstructionExample) constExmpList.get(0);
                    constExmpList.set(0, constructionExample);
                    constExmpList.set(i, constExOne);


                    setChoice(constExmpList, examplesCheck);

                }

            }
        });


        choiceDefVar.addItemListener(new ItemListener() {
            public void itemStateChanged(ItemEvent e) {
                if (choiceDefVar.getSelectedIndex() >= 0 && choiceDefVar.getSelectedIndex() < listDefVar.size()) {
                    constExmpList = new ArrayList();
                    if (getParameter("objectConstructionId") != null && !getParameter("objectConstructionId").trim().equals("")) {
                        constExmpList = getConstructionExample(Long.valueOf(getParameter("objectConstructionId")));
                    }
                    DefectVarity curDefectVarity = (DefectVarity) listDefVar.get(choiceDefVar.getSelectedIndex());
                    defctParamList = getDefectParametersByVarityId(curDefectVarity.getVarityId());
                    int size;
                    if (nowObject != null && (nowObject instanceof Symbols) && ((Symbols) nowObject).getType().equals("defect")) {
                        size = createExamplesCheckAndParams(defctParamList, "update");
                    } else {
                        size = createExamplesCheckAndParams(defctParamList, "insert");
                    }


                    int height = 270 + 30 * (size - 1);
                    int weight = 400;

                    defectFrame.setResizable(true);
                    if (nowObject != null && (nowObject instanceof Symbols) && ((Symbols) nowObject).getType().equals("defect")) {
                        defectFrame.setBounds(1000 - weight, 500 - height, weight, height);
                    } else {
                        defectFrame.setBounds((SCREEN_WEIGHT - weight) / 2, (SCREEN_HEIGHT - height) / 2, weight, height);
                    }

                    defectFrame.setResizable(true);


                    if (getParameter("objectConstructionId") != null && !getParameter("objectConstructionId").trim().equals("")) {
                        constExmpList = getConstructionExample(Long.valueOf(getParameter("objectConstructionId")));
                        setChoice(constExmpList, examplesCheck);
                    }
                    examplesCheck.setEnabled(true);
                }


            }
        });


        buttonForEskizDetail.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent event) {
                int select = choiceEskizDetail.getSelectedIndex();
                if (select >= 0 && select < detailList.size()) {


                    if (getParameter("type") != null && getParameter("type").equals("level") && objectPicture.levelPlanInformation != null) {

                        createDialog2((DetailSymbol) detailList.get(select));


                    } else {
                        addDetailSymbol((DetailSymbol) detailList.get(select), fullPath, null, null, "detail");
                    }

                }
            }
        }
        );

        pen.addActionListener(
                new ActionListener() {
                    public void actionPerformed(ActionEvent event) {
                        unPaintAllButtons();
                        if (toolMode != PEN) {
                            toolMode = PEN;
                            pen.setBackground(Color.GREEN);
                        } else {
                            toolMode = SELECT;
                        }


                    }

                }
        );

        line.addActionListener(
                new ActionListener() {
                    public void actionPerformed(ActionEvent event) {
                        unPaintAllButtons();
                        if (toolMode != LINE) {
                            toolMode = LINE;
                            line.setBackground(Color.GREEN);
                        } else {
                            toolMode = SELECT;
                        }
                    }
                }
        );

        rect.addActionListener(
                new ActionListener() {
                    public void actionPerformed(ActionEvent event) {
                        unPaintAllButtons();
                        if (toolMode != RECT) {
                            toolMode = RECT;
                            rect.setBackground(Color.GREEN);
                        } else {
                            toolMode = SELECT;
                        }
                    }
                }
        );

        ellipse.addActionListener(
                new ActionListener() {
                    public void actionPerformed(ActionEvent event) {
                        unPaintAllButtons();
                        if (toolMode != ELLIPSE) {
                            toolMode = ELLIPSE;
                            ellipse.setBackground(Color.GREEN);
                        } else {
                            toolMode = SELECT;
                        }
                    }
                }
        );

        sizeline.addActionListener(
                new ActionListener() {
                    public void actionPerformed(ActionEvent event) {
                        unPaintAllButtons();
                        if (toolMode != SIZELINE) {
                            toolMode = SIZELINE;
                            sizeline.setBackground(Color.GREEN);
                            sizeLinePosition = 0;
                        } else {
                            toolMode = SELECT;
                        }
                    }
                }
        );

        text.addActionListener(
                new ActionListener() {
                    public void actionPerformed(ActionEvent event) {
                        unPaintAllButtons();
                        if (toolMode != TEXT) {

                            toolMode = TEXT;
                            text.setBackground(Color.GREEN);

                            textFrame = new JFrame("Ввод текста");
                            textFrame.setLayout(new GridLayout(1, 2));

                            textFrame.add(textField);


                            JButton jButton = new JButton("Завершить ввод текста");
                            jButton.addActionListener(new ActionListener() {

                                public void actionPerformed(ActionEvent e) {
                                    unPaintAllButtons();
                                    toolMode = SELECT;
                                    textFrame.dispose();
                                }
                            });

                            textFrame.add(jButton);

                            int height = 60;
                            int weight = 400;
                            textFrame.setBounds((int) (SCREEN_WEIGHT - weight) / 2, (int) (SCREEN_HEIGHT - height) / 2, weight, height);

                            textFrame.setVisible(true);
                            textFrame.setResizable(false);


                        } else {
                            toolMode = SELECT;

                            textFrame.dispose();


                        }
                    }

                }

        );


        setBackground(Color.WHITE);
        image.getGraphics().setPaintMode();
        getGraphics().setPaintMode();
        image.getGraphics().setColor(Color.WHITE);
        getGraphics().setColor(Color.WHITE);

    }

    public void saveImage() {


        textForMashtab.setText("100");
        objectPicture.setScale(1);
        mashtab = 1;
        vertScroll = new Scrollbar(Scrollbar.VERTICAL, paperScrollY, 60, 0, (IMAGE_SIZE_VERT - (int) (IMAGE_VERT / mashtab) - 60));
        horisScroll = new Scrollbar(Scrollbar.HORIZONTAL, paperScrollX, 90, 0, (IMAGE_SIZE_HORZ - (int) (IMAGE_HORZ / mashtab) - 90));


        clearImage();
        objectPicture.drawAllObjects(image.getGraphics(), paperScrollX, paperScrollY);
        getGraphics().drawImage(image, paperX, paperY, null);


        for (int i = 0; i < objectPicture.getObjectList().size(); i++) {
            if (objectPicture.getObjectList().get(i) instanceof Symbols) {
                Symbols symbols = (Symbols) objectPicture.getObjectList().get(i);
                if (symbols.getType().equals("point")) {
                    if (symbols.getActivity().equals("new")) {
                        save(symbols.getExample(), symbols.getStrength());
                        symbols.setActivity("old");
                    } else if (symbols.getActivity().equals("delete")) {
                        com.mysql.jdbc.Connection connection = null;
                        try {
                            connection = createConnection(fullPath);
                            com.mysql.jdbc.Statement st = null;
                            try {
                                st = (com.mysql.jdbc.Statement) connection.createStatement();
                                st.executeUpdate("delete from strengthPoints where pointId=" + symbols.getStrength().getPointId());
                                st.executeUpdate("update strengthPoints set pointPosition=pointPosition-1 where exampleId=" + symbols.getStrength().getExampleId() + " and pointPosition>=" + symbols.getStrength().getPointPosition());
                                st.close();
                                connection.close();
                            } catch (SQLException e) {
                                e.printStackTrace();
                            }
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                } else {
                    if (symbols.getActivity().equals("new")) {
                        save(symbols.getExample(), symbols.getDefect());
                        symbols.setActivity("old");
                    } else if (symbols.getActivity().equals("delete")) {
                        com.mysql.jdbc.Connection connection = null;
                        try {
                            connection = createConnection(fullPath);
                        } catch (IOException e) {
                            e.printStackTrace()//To change body of catch statement use File | Settings | File Templates.
                        }
                        com.mysql.jdbc.Statement st = null;
                        try {

                            st = (com.mysql.jdbc.Statement) connection.createStatement();
                            st.executeUpdate("delete from constructionDefects where constructionDefectId=" + symbols.getDefect().getConstructionDefectId());
                            st.executeUpdate("update constructionDefects set constructionDefectPosition=constructionDefectPosition-1 where exampleId=" + symbols.getDefect().getExampleId() + " and constructionDefectPosition>=" + symbols.getDefect().getConstructionDefectPosition());
                            st.executeUpdate("delete from defectParameters where constructionDefectId=" + symbols.getDefect().getConstructionDefectId());
                            st.close();
                            connection.close();

                        } catch (SQLException e) {
                            e.printStackTrace()//To change body of catch statement use File | Settings | File Templates.
                        }

                    }
                }
            }
        }


        for (int i = 0; i < objectPicture.getObjectList().size(); i++) {
            if (objectPicture.getObjectList().get(i) instanceof Symbols) {
                Symbols symbols = (Symbols) objectPicture.getObjectList().get(i);
                if (symbols.getActivity().equals("delete")) {
                    objectPicture.deleteObject(symbols);
                } else if (symbols.getActivity().equals("nothing")) {
                    objectPicture.deleteObject(symbols);
                }
            }
        }

        ObjectOutputStream out = null;
        try {
            out = new ObjectOutputStream(new FileOutputStream(savePath));
            out.writeObject(objectPicture);
            out.close();
            JOptionPane.showMessageDialog(this, "Изменения сохранены");

            nowHistory = 0;
            nextHistory.setEnabled(false);
            prewHistory.setEnabled(false);

        } catch (IOException e) {
            e.printStackTrace()//To change body of catch statement use File | Settings | File Templates.
        }


        int w = image.getWidth(null);
        int h = image.getHeight(null);
        BufferedImage bi = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);

        Graphics2D g2 = bi.createGraphics();
        g2.drawImage(image, 0, 0, null);

        try {
            ImageIO.write(bi, "jpg", new FileOutputStream(savePathImage));
        } catch (IOException e) {
        }


    }


    public void paint(Graphics g) {
        if (!loaded) {
            loaded = true;
            getGraphics().drawImage(image, paperX, paperY, null);
            getGraphics().drawImage(image, paperX, paperY, null);
            getGraphics().setColor(Color.red);
        }
    }

    int oldX1 = -1000;
    int oldY1 = -1000;
    int oldX1Real = -1000;
    int oldY1Real = -1000;
    boolean flag = false;

    public void mouseClicked(MouseEvent e) {


        if (e.getModifiers() == InputEvent.BUTTON3_MASK || e.getModifiers() == InputEvent.META_MASK) {

            showPopUpMenu(e);
        } else {


            unVisibleText.setFocusable(true);
            unVisibleText.requestFocus();
            Graphics imageGraphics;
            imageGraphics = image.getGraphics();
            imageGraphics.setPaintMode();
            imageGraphics.setColor(toolColor);
            getGraphics().drawImage(image, paperX, paperY, null);


            if (toolMode == SELECT) {

                nowObject = objectPicture.cursorInObject(changeX(e.getX()), changeY(e.getY()));
                if (nowObject != null) {

                    if (nowObject.getPosition() == 0) {
                        nowObject.paintSelect(getGraphics(), paperScrollX, paperScrollY);

                    } else {
                        nowObject.paintRotate(getGraphics(), paperScrollX, paperScrollY);
                    }
                }

            }

        }


    }

    public void mousePressed(MouseEvent e) {


        stilusControl = 0;

        unVisibleText.setFocusable(true);
        unVisibleText.requestFocus();

        oldX1 = changeX(e.getX());
        oldY1 = changeY(e.getY());

        oldX1Real = e.getX();
        oldY1Real = e.getY();

        mouseButton = e.getButton();

        x1 = changeX(e.getX());
        y1 = changeY(e.getY());

        brush = new Brush();
        brush.scale = mashtab;

        oldX = x1;
        oldY = y1;

        MyPoint p = objectPicture.getCorner(x1, y1);

        x1 = p.x;
        y1 = p.y;

        if (toolMode == SIZELINE) {

            if (sizeLinePosition == 1) {
                sizeLine.addFirstPoints(x1, y1);
                sizeLinePosition = 2;
                grawStar(x1, y1);
            }

            if (sizeLinePosition == 0) {
                sizeLine = new SizeLine(x1, y1);
                sizeLinePosition = 1;
                grawStar(x1, y1);
            }

        }


        if (toolMode == SELECT) {

            if (nowObject != null) {

                if (nowObject.getPosition() != -1) {

                    int area = nowObject.areaInObject(x1, y1);
                    if (area == -1) {
                        objectAction = NOTHING;
                    } else if (area == 0 && nowObject.getPosition() == 1) {
                        objectAction = NOTHING;
                    } else if (area > 0 && nowObject.getPosition() == 1) {
                        objectAction = ROTATE;
                    } else if (area == 0 && nowObject.getPosition() == 0) {
                        objectAction = MOVE;
                    } else if (area == 1 && nowObject.getPosition() == 0) {
                        objectAction = CHANGE_SIZE1;
                    } else if (area == 2 && nowObject.getPosition() == 0) {
                        objectAction = CHANGE_SIZE2;
                    } else if (area == 3 && nowObject.getPosition() == 0) {
                        objectAction = CHANGE_SIZE3;
                    } else if (area == 4 && nowObject.getPosition() == 0) {
                        objectAction = CHANGE_SIZE4;
                    }
                } else {
                    objectAction = NOTHING;
                }

            } else {
                objectAction = NOTHING;
            }

        }


        paintLittleStar(getGraphics(), e.getX(), e.getY());


    }


    public void mouseReleased(MouseEvent e) {

        if (!(e.getModifiers() == InputEvent.BUTTON3_MASK || e.getModifiers() == InputEvent.META_MASK)) {
            unVisibleText.setFocusable(true);
            unVisibleText.requestFocus();
            pressed = false;
            getGraphics().drawImage(image, paperX, paperY, null);

            MyPoint p = objectPicture.getCorner(changeX(e.getX()), changeY(e.getY()));

            x2 = p.x;
            y2 = p.y;

            Graphics imageGraphics = image.getGraphics();
            imageGraphics.setPaintMode();
            imageGraphics.setColor(toolColor);
            int xx1 = x1;
            int yy1 = y1;
            int xx2 = x2;
            int yy2 = y2;
            if (mouseButton != MouseEvent.BUTTON1) {
                if (y1 < y2)
                    yy2 = y1 + Math.abs(x2 - x1);
                else
                    yy2 = y1 - Math.abs(x2 - x1);
            }
            switch (toolMode) {
                case LINE:

                    Line line = new Line();
                    line.scale = mashtab;
                    line.setColor(toolColor);
                    line.setFirstPoint(new MyPoint(xx1, yy1));

                    if (ctrlPressed) {

                        if (Math.abs(xx1 - xx2) < Math.abs(yy1 - yy2)) {
                            line.setSecondPoint(new MyPoint(xx1, yy2));
                        } else {
                            line.setSecondPoint(new MyPoint(xx2, yy1));
                        }

                    } else {
                        line.setSecondPoint(new MyPoint(xx2, yy2));
                    }


                    objectPicture.addObject(line);
                    objectPicture.drawObjects(image.getGraphics(), paperScrollX, paperScrollY);
                    getGraphics().drawImage(image, paperX, paperY, null);

                    save();

                    break;
                case RECT:
                    Rectangle rectangle = new Rectangle();
                    if (ctrlPressed) {

                        int a = Math.min(Math.abs(xx2 - xx1), Math.abs(yy2 - yy1));
                        int xNew = a;
                        int yNew = a;
                        if (xx2 - xx1 < 0) {
                            xNew *= -1;
                        }
                        if (yy2 - yy1 < 0) {
                            yNew *= -1;
                        }


                        rectangle = new Rectangle(xx1, yy1, xNew, yNew, mashtab);
                    } else {
                        rectangle = new Rectangle(xx1, yy1, (xx2 - xx1), (yy2 - yy1), mashtab);
                    }


                    rectangle.setColor(toolColor);
                    objectPicture.addObject(rectangle);
                    objectPicture.drawObjects(image.getGraphics(), paperScrollX, paperScrollY);
                    getGraphics().drawImage(image, paperX, paperY, null);
                    save();

                    break;
                case PEN:

                    brush.scale = mashtab;
                    brush.addPoint(x2, y2);
                    brush.setColor(toolColor);
                    objectPicture.addObject(brush);
                    objectPicture.drawObjects(image.getGraphics(), paperScrollX, paperScrollY);
                    getGraphics().drawImage(image, paperX, paperY, null);

                    save();

                    brush = null;
                    break;
                case ELLIPSE:
                    Oval oval = new Oval();
                    if (ctrlPressed) {

                        int a = Math.min(Math.abs(xx2 - xx1), Math.abs(yy2 - yy1));
                        int xNew = a;
                        int yNew = a;
                        if (xx2 - xx1 < 0) {
                            xNew *= -1;
                        }
                        if (yy2 - yy1 < 0) {
                            yNew *= -1;
                        }
                        oval = new Oval(xx1, yy1, xNew, yNew, mashtab);

                    } else {
                        oval = new Oval(xx1, yy1, (xx2 - xx1), (yy2 - yy1), mashtab);
                    }


                    oval.setColor(toolColor);
                    objectPicture.addObject(oval);
                    objectPicture.drawObjects(image.getGraphics(), paperScrollX, paperScrollY);
                    getGraphics().drawImage(image, paperX, paperY, null);
                    save();

                    break;

                case SIZELINE:


                    if (sizeLinePosition == 2) {
                        sizeLinePosition = 0;
                        if (ctrlPressed) {
                            MyPoint point = sizeLine.p[1];
                            if (Math.abs(point.x - x2) < Math.abs(point.y - y2)) {
                                sizeLine.addLastPoints(point.x, y2);
                            } else {
                                sizeLine.addLastPoints(x2, point.y);
                            }
                        } else {
                            sizeLine.addLastPoints(x2, y2);
                        }
                        sizeLine.setColor(toolColor);
                        sizeLine.scale = mashtab;
                        objectPicture.addObject(sizeLine);
                        objectPicture.drawObjects(image.getGraphics(), paperScrollX, paperScrollY);
                        getGraphics().drawImage(image, paperX, paperY, null);
                        save();

                        final int xTextLine = (sizeLine.p[2].x + sizeLine.p[3].x) / 2;
                        final int yTextLine = (sizeLine.p[2].y + sizeLine.p[3].y) / 2;


                        sizeLine = null;

                        textFrame = new JFrame("Ввод текста для размерной линии");
                        textFrame.setLayout(new GridLayout(1, 2));

                        textFrame.add(textField);


                        JButton jButton1 = new JButton("Отмена");
                        jButton1.addActionListener(new ActionListener() {

                            public void actionPerformed(ActionEvent e) {
                                unPaintAllButtons();
                                textFrame.dispose();
                                toolMode = SIZELINE;
                                sizeline.setBackground(Color.GREEN);
                            }
                        });


                        JButton jButton2 = new JButton("Ввод");
                        jButton2.addActionListener(new ActionListener() {
                            public void actionPerformed(ActionEvent e) {

                                TextLine textLine = new TextLine(xTextLine, yTextLine, textField.getText());
                                textLine.scale = mashtab;
                                objectPicture.addObject(textLine);
                                textFrame.dispose();
                                textLine.draw(getGraphics(), paperScrollX, paperScrollY, appletWidth, appletHeight);
                                save();
                                toolMode = SIZELINE;
                                sizeline.setBackground(Color.GREEN);

                            }
                        });


                        textFrame.add(jButton1);
                        textFrame.add(jButton2);

                        int height = 60;
                        int weight = 400;

                        textFrame.setBounds(e.getX(), e.getY() + 25, weight, height);

                        textFrame.setVisible(true);
                        textFrame.setResizable(false);


                    }
                    break;
                case TEXT:
                    if (!textField.getText().trim().equals("")) {
                        TextLine textLine = new TextLine(x2, y2, textField.getText());
                        textLine.setColor(toolColor);
                        textLine.scale = mashtab;
                        objectPicture.addObject(textLine);
                        objectPicture.drawObjects(image.getGraphics(), paperScrollX, paperScrollY);
                        getGraphics().drawImage(image, paperX, paperY, null);
                        save();
                    } else {
                        textField.setText("Введите текст!");
                    }

                    break;
                case SELECT:


                    if (0 < stilusControl && stilusControl < 3) {

                        nowObject = objectPicture.cursorInObject(changeX(e.getX()), changeY(e.getY()));
                        if (nowObject != null) {

                            // System.out.println("Find object");

                            if (nowObject.getPosition() == 0) {
                                nowObject.paintSelect(getGraphics(), paperScrollX, paperScrollY);
                                if (nowObject instanceof Symbols) {
                                    Symbols symbols = (Symbols) nowObject;
                                    if (symbols.getType().equals("detail")) {
                                        /*   unGroup.setEnabled(true);
                                        group.setEnabled(false);*/
                                    }
                                }

                            } else {
                                nowObject.paintRotate(getGraphics(), paperScrollX, paperScrollY);
                            }
                        }
                        stilusControl = 0;
                    } else {

                        if (objectAction == MOVE && nowObject != null) {
                            nowObject.move(changeX(e.getX()), changeY(e.getY()));
                            objectPicture.drawObjects(image.getGraphics(), paperScrollX, paperScrollY);
                            getGraphics().drawImage(image, paperX, paperY, null);
                            save();
                            if (nowObject.getPosition() == 0) {
                                nowObject.paintSelect(getGraphics(), paperScrollX, paperScrollY);
                            } else if (nowObject.getPosition() == 1) {
                                nowObject.paintRotate(getGraphics(), paperScrollX, paperScrollY);
                            }

                        } else if (objectAction == ROTATE && nowObject != null) {

                            nowObject.rotate(changeX(e.getX()), changeY(e.getY()));
                            objectPicture.drawObjects(image.getGraphics(), paperScrollX, paperScrollY);
                            getGraphics().drawImage(image, paperX, paperY, null);

                            save();

                            if (nowObject.getPosition() == 0) {
                                nowObject.paintSelect(getGraphics(), paperScrollX, paperScrollY);
                            } else if (nowObject.getPosition() == 1) {
                                nowObject.paintRotate(getGraphics(), paperScrollX, paperScrollY);
                            }

                        } else
                        if ((objectAction == CHANGE_SIZE1 || objectAction == CHANGE_SIZE2 || objectAction == CHANGE_SIZE3 || objectAction == CHANGE_SIZE4) && nowObject != null) {


                            nowObject.changeSize(changeX(e.getX()), changeY(e.getY()), objectAction);
                            objectPicture.drawObjects(image.getGraphics(), paperScrollX, paperScrollY);
                            getGraphics().drawImage(image, paperX, paperY, null);

                            save();

                            if (nowObject.getPosition() == 0) {
                                nowObject.paintSelect(getGraphics(), paperScrollX, paperScrollY);
                            } else if (nowObject.getPosition() == 1) {
                                nowObject.paintRotate(getGraphics(), paperScrollX, paperScrollY);
                            }

                        } else {

                            if (objectPicture.objectInArea(new MyPoint(oldX1, oldY1), new MyPoint(changeX(e.getX()), changeY(e.getY())))) {

                                objectPicture.paintSelectGroup(getGraphics(), paperScrollX, paperScrollY);
                                /*   unGroup.setEnabled(false);
                                group.setEnabled(true);*/


                            } else {

                                objectPicture.drawObjects(image.getGraphics(), paperScrollX, paperScrollY);
                                getGraphics().drawImage(image, paperX, paperY, null);
                            }


                        }

                    }


                    break;

                case MOVEPAPER:
                    paperX += x2 - x1;
                    paperY += y2 - y1;

                    getGraphics().drawImage(image, paperX, paperY, null);

                    break;

            }

        } else {
            if (0 < stilusControl && stilusControl < 3) {

                showPopUpMenu(e);

            }
        }

    }

    public int mediumRGB(int RGB1, int RGB2) {
        int red = (new Color(RGB1).getRed() + new Color(RGB2).getRed()) / 2;
        int green = (new Color(RGB1).getGreen() + new Color(RGB2).getGreen()) / 2;
        int blue = (new Color(RGB1).getBlue() + new Color(RGB2).getBlue()) / 2;
        return new Color(red, green, blue).getRGB();
    }

    int[][] pixelMatrix = null;

    public void makePixelMatrix(int w, int h) {
        pixelMatrix = new int[w][h];
        realBI = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
        Graphics2D g2 = realBI.createGraphics();
        g2.drawImage(image, 0, 0, null);
        for (int x = 0; x < w; x++) {
            for (int y = 0; y < h; y++) {
                pixelMatrix[x][y] = realBI.getRGB(x, y);

            }
        }
    }

    public int[][] getPixelMatrix() {
        return pixelMatrix;
    }


    public void mouseEntered(MouseEvent e) {

    }

    public void mouseExited(MouseEvent e) {

    }

    int mouseButton = 0;


    public void mouseDragged(MouseEvent e) {


        stilusControl++;

        unVisibleText.setFocusable(true);
        unVisibleText.requestFocus();

        MyPoint p = objectPicture.getCorner(changeX(e.getX()), changeY(e.getY()));

        x2 = p.x;
        y2 = p.y;

        int xx1 = x1;
        int yy1 = y1;
        int xx2 = x2;
        int yy2 = y2;


        if (mouseButton != MouseEvent.BUTTON1) {
            if (y1 < y2)
                yy2 = y1 + Math.abs(x2 - x1);
            else
                yy2 = y1 - Math.abs(x2 - x1);
        }

        Graphics imageGraphics;
        imageGraphics = image.getGraphics();
        imageGraphics.setPaintMode();
        imageGraphics.setColor(toolColor);
        getGraphics().drawImage(image, 0, 0, null);
        getGraphics().setColor(toolColor);

        switch (toolMode) {

            case PEN:
                if (Math.abs(oldX - x2) > 5 || Math.abs(oldY - y2) > 5) {
                    brush.addPoint(x2, y2);
                    oldX = x2;
                    oldY = y2;
                }
                paintLines(brush.getPoints(), false);
                break;
            case LINE:
                if (ctrlPressed) {
                    if (Math.abs(xx1 - xx2) < Math.abs(yy1 - yy2)) {
                        drawLine(xx1, yy1, xx1, yy2, getGraphics());
                    } else {
                        drawLine(xx1, yy1, xx2, yy1, getGraphics());
                    }
                } else {
                    drawLine(xx1, yy1, xx2, yy2, getGraphics());
                }
                break;

            case RECT:
                if (ctrlPressed) {
                    int a = Math.min(Math.abs(xx2 - xx1), Math.abs(yy2 - yy1));
                    int xNew = a;
                    int yNew = a;
                    if (xx2 - xx1 < 0) {
                        xNew *= -1;
                    }
                    if (yy2 - yy1 < 0) {
                        yNew *= -1;
                    }
                    Rectangle rectangle = new Rectangle(xx1, yy1, xNew, yNew, mashtab);
                    paintLines(rectangle.getPoints(), true);
                } else {
                    Rectangle rectangle = new Rectangle(xx1, yy1, (xx2 - xx1), (yy2 - yy1), mashtab);
                    paintLines(rectangle.getPoints(), true);
                }
                break;

            case ELLIPSE:
                if (ctrlPressed) {
                    int a = Math.min(Math.abs(xx2 - xx1), Math.abs(yy2 - yy1));
                    int xNew = a;
                    int yNew = a;
                    if (xx2 - xx1 < 0) {
                        xNew *= -1;
                    }
                    if (yy2 - yy1 < 0) {
                        yNew *= -1;
                    }
                    Oval oval = new Oval(xx1, yy1, xNew, yNew, mashtab);
                    paintLines(oval.getPoints(), true);
                } else {
                    Oval oval = new Oval(xx1, yy1, (xx2 - xx1), (yy2 - yy1), mashtab);
                    paintLines(oval.getPoints(), true);
                }
                break;

            case SIZELINE:

                if (sizeLinePosition == 2) {
                    if (ctrlPressed) {
                        MyPoint point = sizeLine.p[1];
                        if (Math.abs(point.x - x2) < Math.abs(point.y - y2)) {
                            sizeLine.addLastPoints(point.x, y2);
                        } else {
                            sizeLine.addLastPoints(x2, point.y);
                        }
                    } else {
                        sizeLine.addLastPoints(x2, y2);
                    }
                    paintLines(sizeLine.getPoints(), false);
                    paintLines(sizeLine.getFirstArrow(), false);
                    paintLines(sizeLine.getSecondArrow(), false);
                }
                break;

            case SELECT:
                if (objectAction == MOVE && nowObject != null) {
                    nowObject.move(changeX(e.getX()), changeY(e.getY()));
                    nowObject.paintDuringChange(getGraphics(), paperScrollX, paperScrollY);
                    break;
                }
                if (objectAction == ROTATE && nowObject != null) {
                    if (!(nowObject instanceof TextLine)) {
                        GlobalPicture globalPicture = nowObject.newObject();
                        globalPicture.rotate(changeX(e.getX()), changeY(e.getY()));
                        globalPicture.paintDuringChange(getGraphics(), paperScrollX, paperScrollY);
                        break;
                    }
                }

                if ((objectAction == CHANGE_SIZE1 || objectAction == CHANGE_SIZE2 || objectAction == CHANGE_SIZE3 || objectAction == CHANGE_SIZE4) && nowObject != null) {

                    if (!(nowObject instanceof TextLine)) {
                        GlobalPicture globalPicture = nowObject.newObject();
                        globalPicture.changeSize(changeX(e.getX()), changeY(e.getY()), objectAction);
                        globalPicture.changeSize(changeX(e.getX()), changeY(e.getY()), objectAction);
                        globalPicture.paintDuringChange(getGraphics(), paperScrollX, paperScrollY);
                        break;
                    }
                }
                if (objectPicture.area) {
                    objectPicture.moveArea(changeX(e.getX()), changeY(e.getY()));
                    objectPicture.paintDuringChangeArea(getGraphics(), paperScrollX, paperScrollY);
                } else {
                    Graphics g = getGraphics();
                    g.setColor(Color.BLUE);
                    painSelectRectangle(g, new MyPoint(Math.min(oldX1Real, e.getX()), Math.min(oldY1Real, e.getY())), new MyPoint(Math.max(oldX1Real, (e.getX())), Math.max(oldY1Real, (e.getY()))));
                }
                break;
        }


    }

    public void mouseMoved(MouseEvent e) {
    }

    public void keyTyped(KeyEvent e) {
    }

    public void keyPressed(KeyEvent e) {
    }

    public void keyReleased(KeyEvent e) {
    }


    private void clearImage() {

        try {
            InputStream imageStream = new FileInputStream(loadPath);
            image = ImageIO.read(imageStream);


            getGraphics().drawImage(image, paperX, paperY, null);
            imageStream.close();
        }
        catch (IOException e) {
            e.printStackTrace();
        }

    }

    private void paintLines(java.util.List points, boolean close) {

        if (points.size() > 0) {
            for (int i = 0; i < points.size() - 1; i++) {
                MyPoint mPoint1 = (MyPoint) points.get(i);
                MyPoint mPoint2 = (MyPoint) points.get(i + 1);
                drawLine(mPoint1.x, mPoint1.y, mPoint2.x, mPoint2.y, getGraphics());
            }
            if (close) {
                MyPoint mPoint1 = (MyPoint) points.get(0);
                MyPoint mPoint2 = (MyPoint) points.get(points.size() - 1);
                drawLine(mPoint1.x, mPoint1.y, mPoint2.x, mPoint2.y, getGraphics());
            }
        }

    }

    private void grawStar(int x, int y) {
        int n = 3;
        drawLine(x - n, y, x + n, y, getGraphics());
        drawLine(x, y - n, x, y + n, getGraphics());
        drawLine(x - n, y - n, x + n, y + n, getGraphics());
        drawLine(x - n, y + n, x + n, y - n, getGraphics());
    }


    private void setValuesDetail(java.util.List list, Choice choice) {
        for (int i = 0; i < list.size(); i++) {
            DetailSymbol detailSymbol = (DetailSymbol) list.get(i);
            String elementName = "";

            if (detailSymbol.getConstructionType() != null) {
                elementName = detailSymbol.getConstructionType().getFullName();
            }


            if (detailSymbol.getDefectType() != null) {
                elementName = detailSymbol.getDefectType().getDefectTypeName();
                if (detailSymbol.getDefectVarity() != null) {
                    elementName += " " + detailSymbol.getDefectVarity().getVarityName();
                }
            }

            choice.add(elementName);
        }
    }

    private void setChoice(java.util.List list, JComboBox choice) {

        choice.removeAllItems();

        for (int i = 0; i < list.size(); i++) {

            if (list.get(i) instanceof DefectType) {
                DefectType object = (DefectType) list.get(i);
                choice.addItem(object.getDefectTypeName());
            } else if (list.get(i) instanceof DefectVarity) {
                DefectVarity object = (DefectVarity) list.get(i);
                choice.addItem(object.getVarityName());
            } else if (list.get(i) instanceof Reason) {
                Reason object = (Reason) list.get(i);
                choice.addItem(object.getReasonName().getReasonName());
            } else if (list.get(i) instanceof DefectZone) {
                DefectZone object = (DefectZone) list.get(i);
                choice.addItem(object.getDefectZoneName());
            } else if (list.get(i) instanceof DangerCategory) {
                DangerCategory object = (DangerCategory) list.get(i);
                choice.addItem(object.getCategoryName());
            } else if (list.get(i) instanceof ConstructionExample) {
                ConstructionExample constructionExample = (ConstructionExample) list.get(i);

                String s = String.valueOf(constructionExample.getExampleRelativeNumber());
                if (constructionExample.getExampleName() != null && !constructionExample.getExampleName().trim().equals("")) {
                    s = constructionExample.getExampleName();
                }
                choice.addItem(s);

                if (i == list.size() - 1) {
                    choice.addItem("Новый экземпляр");
                }


            }

        }
    }


    private SessionFactory getSession() {

        Configuration cfg = new Configuration();
        cfg.setProperty("hibernate.connection.url", "jdbc:mysql://localhost/vstbase");
        cfg.setProperty("hibernate.connection.driver_class", "com.mysql.jdbc.Driver");
        cfg.setProperty("hibernate.connection.username", "root");
        cfg.setProperty("hibernate.connection.password", "");
        cfg.setProperty("hibernate.dialect", "org.hibernate.dialect.MySQL5Dialect");

        cfg.addClass(DetailSymbol.class);
        cfg.addClass(DefectType.class);
        cfg.addClass(DefectVarity.class);
        cfg.addClass(Material.class);
        cfg.addClass(Reason.class);
        cfg.addClass(ConstructionType.class);
        cfg.addClass(Parameter.class);
        cfg.addClass(DefectCategory.class);
        cfg.addClass(DefectZone.class);
        cfg.addClass(ReasonName.class);
        cfg.addClass(Question.class);
        cfg.addClass(Measure.class);
        cfg.addClass(CategoryParameter.class);
        cfg.addClass(DefectCategoryName.class);
        cfg.addClass(AuthentificationElement.class);
        cfg.addClass(QuestionType.class);
        cfg.addClass(DocumentType.class);
        cfg.addClass(Answer.class);
        cfg.addClass(DangerCategory.class);
        cfg.addClass(ConstructionExample.class);
        cfg.addClass(Strength.class);
        cfg.addClass(ObjectConstruction.class);
        cfg.addClass(ObjectAnswer.class);
        cfg.addClass(BuildingObject.class);
        cfg.addClass(ConstructionDefect.class);
        cfg.addClass(DefectAuthentification.class);
        cfg.addClass(ConstructionDefectZone.class);
        cfg.addClass(ObjectPhoto.class);
        cfg.addClass(DefectParameter.class);
        cfg.addClass(DefectParameterZone.class);
        cfg.addClass(ObjectType.class);
        cfg.addClass(User.class);
        cfg.addClass(Role.class);
        cfg.addClass(LevelPlan.class);

        SessionFactory sessionFactory = cfg.buildSessionFactory();

        return sessionFactory;
    }


    private void addDetailSymbol(DetailSymbol detailSymbol, String fullPath, ConstructionDefect defect, ConstructionExample example, String type) {

        ObjectPicture symbolObjectPicture = ObjectPictureUtil.addDetailSymbol(detailSymbol, fullPath);


        Symbols symbols = new Symbols(symbolObjectPicture);

        if ("defect".equals(type)) {
            symbols.getTextLineList().add(new TextLine(200, 185, String.valueOf("№ " + defect.getDefectRelativeNumber()), mashtab));
            for (int i = 0; i < defect.getDefectParameters().size(); i++) {
                DefectParameter defectParameter = (DefectParameter) defect.getDefectParameters().get(i);
                symbols.getTextLineList().add(new TextLine(200, 170 - i * 15, String.valueOf(defectParameter.getParameter() + " " + defectParameter.getParameterValue() + " "), mashtab));
            }

        }
        symbols.setDefect(defect);
        symbols.setType(type);
        symbols.setExample(example);
        symbols.setActivity("new");


        symbols.setScale(mashtab);
        objectPicture.addObject(symbols);

        objectPicture.drawObjects(image.getGraphics(), paperScrollX, paperScrollY);
        getGraphics().drawImage(image, paperX, paperY, null);

        save();

    }

    private void updateDefect(ConstructionDefect defect, ConstructionExample example, Symbols symbols) {


        MyPoint point = symbols.getMaxPoint();
        symbols.getTextLineList().add(new TextLine(point.x, point.y, String.valueOf("№ " + defect.getDefectRelativeNumber()), mashtab));
        for (int i = 0; i < defect.getDefectParameters().size(); i++) {
            DefectParameter defectParameter = (DefectParameter) defect.getDefectParameters().get(i);
            symbols.getTextLineList().add(new TextLine(point.x, point.y - 15 - i * 15, String.valueOf(defectParameter.getParameter() + " " + defectParameter.getParameterValue() + " "), mashtab));
        }


        symbols.setDefect(defect);
        symbols.setType("defect");
        symbols.setExample(example);
        symbols.setActivity("new");

        symbols.setScale(mashtab);
        objectPicture.addObject(symbols);

        objectPicture.drawObjects(image.getGraphics(), paperScrollX, paperScrollY);
        getGraphics().drawImage(image, paperX, paperY, null);

        save();

    }


    private void addDetailSymbol(DetailSymbol detailSymbol, String fullPath, ConstructionDefect defect, ConstructionExample example, String type, String action, int x1, int y1, int x2, int y2) {

        Symbols symbols = new Symbols(ObjectPictureUtil.addDetailSymbol(detailSymbol, fullPath));


        if (objectPicture.levelPlanInformation != null) {
            System.out.println("objectPicture.levelPlanInformation != null");
            for (int y = y1; y <= y2; y++) {
                int xx = objectPicture.levelPlanInformation.length - 1;
                int new_x = 0;
                if (y == y2) {
                    xx = x2;
                }
                if (y == y1) {
                    new_x = x1;
                }
                for (int x = new_x; x <= xx; x++) {
                    System.out.println("x:" + x + "; y:" + y);

                    if ((objectPicture.levelPlanInformation[x][y].getSymbols() != null && action.equals("replacement")) || (objectPicture.levelPlanInformation[x][y].getSymbols() == null)) {

                        System.out.println("paste");
                        Symbols newSymbols = (Symbols) symbols.newObject();

                        newSymbols.setDefect(null);
                        newSymbols.setType(type);
                        newSymbols.setExample(null);
                        newSymbols.setActivity("new");
                        newSymbols.setScale(mashtab);

                        objectPicture.levelPlanInformation[x][y].setSymbols(newSymbols, mashtab);


                    }
                }

            }
        }

        objectPicture.drawObjects(image.getGraphics(), paperScrollX, paperScrollY);
        getGraphics().drawImage(image, paperX, paperY, null);

        save();

    }


    public java.util.List getDefectParametersByVarityId(Integer varityId) {

        java.util.List parameterList = session.createQuery("from Parameter where parameterId in (select parameters.parameterId from DefectVarity defectVarity inner join defectVarity.parameters as parameters where defectVarity.varityId=?)").setString(0, String.valueOf(varityId)).list();

        /* for (int i = 0; i < parameterList.size(); i++) {
            Parameter parameter = (Parameter) parameterList.get(i);
            Parameter curParameter = new Parameter();
            curParameter.setParameterId(parameter.getParameterId());
            curParameter.setParameterName(parameter.getParameterName());
            Measure measure = new Measure();
            measure.setMeasureId(parameter.getMeasure().getMeasureId());
            measure.setMeasureName(parameter.getMeasure().getMeasureName());
        }*/


        java.util.List parameterDefectList = new ArrayList();
        for (int i = 0; i < parameterList.size(); i++) {
            Parameter parameter = (Parameter) parameterList.get(i);
            DefectParameter defectParameter = new DefectParameter();
            defectParameter.setParameter(parameter);
            parameterDefectList.add(defectParameter);

        }
        return parameterDefectList;
    }


    public int createExamplesCheckAndParams(java.util.List listPr, String type) {

        defctParamList = listPr;
        paramPanel.removeAll();


        paramPanel.setLayout(new GridLayout(0, 2));

        addStaticComponent();

        System.out.println(listPr.size());

        for (int i = 0; i < listPr.size(); i++) {
            DefectParameter defectParameter = (DefectParameter) listPr.get(i);
            System.out.println(i + ": " + defectParameter.getParameterValue());
            //if (defectParameter.getParameterValue() != 0.0) {
            paramText[i] = new JTextField(String.valueOf(defectParameter.getParameterValue()));
            // } else {
            //     paramText[i] = new JTextField("");
            // }
            paramLabel[i] = new JLabel(defectParameter.getParameter().getParameterFullName());
            paramPanel.add(paramLabel[i]);
            paramPanel.add(paramText[i]);
        }

        addStaticButtons(type);
        paramPanel.repaint();

        return listPr.size();


    }


    public java.util.List getConstructionExample(Long objConstId) {

        if (objConstId != null) {

            return session.createQuery("select new ConstructionExample(ce.exampleId,ce.exampleRelativeNumber,ce.exampleName,ce.constructionType,(select dangerCategory from ConstructionExample as ce2  where ce2.exampleId=ce.exampleId),ce.noDeffects,ce.objectConstructionId) from ConstructionExample as ce where ce.objectConstructionId=?").setLong(0, objConstId.longValue()).list();


        } else {
            return null;
        }

    }


    public Long getMaxIdExample() {

        Long max = (Long) session.createQuery("select max(exampleId) from ConstructionExample").uniqueResult();
        if (max == null) {
            return new Long(1);
        }
        return (Long) (max.longValue() + 1);

    }


    public Long getMaxIdStrength() {


        Long max = (Long) session.createQuery("select max(pointId) from Strength").uniqueResult();
        if (max == null) {
            return new Long(1);
        }
        return (Long) (max.longValue() + 1);


    }

    public Integer getMaxStrengthPosition(Integer id) {
      Integer max = (Integer) session.createQuery("select max(strength.pointPosition) from Strength strength where strength.exampleId=" + id).uniqueResult();


        if (max == null) {
            return new Integer(0);
        }
        return (Integer) (max + 1);
    }


    public Integer getMaxIdDefect() {


        Integer max = (Integer) session.createQuery("select max(constructionDefect.constructionDefectId) from ConstructionDefect constructionDefect ").uniqueResult();
        if (max == null) {
            return new Integer(1);
        }
        return (Integer) (max + 1);


    }

    public Integer getConstructionExamplePosition(Integer id) {
      Integer max = (Integer) session.createQuery("select max(constructionExample.constructionExamplePosition) from ConstructionExample constructionExample where  constructionExample.objectConstructionId=" + id).uniqueResult();

        if (max == null) {
            return new Integer(0);
        }
        return (Integer) (max + 1);
    }

    public Long getDefectParameterPosition(Long id) {
        Long max;
        java.util.List list = session.createQuery("select max(defectParameter.defectParameterPosition) from DefectParameter defectParameter where defectParameter.constructionDefectId=" + id).list();
        if (list.size() > 1) {
            max = (Long) list.get(0);


            for (int i = 0; i < list.size(); i++) {
                Long newMax = (Long) list.get(i);

                if (newMax != null && newMax.longValue() > max.longValue()) {
                    max = newMax;
                }
            }


        } else {
            max = (Long) session.createQuery("select max(defectParameter.defectParameterPosition) from DefectParameter defectParameter where defectParameter.constructionDefectId=" + id).uniqueResult();

        }


        if (max == null) {
            return new Long(0);
        }
        return (Long) (max.longValue() + 1);
    }


    private Integer getExampleNumberByConstructionObjectId(Long objectConstructionId) {
        try {
            return (Integer) (((Integer) session.createQuery("select max(exampleRelativeNumber)  from ConstructionExample where objectConstructionId=?)").setLong(0, objectConstructionId.longValue()).uniqueResult()).intValue() + 1);
        } catch (Exception e) {
            return new Integer(1);
        }
    }


    public ConstructionExample createConstructionExample() throws IOException, SQLException {


        ConstructionExample constructionExample = new ConstructionExample();
        String typeId = getParameter("objectConstructionId");
        String number = typeId + "." + getMaxIdExample();
        constructionExample.setExampleRelativeNumber(getExampleNumberByConstructionObjectId(new Long(typeId)));


        constructionExample.setExampleName(textName.getText());
        if (typeId != null) {

            constructionExample.setObjectConstructionId(new Integer(typeId));
            ObjectConstruction objectConstruction = (ObjectConstruction) session.get(ObjectConstruction.class, new Long(typeId));


            constructionExample.setDangerCategory(null);
            constructionExample.setBuildObjectId(objectConstruction.getObjectId());
            constructionExample.setObjectConstructionId(objectConstruction.getTypeId());
            constructionExample.setConstructionType(objectConstruction.getConstructionType());
            constructionExample.setRecommendedDangerCategory(null);

            if (objectConstruction.getEsckizBlob() != null) {
                String wayToDefectEskiz = ImageUtil.getUniqueJPEGFile(fullPath);
                constructionExample.setDefectEsckizBlob(objectConstruction.getEsckizBlob());
                constructionExample.setWayToDefectEsckiz(wayToDefectEskiz);
                constructionExample.setDefectEsckizWayImage("image" + wayToDefectEskiz);
                objectConstruction.getEsckizBlob();
                File file = new File(fullPath + wayToDefectEskiz);
                file.createNewFile();
                FileOutputStream fileOutputStream = new FileOutputStream(fullPath + wayToDefectEskiz);
                Blob blob = objectConstruction.getEsckizBlob();
                byte[] bufer = new byte[62000];
                InputStream inputStream = blob.getBinaryStream();
                while (inputStream.read(bufer) != -1) {
                    fileOutputStream.write(bufer);
                }
                inputStream.close();
                fileOutputStream.close();

                String wayToPowerEskiz = ImageUtil.getUniqueJPEGFile(fullPath);
                constructionExample.setWayToPowerEsckiz(wayToPowerEskiz);
                constructionExample.setPowerEsckizBlob(objectConstruction.getEsckizBlob());
                constructionExample.setPowerEsckizWayImage("image" + wayToPowerEskiz);
                objectConstruction.getEsckizBlob();
                file = new File(fullPath + wayToPowerEskiz);
                if (file.exists()) {
                    file.delete();
                }
                file.createNewFile();
                fileOutputStream = new FileOutputStream(fullPath + wayToPowerEskiz);
                blob = objectConstruction.getEsckizBlob();
                byte[] powerBufer = new byte[62000];
                inputStream = blob.getBinaryStream();
                while (inputStream.read(powerBufer) != -1) {
                    fileOutputStream.write(powerBufer);
                }
                inputStream.close();
                fileOutputStream.close();
            }

            constructionExample.setConstructionType(objectConstruction.getConstructionType());
        }
        return constructionExample;
    }


    public void save(ObjectConstruction objectConstruction, ConstructionExample constructionExample) throws IOException {


        if (constructionExample.getWayToDefectEsckiz() != null && !constructionExample.getWayToDefectEsckiz().equals("") && (new File(fullPath + constructionExample.getWayToDefectEsckiz())).exists()) {
            constructionExample.setDefectEsckizBlob(Hibernate.createBlob(new FileInputStream(fullPath + constructionExample.getWayToDefectEsckiz())));
        }
        if (constructionExample.getWayToPowerEsckiz() != null && !constructionExample.getWayToPowerEsckiz().equals("") && (new File(fullPath + constructionExample.getWayToPowerEsckiz())).exists()) {
            constructionExample.setPowerEsckizBlob(Hibernate.createBlob(new FileInputStream(fullPath + constructionExample.getWayToPowerEsckiz())));
        }

        constructionExample.setConstructionExamplePosition(getConstructionExamplePosition(objectConstruction.getTypeId()));
        constructionExample.setBuildObjectId(objectConstruction.getObjectId());
        session.save(constructionExample);
        objectConstruction.getConstructionExamples().add(constructionExample);
        session.clear();
        session.update(objectConstruction);


    }

    public void save(ConstructionExample constructionExample, ConstructionDefect constructionDefect) {

        constructionDefect.setConstructionDefectPosition(getPosition(constructionExample.getExampleId()));
        constructionDefect.setExampleId(constructionExample.getExampleId());
        Integer id = getMaxIdDefect();
        constructionDefect.setConstructionDefectId(id);

        System.out.println("constructionDefect id = " + constructionDefect.getConstructionDefectId());

        System.out.println("Size " + constructionDefect.getDefectParameters().size());

        for (int i = 0; i < constructionDefect.getDefectParameters().size(); i++) {

            DefectParameter defectParameter = (DefectParameter) constructionDefect.getDefectParameters().get(i);
            defectParameter.setConstructionDefectId(constructionDefect.getConstructionDefectId());
            System.out.println("parametr = " + constructionDefect.getConstructionDefectId());
            defectParameter.setDefectParameterPosition(new Integer(i));
            session.save(defectParameter);
            System.out.println("parametr id " + defectParameter.getDefectParameterId());

        }

        constructionExample.getExampleDefects().add(constructionDefect);
        session.save(constructionDefect);
        System.out.println("constructionDefect id = " + constructionDefect.getConstructionDefectId());

        session.clear();

        // Query query = session.createQuery("update DefectParameter set constructionDefectId=:constDef where defectParameterId=:defId");

        if (!id.equals(constructionDefect.getConstructionDefectId())) {
            for (int i = 0; i < constructionDefect.getDefectParameters().size(); i++) {

                System.out.println("UPdate");
                DefectParameter defectParameter = (DefectParameter) constructionDefect.getDefectParameters().get(i);

                defectParameter.setConstructionDefectId(constructionDefect.getConstructionDefectId());
                session.update(defectParameter);

                System.out.println(defectParameter.getDefectParameterId().longValue());
                System.out.println(constructionDefect.getConstructionDefectId().longValue());
                /* query.setLong("defId", defectParameter.getDefectParameterId().longValue());
                                query.setLong("constDef", constructionDefect.getConstructionDefectId().longValue());
                */


            }
        }
        session.flush();

        session.clear();
        session.update(constructionExample);

    }


    public void save(ConstructionExample constructionExample, Strength strength) {


        strength.setPointPosition(getMaxStrengthPosition(constructionExample.getExampleId()));

        constructionExample.getStrengthPoints().add(strength);
        session.save(strength);
        session.clear();
        session.update(constructionExample);

    }


    public String getDefectConstructionNumber(String exampleId) {
        try {
            ConstructionExample constructionExample = (ConstructionExample) session.get(ConstructionExample.class, new Long(exampleId));
            session.evict(constructionExample);
            return constructionExample.getExampleRelativeNumber() + "." + (constructionExample.getExampleDefects().size() + 1);
        } catch (Exception e) {
            return "0.0.0.1";
        }
    }


    public Integer getPosition(Integer id) {
      Integer max = (Integer) session.createQuery("select max(constructionDefect.constructionDefectPosition) from ConstructionDefect constructionDefect where  constructionDefect.exampleId=" + id).uniqueResult();


        if (max == null) {
            return new Integer(0);
        }
        return (Integer) (max + 1);
    }


    public String getPointNumber(String exampleId) {
        try {
            ConstructionExample constructionExample = (ConstructionExample) session.get(ConstructionExample.class, new Long(exampleId));
            return constructionExample.getExampleRelativeNumber() + "." + (constructionExample.getStrengthPoints().size() + 1);
        } catch (Exception e) {
            return "1.0.1";
        }

    }


    public ConstructionExample getConstructionExample2(final Long exampleId) {
        ConstructionExample constructionExample = (ConstructionExample) session.get(ConstructionExample.class, exampleId);
        if (constructionExample == null) {
            throw new ObjectRetrievalFailureException(ConstructionExample.class, exampleId);
        }
        return constructionExample;
    }


    private void copy() throws IOException {

        String copyPath = fullPath + "copy.jpg";

        if (nowObject != null) {

            ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream(copyPath));
            out.writeObject(nowObject);
            out.close();


        }
    }

    private void insert() throws IOException {

        String insertPath = fullPath + "copy.jpg";

        ObjectInputStream in = new ObjectInputStream(new FileInputStream(insertPath));
        try {
            GlobalPicture globalPicture = (GlobalPicture) in.readObject();
            if (objectPicture != null) {

                //!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!

                globalPicture.scale = mashtab;
                objectPicture.addObject(globalPicture);
                globalPicture.draw(getGraphics(), paperScrollX, paperScrollY, appletWidth, appletHeight);

                save();

            }
        } catch (ClassNotFoundException e) {
            System.out.println("ClassNotFoundException");
            e.printStackTrace();
        }
        in.close();
    }


    private void insert(int x, int y) throws IOException {

        String insertPath = fullPath + "copy.jpg";

        ObjectInputStream in = new ObjectInputStream(new FileInputStream(insertPath));
        try {
            GlobalPicture globalPicture = (GlobalPicture) in.readObject();
            if (objectPicture != null) {

                //!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!

                globalPicture.scale = mashtab;
                globalPicture.move(x, y);
                objectPicture.addObject(globalPicture);
                globalPicture.draw(getGraphics(), paperScrollX, paperScrollY, appletWidth, appletHeight);

                save();

            }
        } catch (ClassNotFoundException e) {
            System.out.println("ClassNotFoundException");
            e.printStackTrace();
        }
        in.close();
    }


    private void save() {


        ObjectOutputStream out = null;
        try {


            nowHistory = (nowHistory + 1) % HISTORY_STEP;
            lastHistory = nowHistory;


            out = new ObjectOutputStream(new FileOutputStream(historyPath + nowHistory + historyFile));
            out.writeObject(objectPicture);
            out.close();


            nextHistory.setEnabled(false);
            prewHistory.setEnabled(true);


        } catch (IOException ee) {
            ee.printStackTrace()//To change body of catch statement use File | Settings | File Templates.
        }
    }


    private void returnPicture() {


        if (nowHistory == lastHistory) {
            nextHistory.setEnabled(false);
            prewHistory.setEnabled(true);
        } else if (nowHistory - 1 == lastHistory) {
            nextHistory.setEnabled(true);
            prewHistory.setEnabled(false);
        } else {
            nextHistory.setEnabled(true);
            prewHistory.setEnabled(true);
        }

        ObjectInputStream in = null;
        try {

            in = new ObjectInputStream(new FileInputStream(historyPath + nowHistory + historyFile));
            try {
                objectPicture = (ObjectPicture) in.readObject();
                if (objectPicture != null) {
                    objectPicture.drawObjects(image.getGraphics(), paperScrollX, paperScrollY);
                    getGraphics().drawImage(image, paperX, paperY, null);


                }
            } catch (ClassNotFoundException e1) {
                e1.printStackTrace()//To change body of catch statement use File | Settings | File Templates.
            }
            in.close();
        } catch (IOException e1) {
            e1.printStackTrace()//To change body of catch statement use File | Settings | File Templates.
        }
    }


    private void painSelectRectangle(Graphics graphics, MyPoint minPoint, MyPoint maxPoint) {
        for (int x = minPoint.x; x <= maxPoint.x - 15; x += 30) {
            graphics.drawLine(x, minPoint.y, x + 15, minPoint.y);
            graphics.drawLine(x, maxPoint.y, x + 15, maxPoint.y);
        }
        for (int y = minPoint.y; y <= maxPoint.y - 15; y += 30) {
            graphics.drawLine(minPoint.x, y, minPoint.x, y + 15);
            graphics.drawLine(maxPoint.x, y, maxPoint.x, y + 15);
        }
    }


    private Symbols createStrength() {
        ObjectPicture objectPicture1 = new ObjectPicture();
        Line line = new Line();
        line.setFirstPoint(new MyPoint(100, 100));
        line.setSecondPoint(new MyPoint(110, 110));
        objectPicture1.addObject(line);
        line = new Line();
        line.setFirstPoint(new MyPoint(110, 100));
        line.setSecondPoint(new MyPoint(100, 110));
        objectPicture1.addObject(line);
        line = new Line();
        line.setFirstPoint(new MyPoint(105, 100));
        line.setSecondPoint(new MyPoint(105, 110));
        objectPicture1.addObject(line);
        line = new Line();
        line.setFirstPoint(new MyPoint(110, 105));
        line.setSecondPoint(new MyPoint(100, 105));
        objectPicture1.addObject(line);

        Symbols symbols = new Symbols(objectPicture1);

        symbols.getTextLineList().add(new TextLine(100, 95, texPoint.getText()));
        symbols.getTextLineList().add(new TextLine(100, 85, String.valueOf("№ " + strength.getPointRelativeNumber())));


        return symbols;
    }

    private Symbols updateStrength(ConstructionExample constructionExample) {

        Symbols s = (Symbols) nowObject;
        Symbols symbols = new Symbols();
        symbols.list = s.list;
        MyPoint point = symbols.getMaxPoint();

        symbols.getTextLineList().add(new TextLine(point.x - 10, point.y - 20, texPoint.getText(), mashtab));
        symbols.getTextLineList().add(new TextLine(point.x - 10, point.y - 10, String.valueOf("№ " + strength.getPointRelativeNumber()), mashtab));

        symbols.setExample(constructionExample);
        symbols.setStrength(strength);
        symbols.setActivity("new");
        symbols.setType("point");

        return symbols;

    }


    private com.mysql.jdbc.Connection createConnection(String currentPath) throws IOException {

        Properties props = new Properties();

        props.setProperty("driver.url", "jdbc:mysql://localhost/vstbase");
        props.setProperty("driver.class", "com.mysql.jdbc.Driver");
        props.setProperty("user", "root");
        props.setProperty("password", "");

        String driverURL = "jdbc:mysql://localhost/vstbase?useUnicode=true&amp;characterEncoding=UTF-8";
        com.mysql.jdbc.Connection dbConn = null;
        try {
            Class.forName("com.mysql.jdbc.Driver");
            dbConn = (com.mysql.jdbc.Connection) DriverManager.getConnection(driverURL, props);
            return dbConn;
        }
        catch (Exception e) {
            e.printStackTrace();
            return null;
        }


    }


    private void deleteObject() {

        if (nowObject != null) {


            if (nowObject instanceof Symbols && (((Symbols) nowObject).getType().equals("point") || ((Symbols) nowObject).getType().equals("defect"))) {

                Symbols symbols = (Symbols) nowObject;
                if (symbols.getActivity().equals("new")) {
                    symbols.setActivity("nothing");
                } else if (symbols.getActivity().equals("old")) {
                    symbols.setActivity("delete");
                }

            } else {
                objectPicture.deleteObject(nowObject);
            }


        } else {
            objectPicture.deleteGroupObject();
        }

        objectPicture.drawObjects(image.getGraphics(), paperScrollX, paperScrollY);
        getGraphics().drawImage(image, paperX, paperY, null);


    }

    private int changeX(int x) {
        return (int) (paperScrollX + x / mashtab);
    }

    private int changeY(int y) {
        return (int) (paperScrollY + y / mashtab);
    }

    private void drawLine(int x1, int y1, int x2, int y2, Graphics graphics) {
        graphics.drawLine((int) ((x1 - paperScrollX) * mashtab), (int) ((y1 - paperScrollY) * mashtab), (int) ((x2 - paperScrollX) * mashtab), (int) ((y2 - paperScrollY) * mashtab));
    }

    public void fillRect(Graphics graphics, int leftTopPointX, int leftTopPointY, int width, int height) {
        graphics.fillRect((int) ((leftTopPointX - paperScrollX) * mashtab), (int) ((leftTopPointY - paperScrollY) * mashtab), (int) (width * mashtab), (int) (mashtab * height));
    }

    public void drawOval(Graphics graphics, int leftTopPointX, int leftTopPointY, int width, int height) {
        graphics.drawOval((int) ((leftTopPointX - paperScrollX) * mashtab), (int) ((leftTopPointY - paperScrollY) * mashtab), (int) (width * mashtab), (int) (height * mashtab));
    }

    public void drawString(Graphics graphics, MyPoint point, String text) {
        graphics.drawString(text, (int) ((point.x - paperScrollX) * mashtab), (int) ((point.y - paperScrollY) * mashtab));
    }


    public void createDialog2(final DetailSymbol detail) {


        final JFrame jfrm = new JFrame("Вставка конструкций");
        int height = 170;
        int weight = 400;
        jfrm.setBounds((SCREEN_WEIGHT - weight) / 2, (SCREEN_HEIGHT - height) / 2, weight, height);
        // jfrm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        jfrm.setLayout(new GridLayout(0, 1));
        JLabel label1 = new JLabel("Добавить конструкции от ячейки с координатами:");
        jfrm.add(label1);
        final JTextField textField1x = new JTextField("x(число от 1 до 100)");
        final JTextField textField1y = new JTextField("y(латиская, заглавная буква)");
        JPanel panel1 = new JPanel();
        panel1.setLayout(new BoxLayout(panel1, BoxLayout.X_AXIS));
        panel1.add(textField1x);
        panel1.add(textField1y);


        jfrm.add(panel1);

        JLabel label2 = new JLabel("До от ячейки с координатами:");
        jfrm.add(label2);

        final JTextField textField2x = new JTextField("x(число от 1 до 100)");
        final JTextField textField2y = new JTextField("y(латиская, заглавная буква)");

        JPanel panel2 = new JPanel();
        panel2.setLayout(new BoxLayout(panel2, BoxLayout.X_AXIS));
        panel2.add(textField2x);
        panel2.add(textField2y);

        jfrm.add(panel2);

        JButton addButton = new JButton("Добавить");
        JButton cancelButton = new JButton("Отмена");


        JPanel panel3 = new JPanel();
        panel3.setLayout(new BoxLayout(panel3, BoxLayout.X_AXIS));
        panel3.add(addButton);
        panel3.add(cancelButton);


        jfrm.getContentPane().add(panel3);
        jfrm.setVisible(true);
        jfrm.setResizable(false);

        addButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                if (testCharTextField(textField1x, 1, 100, "Введите число от 1 до 100") &
                        testCharTextField(textField1y) &
                        testCharTextField(textField2x, 1, 100, "Введите число от 1 до 100") &
                        testCharTextField(textField2y)) {

                    int x1 = Integer.parseInt(textField1x.getText()) - 1;
                    int y1 = textField1y.getText().toCharArray()[0] - 65;
                    int x2 = Integer.parseInt(textField2x.getText()) - 1;
                    int y2 = textField2y.getText().toCharArray()[0] - 65;

                    System.out.println(x1 + " " + y1 + " " + x2 + " " + y2);

                    if (y1 < y2 || (y1 == y2 && x1 < x2)) {
                        minCountForDiapazoneX = x1;
                        minCountForDiapazoneY = y1;
                        maxCountForDiapazoneX = x2;
                        maxCountForDiapazoneY = y2;
                    } else {
                        minCountForDiapazoneX = x2;
                        minCountForDiapazoneY = y2;
                        maxCountForDiapazoneX = x1;
                        maxCountForDiapazoneY = y1;
                    }


                    addDetailInLevelPlan(detail, jfrm);


                }
            }
        });

        cancelButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                jfrm.dispose();
            }
        });

        jfrm.setVisible(true);

    }

    public void createDialog1() {


        final JFrame jfrm = new JFrame("Ввод количества линий");

        int height = 150;
        int weight = 300;
        jfrm.setBounds((SCREEN_WEIGHT - weight) / 2, (SCREEN_HEIGHT - height) / 2, weight, height);


        jfrm.setLayout(new GridLayout(0, 1));

        JLabel label1 = new JLabel("По оси Х");
        final JTextField textField1x = new JTextField("(число от 1 до 100)");

        JPanel panel1 = new JPanel();
        panel1.setLayout(new BoxLayout(panel1, BoxLayout.Y_AXIS));
        panel1.add(label1);
        panel1.add(textField1x);

        JLabel label2 = new JLabel("По Оси У");
        final JTextField textField1y = new JTextField("(число от 1 до 26)");


        JPanel panel2 = new JPanel();
        panel2.setLayout(new BoxLayout(panel2, BoxLayout.Y_AXIS));
        panel2.add(label2);
        panel2.add(textField1y);

        JButton addButton = new JButton("Добавить");
        JButton cancelButton = new JButton("Отмена");

        JPanel panel3 = new JPanel();
        panel3.setLayout(new BoxLayout(panel3, BoxLayout.X_AXIS));
        panel3.add(addButton);
        panel3.add(cancelButton);

        jfrm.getContentPane().add(panel1);
        jfrm.getContentPane().add(panel2);
        jfrm.getContentPane().add(panel3);
        jfrm.setVisible(true);
        jfrm.setResizable(false);

        addButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {

                if (testCharTextField(textField1x, 1, 100, "Введите число от 1 до 100") &
                        testCharTextField(textField1y, 1, 26, "Введите число от 1 до 26")
                        ) {

                    baseCountX = Integer.parseInt(textField1x.getText());
                    baseCountY = Integer.parseInt(textField1y.getText());

                    System.out.println(baseCountX);
                    System.out.println(baseCountY);

                    createMassiv();
                    jfrm.dispose();

                    objectPicture.drawObjects(image.getGraphics(), paperScrollX, paperScrollY);
                    getGraphics().drawImage(image, 0, 0, null);

                }


            }
        });

        cancelButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                jfrm.dispose();
            }
        });


    }


    void createMassiv() {

        System.out.println(IMAGE_SIZE_HORZ / baseCountX);

        objectPicture.levelPlanInformation = new LevelPlanInformation[baseCountX][baseCountY];

        for (int x = 0; x < baseCountX; x++) {
            for (int y = 0; y < baseCountY; y++) {

                objectPicture.levelPlanInformation[x][y] = new LevelPlanInformation(IMAGE_SIZE_HORZ / baseCountX, IMAGE_SIZE_VERT / baseCountY, x, y, mashtab);

            }
        }


    }


    private boolean testCharTextField(JTextField textField, int minVal, int maxVal, String message) {
        if (textField.getText().equals("")) {
            textField.setText(message);
            return false;
        } else {
            int ch = Integer.parseInt(textField.getText());
            if (ch >= minVal && ch <= maxVal) {
                return true;
            } else {
                textField.setText(message);
                return false;
            }
        }
    }

    private boolean testCharTextField(JTextField textField) {
        if (textField.getText().equals("")) {
            textField.setText("Введите латинскую заглавную букву");
            return false;
        } else {
            char[] ch = textField.getText().toCharArray();
            if (ch.length == 1 && ch[0] >= 65 && ch[0] <= 65 + 26) {
                return true;
            } else {
                textField.setText("Введите латинскую заглавную букву");
                return false;
            }
        }
    }

    private void isNotFreeDialog(final DetailSymbol detail, final JFrame generalFrame) {

        final JFrame jfrm = new JFrame("!");

        int height = 150;
        int weight = 600;
        jfrm.setBounds((SCREEN_WEIGHT - weight) / 2, (SCREEN_HEIGHT - height) / 2, weight, height);


        jfrm.setLayout(new GridLayout(0, 1));
        JLabel label1 = new JLabel("В введенном вами диапазоне уже существуют конструкции");
        jfrm.getContentPane().add(label1);
        JButton addButton1 = new JButton("Вставить с заменой");
        JButton addButton2 = new JButton("Вставить в свободные ячейки");
        JButton cancelButton = new JButton("Отмена");
        JPanel panel1 = new JPanel();
        panel1.setLayout(new BoxLayout(panel1, BoxLayout.X_AXIS));
        panel1.add(addButton1);
        panel1.add(addButton2);
        panel1.add(cancelButton);
        jfrm.getContentPane().add(panel1);
        jfrm.setVisible(true);
        jfrm.setResizable(false);
        addButton1.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {

                addDetailSymbol(detail, fullPath, null, null, "detail", "replacement", minCountForDiapazoneX, minCountForDiapazoneY, maxCountForDiapazoneX, maxCountForDiapazoneY);
                jfrm.dispose();
                generalFrame.dispose();

            }
        });

        addButton2.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {

                addDetailSymbol(detail, fullPath, null, null, "detail", "", minCountForDiapazoneX, minCountForDiapazoneY, maxCountForDiapazoneX, maxCountForDiapazoneY);
                jfrm.dispose();
                generalFrame.dispose();

            }
        });

        cancelButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                jfrm.dispose();
            }
        });


    }


    public void addStaticComponent() {

        paramPanel.add(new JLabel("Зона конструкции"));
        paramPanel.add(choiceConstZone);

        paramPanel.add(new JLabel("Категория опасности"));
        paramPanel.add(choiceDanger);

        paramPanel.add(new JLabel("Тип дефекта"));
        paramPanel.add(choiceDefType);


        paramPanel.add(new JLabel("Характер дефекта"));
        paramPanel.add(choiceDefVar);

        paramPanel.add(new JLabel("Причина"));
        paramPanel.add(choiceReason);


        paramPanel.add(new JLabel("Другая причина"));
        paramPanel.add(textDiffReason);


        paramPanel.add(new JLabel("Привязка экземпляра к оси"));


        paramPanel.add(new JLabel(""));


        paramPanel.add(examplesCheck);
        paramPanel.add(textName);

    }

    public void addStaticButtons(String type) {

        JButton button = new JButton("Отмена");
        button.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                defectFrame.dispose();
            }
        });

        paramPanel.add(button);
        if (type.equals("insert")) {
            paramPanel.add(buttonForEskizDefect);
        } else if (type.equals("update")) {
            paramPanel.add(buttonForEskizDefectUpdate);
        }


    }

/*

    public void windowOpened(WindowEvent e) {
        System.out.println("windowOpened");
    }

    public void windowClosing(WindowEvent e) {

        System.out.println("windowClosing");

        final JFrame closeFrame = new JFrame("!");
        closeFrame.setLayout(new GridLayout(0, 1));

        closeFrame.add(new JLabel("Сохранить изображение перед выходом?"));

        JPanel panel = new JPanel();
        panel.setLayout(new BoxLayout(panel, BoxLayout.X_AXIS));

        JButton buttonYes = new JButton("Да");
        buttonYes.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                saveImage();
                closeFrame.dispose();
                System.exit(0);


            }
        });
        JButton buttonNo = new JButton("Нет");
        buttonNo.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                pointFrame.dispose();
                System.exit(0);

            }
        });
        JButton buttonCansel = new JButton("Отмена");
        buttonCansel.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                pointFrame.dispose();
            }
        });

        panel.add(buttonYes);
        panel.add(buttonNo);
        panel.add(buttonCansel);


        closeFrame.add(panel);


        int height = 80;
        int weight = 400;
        closeFrame.setBounds((SCREEN_WEIGHT - weight) / 2, (SCREEN_HEIGHT - height) / 2, weight, height);


        closeFrame.setVisible(true);
        closeFrame.setResizable(false);
    }

    public void windowClosed(WindowEvent e) {
        System.out.println("windowClosed");
    }

    public void windowIconified(WindowEvent e) {
        //To change body of implemented methods use File | Settings | File Templates.
    }

    public void windowDeiconified(WindowEvent e) {
        //To change body of implemented methods use File | Settings | File Templates.
    }

    public void windowActivated(WindowEvent e) {
        //To change body of implemented methods use File | Settings | File Templates.
    }

    public void windowDeactivated(WindowEvent e) {
        //To change body of implemented methods use File | Settings | File Templates.
    }
*/


    public void showPopUpMenu(MouseEvent e) {

        menuGroup.setEnabled(true);

        if (nowObject == null) {
            menuCopy.setEnabled(false);
            menuMove.setEnabled(false);
            menuDelete.setEnabled(false);
            menuUnGroup.setEnabled(false);
            menuUpdateDefect.setEnabled(false);
            menuUpdatePoint.setEnabled(false);
        } else {
            menuCopy.setEnabled(true);
            menuMove.setEnabled(true);
            menuDelete.setEnabled(true);
            menuGroup.setEnabled(true);
        }

        if (!(nowObject != null && (nowObject instanceof Symbols))) {
            menuUnGroup.setEnabled(false);
        } else {
            menuUnGroup.setEnabled(true);
        }

        if (nowObject != null && nowObject instanceof Symbols && ((Symbols) nowObject).getType().equals("defect")) {
            menuUpdateDefect.setEnabled(true);
            menuUnGroup.setEnabled(false);
            menuGroup.setEnabled(false);
        } else {
            menuUpdateDefect.setEnabled(false);
        }

        if (nowObject != null && nowObject instanceof Symbols && ((Symbols) nowObject).getType().equals("point")) {
            menuUpdatePoint.setEnabled(true);
            menuUnGroup.setEnabled(false);
            menuGroup.setEnabled(false);
        } else {
            menuUpdatePoint.setEnabled(false);
        }

        RIGHT_MOUSE_X = e.getX();
        RIGHT_MOUSE_Y = e.getY();

        popupMenu.show(e.getComponent(), e.getX(), e.getY());


    }


    private void setComboBoxes(DefectType defectType,
                               DefectVarity defectVarity, Symbols symbols) {

        if (getParameter("objectConstructionId") != null && !getParameter("objectConstructionId").trim().equals("")) {
            constExmpList = getConstructionExample(Long.valueOf(getParameter("objectConstructionId")));
            setChoice(constExmpList, examplesCheck);
        }


        listDefectType = new ArrayList();
        listDefectType.add(defectType);
        setChoice(listDefectType, choiceDefType);
        choiceDefType.setEnabled(false);

        listDefectZones = session.createQuery("select constructionType.defectZones from ConstructionType constructionType where constructionType.constructionTypeId=?").setString(0, getParameter("constructionId")).list();
        setChoice(listDefectZones, choiceConstZone);

        listDanger = session.createQuery("from DangerCategory").list();
        setChoice(listDanger, choiceDanger);


        if (symbols != null) {
            listDefVar = defectType.getVarities();
            setChoice(listDefVar, choiceDefVar);

            System.out.println("Update!!!!!!!!!!!!!!!!");
            System.out.println(symbols.getDefect().getConstructionDefectId());
            System.out.println(symbols.getDefect().getDefectParameters().size());

            createExamplesCheckAndParams(symbols.getDefect().getDefectParameters(), "update");

        } else {
            if (defectVarity != null) {

                System.out.println("defect varity != null");
                System.out.println(defectVarity.getVarityId());

                listDefVar = new ArrayList();
                listDefVar.add(defectVarity);
                setChoice(listDefVar, choiceDefVar);
                choiceDefVar.setEnabled(false);
                defctParamList = getDefectParametersByVarityId(defectVarity.getVarityId());
                createExamplesCheckAndParams(defctParamList, "insert");
            } else {

                System.out.println("defect varity == null");
                System.out.println(defectType.getDefectTypeId());

                DefectType defType = (DefectType) session.get(DefectType.class, defectType.getDefectTypeId());
                listDefVar = defType.getVarities();
                setChoice(listDefVar, choiceDefVar);
                if (choiceDefVar.getSelectedIndex() >= 0 && choiceDefVar.getSelectedIndex() < listDefVar.size()) {
                    DefectVarity curDefectVarity = (DefectVarity) listDefVar.get(choiceDefVar.getSelectedIndex());
                    defctParamList = getDefectParametersByVarityId(curDefectVarity.getVarityId());
                    createExamplesCheckAndParams(defctParamList, "insert");
                }
            }
        }


    }


    private void changeReasonList() {

        if (getParameter("constructionId") != null && !getParameter("constructionId").trim().equals("")
                && choiceDefType.getSelectedIndex() >= 0 && choiceDefType.getSelectedIndex() < listDefectType.size()
                && choiceDefVar.getSelectedIndex() >= 0 && choiceDefVar.getSelectedIndex() < listDefVar.size()
                && choiceConstZone.getSelectedIndex() >= 0 && choiceConstZone.getSelectedIndex() < listDefectZones.size()
                ) {
            DefectType defectType = (DefectType) listDefectType.get(choiceDefType.getSelectedIndex());
            DefectVarity varity = (DefectVarity) listDefVar.get(choiceDefVar.getSelectedIndex());
            DefectZone defectZone = (DefectZone) listDefectZones.get(choiceConstZone.getSelectedIndex());
            listReason = session.createQuery("from Reason res   where res.defectType.defectTypeId=? AND res.defectVarity.varityId=? AND res.defectZone.defectZoneId=? AND res.constructionType.constructionTypeId=?").setLong(0, defectType.getDefectTypeId().longValue()).setLong(1, varity.getVarityId().longValue()).setLong(2, defectZone.getDefectZoneId().longValue()).setString(3, getParameter("constructionId")).list();
            setChoice(listReason, choiceReason);
        }


    }


    private void updateMassiv() {

        LevelPlanInformation[][] levelPlan = new LevelPlanInformation[objectPicture.levelPlanInformation.length][objectPicture.levelPlanInformation[0].length];
        for (int i = 0; i < objectPicture.levelPlanInformation.length; i++) {
            System.arraycopy(objectPicture.levelPlanInformation[i], 0, levelPlan[i], 0, objectPicture.levelPlanInformation[i].length);
        }

        createNewMassiv();

        for (int x = 0; x < levelPlan.length; x++) {
            for (int y = 0; y < levelPlan[x].length; y++) {
                if (levelPlan[x][y].getSymbols() != null) {
                    objectPicture.levelPlanInformation[x][y].setSymbols(levelPlan[x][y].getSymbols(), mashtab);
                }

            }
        }
    }


    private void createNewMassiv() {

        System.out.println("create massiv");
        System.out.println("baseCountX = " + baseCountX);
        System.out.println("baseCountY = " + baseCountY);

        objectPicture.levelPlanInformation = new LevelPlanInformation[baseCountX][baseCountY];

        for (int x = 0; x < baseCountX; x++) {
            for (int y = 0; y < baseCountY; y++) {

                objectPicture.levelPlanInformation[x][y] = new LevelPlanInformation(IMAGE_SIZE_HORZ / baseCountX, IMAGE_SIZE_VERT / baseCountY, x, y, mashtab);

            }
        }

    }

    private void addDetailInLevelPlan(final DetailSymbol detail, JFrame jfrm) {

        if (objectPicture.levelPlanInformation == null) {


            baseCountX = Math.max(minCountForDiapazoneX, maxCountForDiapazoneX) + 1;
            baseCountY = Math.max(minCountForDiapazoneY, maxCountForDiapazoneY) + 1;

            createNewMassiv();

            addDetailSymbol(detail, fullPath, null, null, "detail", "", minCountForDiapazoneX, minCountForDiapazoneY, maxCountForDiapazoneX, maxCountForDiapazoneY);

            jfrm.dispose();
        } else {

            baseCountX = Math.max(minCountForDiapazoneX, maxCountForDiapazoneX) + 1;
            baseCountY = Math.max(minCountForDiapazoneY, maxCountForDiapazoneY) + 1;

            System.out.println("real size");
            System.out.println(objectPicture.levelPlanInformation.length);
            System.out.println(objectPicture.levelPlanInformation[0].length);
            System.out.println("needed size");
            System.out.println(baseCountX);
            System.out.println(baseCountY);


            if (objectPicture.levelPlanInformation.length < baseCountX ||
                    objectPicture.levelPlanInformation[0].length < baseCountY) {


                baseCountX = Math.max(objectPicture.levelPlanInformation.length, baseCountX);
                baseCountY = Math.max(objectPicture.levelPlanInformation[0].length, baseCountY);

                System.out.println("измняем и вставляем");
                updateMassiv();
                addDetailInLevelPlan(detail, jfrm);

            } else {

                System.out.println("addDetailSymbol || isNotFreeDialog");

                if (objectPicture.isFree(minCountForDiapazoneX, minCountForDiapazoneY, maxCountForDiapazoneX, maxCountForDiapazoneY)) {
                    System.out.println("addDetailSymbol");
                    addDetailSymbol(detail, fullPath, null, null, "detail", "", minCountForDiapazoneX, minCountForDiapazoneY, maxCountForDiapazoneX, maxCountForDiapazoneY);
                    jfrm.dispose();
                } else {

                    isNotFreeDialog(detail, jfrm);

                }

            }

        }
    }


    private void createDefectFrame(Symbols symbols) {


        int select = choiceEskizDefect.getSelectedIndex();

        if ((select >= 0 && select < defectList.size()) || symbols != null) {

            defectFrame = new JFrame("Добавить дефект");

            defectFrame.setLayout(new GridLayout(0, 1));

            paramPanel.removeAll();

            paramPanel.setLayout(new GridLayout(0, 2));

            addStaticComponent();

            if (symbols != null) {

                System.out.println("symbols != null");
                addStaticButtons("update");
            } else {
                System.out.println("symbols == null");
                addStaticButtons("insert");
            }


            defectFrame.getContentPane().add(paramPanel);

            int height = 300;
            int weight = 400;
            if (symbols != null) {
                defectFrame.setBounds(1000 - weight, 500 - height, weight, height);
            } else {
                defectFrame.setBounds((SCREEN_WEIGHT - weight) / 2, (SCREEN_HEIGHT - height) / 2, weight, height);
            }


            defectFrame.setVisible(true);
            defectFrame.setResizable(false);

            DefectType defectType;
            DefectVarity defectVarity;
            if (symbols != null) {
                defectType = symbols.getDefect().getDefectType();
                defectVarity = symbols.getDefect().getDefectVarity();
            } else {
                DetailSymbol detailSymbol = (DetailSymbol) defectList.get(select);
                defectType = detailSymbol.getDefectType();
                defectVarity = detailSymbol.getDefectVarity();
            }

            setComboBoxes(defectType, defectVarity, symbols);

            if (symbols != null) {

                choiceConstZone.setSelectedItem(symbols.getDefect().getDefectZone().getDefectZoneName());
                choiceDanger.setSelectedItem(symbols.getDefect().getDangerCategory().getCategoryName());
                choiceDefType.setSelectedItem(symbols.getDefect().getDefectType().getDefectTypeName());
                choiceDefVar.setSelectedItem(symbols.getDefect().getDefectVarity().getVarityName());
                choiceReason.setSelectedItem(symbols.getDefect().getReason().getReasonName());
                textDiffReason.setText(symbols.getDefect().getOtherReason());

                String s = String.valueOf(symbols.getExample().getExampleRelativeNumber());
                if (symbols.getExample().getExampleName() != null && !symbols.getExample().getExampleName().trim().equals("")) {
                    s = symbols.getExample().getExampleName();
                }
                examplesCheck.setSelectedItem(s);

                System.out.println("setText");
                for (int i = 0; i < symbols.getDefect().getDefectParameters().size(); i++) {
                    DefectParameter defectParameter = (DefectParameter) symbols.getDefect().getDefectParameters().get(i);
                    System.out.println(i + ": " + defectParameter.getParameterValue());
                    if (paramText[i] != null) {
                        paramText[i].setText(String.valueOf(defectParameter.getParameterValue()));
                    }

                }


            }


        }


    }


    private boolean testText(String s) {
        if (!s.trim().equals("")) {
            char[] c = s.toCharArray();
            int k = 0;
            for (int i = 0; i < c.length; i++) {

                if (c[i] == '.') {
                    k++;
                }

                if (((c[i] < '0' || c[i] > '9') && c[i] != '.') || k > 1) {
                    return false;
                }
            }
            return true;
        } else {
            return false;
        }

    }


    private void paintLittleStar(Graphics graphics, int x, int y) {

        graphics.drawLine(x - 3, y - 3, x + 3, y + 3);
        graphics.drawLine(x - 3, y + 3, x + 3, y - 3);
        graphics.drawLine(x, y + 3, x, y - 3);
        graphics.drawLine(x - 3, y, x + 3, y);

    }


    private void showPointDialog(Symbols symbols) {

        constExmpList = getConstructionExample(Long.valueOf(getParameter("objectConstructionId")));
        setChoice(constExmpList, examplesCheck);

        if (symbols != null) {
            examplesCheck.setSelectedItem(symbols.getStrength().getPointRelativeNumber());
            pointFrame = new JFrame("Изменить точку замера");

        } else {
            pointFrame = new JFrame("Добавить точку замера");

        }

        pointFrame.setLayout(new GridLayout(0, 2));

        pointFrame.add(new JLabel("Прочность в этой точке"));
        pointFrame.add(texPoint);
        pointFrame.add(labeName);
        pointFrame.add(new JLabel(""));
        pointFrame.add(examplesCheck);
        pointFrame.add(textName);

        JButton button = new JButton("Отмена");
        button.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                pointFrame.dispose();
            }
        });

        pointFrame.add(button);


        if (symbols == null) {

            pointFrame.add(buttonAddPoit);

            int height = 140;
            int weight = 400;
            pointFrame.setBounds((SCREEN_WEIGHT - weight) / 2, (SCREEN_HEIGHT - height) / 2, weight, height);

        } else {
            pointFrame.add(buttonAddPoitUpdate);

            int height = 140;
            int weight = 400;
            pointFrame.setBounds((1000 - weight), (500 - height), weight, height);

            ConstructionExample constructionExample = (ConstructionExample) session.get(ConstructionExample.class, symbols.getStrength().getExampleId());
            String s = String.valueOf(constructionExample.getExampleRelativeNumber());
            if (constructionExample.getExampleName() != null && !constructionExample.getExampleName().trim().equals("")) {
                s = constructionExample.getExampleName();
            }
            examplesCheck.setSelectedItem(s);
            texPoint.setText(String.valueOf(symbols.getStrength().getStrengthValue()));


        }


        int height = 140;
        int weight = 400;
        pointFrame.setBounds((SCREEN_WEIGHT - weight) / 2, (SCREEN_HEIGHT - height) / 2, weight, height);


        pointFrame.setVisible(true);
        pointFrame.setResizable(false);
    }


    private ConstructionExample createStrengthAndTakeConstructionExample(int j) {
        ConstructionExample constructionExample = new ConstructionExample();
        if (j >= 0 && j < constExmpList.size()) {
            constructionExample = (ConstructionExample) constExmpList.get(j);
        } else if (j == constExmpList.size()) {
            ObjectConstruction objectConstruction = (ObjectConstruction) session.get(ObjectConstruction.class, Long.valueOf(getParameter("objectConstructionId")));
            try {
                constructionExample = createConstructionExample();
                save(objectConstruction, constructionExample);
            } catch (IOException ee) {
                ee.printStackTrace()//To change body of catch statement use File | Settings | File Templates.
            } catch (SQLException ee) {
                ee.printStackTrace()//To change body of catch statement use File | Settings | File Templates.
            }
        }

        Integer exampleId = constructionExample.getExampleId();

        strength = new Strength();
        String objId = getParameter("objectConstructionId");
        if (objId != null && !objId.equals("")) {
            Integer objectConstructionId = new Integer(Integer.parseInt(objId));
            strength.setPointRelativeNumber(new Integer(getPointNumberByObjectConstructionId(objectConstructionId) + strengthPointNum));
            strengthPointNum++;
        }
        strength.setStrengthValue(Float.valueOf(texPoint.getText()).floatValue());

        if (strength.getWayToEskiz() == null || strength.getWayToEskiz().equals("")) {
            strength.setWayToEskiz(constructionExample.getWayToPowerEsckiz());
        }

        strength.setExampleId(exampleId);
        strength.setAction(1);
        return constructionExample;
    }


    private ConstructionExample createConstructionExample(int j) {
        ConstructionExample constructionExample = new ConstructionExample();
        if (j >= 0 && j < constExmpList.size()) {
            return (ConstructionExample) constExmpList.get(j);

        } else if (j == constExmpList.size()) {
            ObjectConstruction objectConstruction = (ObjectConstruction) session.get(ObjectConstruction.class, Long.valueOf(getParameter("objectConstructionId")));
            try {
                constructionExample = createConstructionExample();
                save(objectConstruction, constructionExample);
                return constructionExample;

            } catch (IOException ee) {
                ee.printStackTrace();

            }
            catch (SQLException ee) {
                ee.printStackTrace();
            }

        }
        return constructionExample;
    }


    private ConstructionDefect createConstructionDefect(ConstructionExample constructionExample) {
        ConstructionDefect constructionDefect = new ConstructionDefect();
        constructionDefect.setExampleId(constructionExample.getExampleId());
        constructionDefect.setDefectNumber(getDefectConstructionNumber(constructionDefect.getExampleId().toString()));
        constructionDefect.setDefectZone((DefectZone) listDefectZones.get(choiceConstZone.getSelectedIndex()));
        constructionDefect.setDefectVarity((DefectVarity) listDefVar.get(choiceDefVar.getSelectedIndex()));
        constructionDefect.setDefectType((DefectType) listDefectType.get(choiceDefType.getSelectedIndex()));
        constructionDefect.setDangerCategory((DangerCategory) listDanger.get(choiceDanger.getSelectedIndex()));
        constructionDefect.setOtherReason(textDiffReason.getText());
        constructionDefect.setDefectRelativeNumber(new Integer(getDefectNumberByObjectConstructionId(constructionExample.getObjectConstructionId()) + defectNum));
        constructionDefect.setAction(1);

        defectNum++;
        if (choiceReason.getSelectedIndex() >= 0 && choiceReason.getSelectedIndex() < listReason.size()) {
            constructionDefect.setReason((Reason) listReason.get(choiceReason.getSelectedIndex()));
        }

        for (int i = 0; i < defctParamList.size(); i++) {
            System.out.println(i);
            if (paramText[i] != null) {
                System.out.println("paramText[" + i + "] != null");

                DefectParameter defectParameter = (DefectParameter) defctParamList.get(i);

                System.out.println(paramText[i].getText());

                defectParameter.setParameterValue(Float.valueOf(paramText[i].getText()).floatValue());
            } else {
                System.out.println("error?");
            }
        }

        constructionDefect.setDefectParameters(defctParamList);

        return constructionDefect;

    }

    /*


    boolean sizeLineFlag = false;
    int sizeLinePoiuntCount = 0;

   SizeLine[] sizeLineList;
   TextLine[] textLineList;

    MyPoint firstPointInSizeLine=new MyPoint();
    MyPoint secondPointInSizeLine=new MyPoint();

    JFrame sizeLineCountFrame;
    JTextField[] textFieldSizeLineValues;


    */


    private void createSizeLineCountFrame() {

        sizeLineCountFrame = new JFrame("Ввод системы размеров");
        sizeLineCountFrame.setEnabled(true);
        sizeLineCountFrame.setVisible(true);
        sizeLineCountFrame.setLayout(new GridLayout(0, 1));

        JPanel panel0 = new JPanel();
        panel0.setLayout(new BoxLayout(panel0, BoxLayout.Y_AXIS));
        panel0.add(new JLabel("1. Выберите область нанесения размеров через графический редактор (2 точки)"));
        panel0.setEnabled(true);
        sizeLineCountFrame.add(panel0);


        JPanel panel1 = new JPanel();
        panel1.setLayout(new BoxLayout(panel1, BoxLayout.Y_AXIS));
        panel1.add(new JLabel("2. Общий размер"));
        final JTextField textField1 = new JTextField();
        panel1.add(textField1);
        panel1.add(new JLabel("Количество областей для нанесения размеров"));
        final JTextField textField2 = new JTextField();
        panel1.add(textField2);
        JButton buttonYes = new JButton("ok");
        buttonYes.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                if (textField1.getText().trim().equals("") || textField2.getText().trim().equals("")) {
                    if (textField1.getText().trim().equals("")) {
                        textField1.setText("Введите размер");
                    }
                    if (textField2.getText().trim().equals("")) {
                        textField1.setText("Введите количество областей");
                    }
                } else {
                    try {
                        sizeLinePoiuntCount = Integer.parseInt(textField2.getText());
                    }
                    catch (NumberFormatException q) {
                        textField2.setText("Введите текст");
                    }
                }
                //To change body of implemented methods use File | Settings | File Templates.
            }
        });
        panel1.add(buttonYes);
        panel1.setEnabled(false);
        sizeLineCountFrame.add(panel1);



        JPanel panel2 = new JPanel();
        panel2.setLayout(new BoxLayout(panel1, BoxLayout.Y_AXIS));
        panel2.add(new JLabel("3. Введите размеры областей"));
        panel2.setEnabled(false);
        sizeLineCountFrame.add(panel2);




        JPanel panel3 = new JPanel();
        panel3.setLayout(new BoxLayout(panel3, BoxLayout.X_AXIS));
        JButton buttonInsert = new JButton("ok");
        buttonInsert.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
            }
        });
        JButton buttonCansel = new JButton("ok");
        buttonCansel.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
            }
        });
        panel3.add(buttonCansel);
        panel3.add(buttonInsert);
        panel3.setEnabled(false);
        sizeLineCountFrame.add(panel3);


    }


}
TOP

Related Classes of com.vst.webapp.util.PainterApplet

TOP
Copyright © 2018 www.massapi.com. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.