Eliseev E.E. LabWork06 #6

Closed
ElEgEv wants to merge 8 commits from LabWork06 into LabWork05
12 changed files with 258 additions and 11 deletions
Showing only changes of commit f119611d50 - Show all commits

View File

@ -119,6 +119,15 @@
<item class="javax.swing.JScrollBar" icon="/com/intellij/uiDesigner/icons/scrollbar.png" removable="false" auto-create-binding="true" can-attach-label="false">
<default-constraints vsize-policy="6" hsize-policy="0" anchor="0" fill="2" />
</item>
<item class="javax.swing.JMenuBar" icon="" removable="true" auto-create-binding="false" can-attach-label="false" is-container="true">
<default-constraints vsize-policy="3" hsize-policy="3" anchor="0" fill="0" />
</item>
<item class="javax.swing.JMenu" icon="" removable="true" auto-create-binding="false" can-attach-label="false" is-container="true">
<default-constraints vsize-policy="3" hsize-policy="3" anchor="0" fill="0" />
</item>
<item class="javax.swing.JMenuItem" icon="" removable="true" auto-create-binding="false" can-attach-label="false">
<default-constraints vsize-policy="3" hsize-policy="3" anchor="0" fill="0" />
</item>
</group>
</component>
</project>

View File

@ -51,4 +51,9 @@ public class DrawingAirplaneWindow extends JComponent implements IAdditionalDraw
g2d.drawOval((int)_startPosX + 27, (int)_startPosY + 11, 6, 4);
}
}
@Override
public int GetAddEnum() {
return _airplaneWindowEnum.GetAddEnum();
}
}

View File

@ -54,6 +54,11 @@ public class DrawingPlane extends JPanel
_airplaneWindow.SetAddEnum(countWindow);
}
//кол-во иллюминаторов
public int GetWindows(){
return _airplaneWindow.GetAddEnum();
}
//конструктор
public DrawingPlane(int speed, float weight, Color corpusColor, int countWindow, int planeWidth, int planeHeight)
{

View File

@ -51,4 +51,9 @@ public class DrawingRectAirplaneWindow extends JComponent implements IAdditional
g2d.drawRect((int)_startPosX + 27, (int)_startPosY + 11, 6, 4);
}
}
@Override
public int GetAddEnum() {
return _airplaneWindowEnum.GetAddEnum();
}
}

View File

@ -60,4 +60,9 @@ public class DrawingTriangleAirplaneWindow extends JComponent implements IAdditi
g2d.drawPolygon(x_point, y_point, 3);
}
}
@Override
public int GetAddEnum() {
return _airplaneWindowEnum.GetAddEnum();
}
}

View File

@ -50,4 +50,18 @@ public class DrawningObjectPlane implements IDrawningObject
return null;
}
public String GetInfo()
{
if(_plane != null)
{
return ExtentionPlane.GetDataForSave(_plane);
}
return null;
}
public static IDrawningObject Create(String data)
{
return new DrawningObjectPlane(ExtentionPlane.CreateDrawingPlane(data));
}
}

View File

@ -31,10 +31,11 @@ public class ExtentionPlane
}
//сохраниние объекта в строку
public static String GetDataForSave(DrawingAirbus drawingPlane)
public static String GetDataForSave(DrawingPlane drawingPlane)
{
var plane = drawingPlane.Plane;
var str = String.format("%d%c%d%c%d", plane.GetSpeed(), _separatorForObject, plane.GetWeight(), _separatorForObject, plane.GetColor().getRGB());
var str = String.format("%d%c%d%c%d%c%d", plane.GetSpeed(), _separatorForObject, (int)plane.GetWeight(), _separatorForObject,
plane.GetColor().getRGB(), _separatorForObject, drawingPlane.GetWindows());
//если объект не расширеный
if(!(plane instanceof EntityAirbus airbus))
@ -42,6 +43,6 @@ public class ExtentionPlane
return str;
}
return str + String.format("%c%s%c%b%c%b", _separatorForObject, airbus.AddColor(), _separatorForObject, airbus.AddEngine(),airbus.AddCompartment());
return str + String.format("%c%s%c%b%c%b", _separatorForObject, airbus.AddColor(), _separatorForObject, airbus.AddEngine(), _separatorForObject, airbus.AddCompartment());
}
}

View File

@ -1,16 +1,16 @@
<?xml version="1.0" encoding="UTF-8"?>
<form xmlns="http://www.intellij.com/uidesigner/form/" version="1" bind-to-class="FormMapWithSetPlanesGeneric">
<grid id="27dc6" binding="MainPanel" layout-manager="GridLayoutManager" row-count="1" column-count="2" same-size-horizontally="false" same-size-vertically="false" hgap="-1" vgap="-1">
<grid id="27dc6" binding="MainPanel" layout-manager="GridLayoutManager" row-count="2" column-count="2" same-size-horizontally="false" same-size-vertically="false" hgap="-1" vgap="-1">
<margin top="0" left="0" bottom="0" right="0"/>
<constraints>
<xy x="20" y="20" width="994" height="654"/>
<xy x="20" y="20" width="994" height="683"/>
</constraints>
<properties/>
<border type="none"/>
<children>
<grid id="92d87" binding="PictureBoxPlane" layout-manager="BorderLayout" hgap="0" vgap="0">
<constraints>
<grid row="0" column="0" row-span="1" col-span="1" vsize-policy="3" hsize-policy="3" anchor="0" fill="3" indent="0" use-parent-layout="false">
<grid row="1" column="0" row-span="1" col-span="1" vsize-policy="3" hsize-policy="3" anchor="0" fill="3" indent="0" use-parent-layout="false">
<minimum-size width="730" height="650"/>
<preferred-size width="730" height="650"/>
<maximum-size width="730" height="650"/>
@ -23,7 +23,7 @@
<grid id="4871f" binding="GroupBoxTools" layout-manager="GridLayoutManager" row-count="17" column-count="3" same-size-horizontally="false" same-size-vertically="false" hgap="-1" vgap="-1">
<margin top="0" left="0" bottom="0" right="0"/>
<constraints>
<grid row="0" column="1" row-span="1" col-span="1" vsize-policy="3" hsize-policy="3" anchor="0" fill="3" indent="0" use-parent-layout="false">
<grid row="1" column="1" row-span="1" col-span="1" vsize-policy="3" hsize-policy="3" anchor="0" fill="3" indent="0" use-parent-layout="false">
<minimum-size width="250" height="650"/>
<preferred-size width="250" height="650"/>
<maximum-size width="250" height="650"/>
@ -247,6 +247,44 @@
</component>
</children>
</grid>
<grid id="bb85f" class="javax.swing.JMenuBar" binding="MenuBarSaveLoad" layout-manager="GridLayoutManager" row-count="1" column-count="2" same-size-horizontally="false" same-size-vertically="false" hgap="-1" vgap="-1">
<margin top="0" left="0" bottom="0" right="0"/>
<constraints>
<grid row="0" column="0" row-span="1" col-span="2" vsize-policy="3" hsize-policy="3" anchor="1" fill="1" indent="0" use-parent-layout="false"/>
</constraints>
<properties/>
<border type="none"/>
<children>
<grid id="874ff" class="javax.swing.JMenu" binding="MenuChoiceOperation" layout-manager="FlowLayout" hgap="5" vgap="5" flow-align="1">
<constraints>
<grid row="0" column="0" row-span="1" col-span="1" vsize-policy="3" hsize-policy="3" anchor="0" fill="3" indent="0" use-parent-layout="false"/>
</constraints>
<properties>
<text value="Файл"/>
</properties>
<border type="none"/>
<children>
<component id="11ed2" class="javax.swing.JMenuItem" binding="MenuItemLoadData">
<constraints/>
<properties>
<text value="Загрузить"/>
</properties>
</component>
<component id="919f4" class="javax.swing.JMenuItem" binding="MenuItemSaveData">
<constraints/>
<properties>
<text value="Сохранить"/>
</properties>
</component>
</children>
</grid>
<hspacer id="2b204">
<constraints>
<grid row="0" column="1" row-span="1" col-span="1" vsize-policy="1" hsize-policy="6" anchor="0" fill="1" indent="0" use-parent-layout="false"/>
</constraints>
</hspacer>
</children>
</grid>
</children>
</grid>
</form>

View File

@ -2,12 +2,14 @@ import javax.imageio.ImageIO;
import javax.swing.*;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.filechooser.FileSystemView;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.image.BufferedImage;
import java.io.File;
import java.util.HashMap;
public class FormMapWithSetPlanesGeneric extends JFrame{
@ -30,6 +32,10 @@ public class FormMapWithSetPlanesGeneric extends JFrame{
private JButton ButtonDeleteMap;
private JPanel GroupBoxMap;
private JButton ButtonShowDelete;
private JMenuBar MenuBarSaveLoad;
private JMenu MenuChoiceOperation;
private JMenuItem MenuItemLoadData;
private JMenuItem MenuItemSaveData;
//объект от коллекции карт
private final MapsCollection _mapsCollection;
@ -172,7 +178,7 @@ public class FormMapWithSetPlanesGeneric extends JFrame{
return;
}
DrawningObjectPlane plane = _mapsCollection.get(ListBoxMaps.getSelectedValue().toString()).GetPlaneInDelete();
DrawningObjectPlane plane = (DrawningObjectPlane)_mapsCollection.get(ListBoxMaps.getSelectedValue().toString()).GetPlaneInDelete();
if(plane == null)
{
@ -370,6 +376,53 @@ public class FormMapWithSetPlanesGeneric extends JFrame{
}
}
});
//обработка нажатия загрузки
MenuItemLoadData.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
JFileChooser jfc = new JFileChooser();
int result = jfc.showOpenDialog(null);
if (result == JFileChooser.APPROVE_OPTION)
{
if (_mapsCollection.LoadData(jfc.getSelectedFile().getPath()))
{
ReloadMaps();
JOptionPane.showMessageDialog(null,"Загрузка данных прошла успешно",
"Результат", JOptionPane.INFORMATION_MESSAGE);
}
else
{
JOptionPane.showMessageDialog(null, "Ошибка загрузки данных",
"Результат", JOptionPane.ERROR_MESSAGE);
}
}
}
});
//обработка нажатия сохранения
MenuItemSaveData.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
JFileChooser jfc = new JFileChooser();
int result = jfc.showSaveDialog(null);
if (result == JFileChooser.APPROVE_OPTION)
{
if (_mapsCollection.SaveData(jfc.getSelectedFile().getPath()))
{
JOptionPane.showMessageDialog(null,"Сохранение прошло успешно",
"Результат", JOptionPane.INFORMATION_MESSAGE);
}
else
{
JOptionPane.showMessageDialog(null, "Не сохранилось",
"Результат", JOptionPane.ERROR_MESSAGE);
}
}
}
});
}
private void createUIComponents()

View File

@ -4,4 +4,5 @@ public interface IAdditionalDrawingObject
{
void SetAddEnum(int airplaneWindow);
void DrawAirplaneWindow(Color colorAirplaneWindow, Graphics g, float _startPosX, float _startPosY);
int GetAddEnum();
}

View File

@ -90,6 +90,29 @@ public class MapWithSetPlanesGeneric <T extends IDrawningObject, U extends Abstr
return new BufferedImage(_pictureWidth, _pictureHeight, BufferedImage.TYPE_INT_RGB);
}
//получение данных в виде строки
public String GetData(char separatorType, char separatorData)
{
String data = String.format("%s%c", _map.getClass().getName(), separatorType);
for (var plane : _setPlanes)
{
data += String.format("%s%c", plane.GetInfo(), separatorData);
}
return data;
}
//Загрузка списка из массива строк
public void LoadData(String[] records)
{
for (var rec : records)
{
_setPlanes.Insert((T)DrawningObjectPlane.Create(rec));
}
}
//"взламываем" набор, чтобы все элементы оказались в начале
private void Shaking()
{

View File

@ -1,10 +1,12 @@
import javax.swing.*;
import java.io.*;
import java.util.*;
//класс для хранения коллекции карт
public class MapsCollection
{
//словарь (хранилище) с картами
public HashMap<String, MapWithSetPlanesGeneric<DrawningObjectPlane, AbstractMap>> _mapStorage;
public HashMap<String, MapWithSetPlanesGeneric<IDrawningObject, AbstractMap>> _mapStorage;
//возвращение списка названий карт
public ArrayList<String> Keys()
@ -18,6 +20,12 @@ public class MapsCollection
//высота окна отрисовки
private final int _pictureHeight;
//разделитель для записи информации по элементу словаря в файл
private final char separatorDict = '|';
//разделитель для записи коллекции данных в файл
private final char separatorData = ';';
//конструктор
public MapsCollection(int pictureWidth, int pictureHeight)
{
@ -43,8 +51,88 @@ public class MapsCollection
_mapStorage.remove(name);
}
//сохранение информации по самолётам в ангарах в файл
public Boolean SaveData(String filename)
{
File file = new File(filename);
if (file.exists())
{
file.delete();
}
try (BufferedWriter writter = new BufferedWriter(new FileWriter(filename)))
{
writter.write(String.format("MapsCollection" + System.lineSeparator()));
for(Map.Entry<String, MapWithSetPlanesGeneric<IDrawningObject, AbstractMap>> entry : _mapStorage.entrySet())
{
writter.write("" + entry.getKey() + separatorDict + entry.getValue().GetData(separatorDict, separatorData) + "\n");
}
}
catch (IOException e) {
JOptionPane.showMessageDialog(null, e.getMessage());
}
return true;
}
//загрузка нформации по по самолётам в ангарах из файла
public Boolean LoadData(String filename)
{
File file = new File(filename);
if (!file.exists())
{
return false;
}
try (BufferedReader reader = new BufferedReader(new FileReader(filename)))
{
String str = "";
//если не содержит такую запись или пустой файл
if ((str = reader.readLine()) == null || !str.contains("MapsCollection"))
{
return false;
}
_mapStorage.clear();
while ((str = reader.readLine()) != null)
{
var element = str.split(String.format("\\%c", separatorDict));
AbstractMap map = null;
switch (element[1])
{
case "SimpleMap":
map = new SimpleMap();
break;
case "DesertStormMap":
map = new DesertStormMap();
break;
case "StarWarsMap":
map = new StarWarsMap();
break;
}
_mapStorage.put(element[0], new MapWithSetPlanesGeneric<IDrawningObject, AbstractMap>(_pictureWidth, _pictureHeight,
map));
_mapStorage.get(element[0]).LoadData(element[2].split(String.valueOf(separatorData)));
}
}
catch (IOException e)
{
JOptionPane.showMessageDialog(null, e.getMessage());
}
return true;
}
//Доступ к аэродрому
public MapWithSetPlanesGeneric<DrawningObjectPlane, AbstractMap> get(String index)
public MapWithSetPlanesGeneric<IDrawningObject, AbstractMap> get(String index)
{
if(_mapStorage.containsKey(index))
{
@ -54,7 +142,7 @@ public class MapsCollection
return null;
}
public DrawningObjectPlane Get(String name, int index)
public IDrawningObject Get(String name, int index)
{
if(_mapStorage.containsKey(name))
{