PIbd-11 Valiulov I.A. LabWork06 Hard #6

Closed
Ilyas wants to merge 1 commits from LabWork06 into LabWork05
11 changed files with 462 additions and 11 deletions

View File

@ -6,10 +6,7 @@ import DrawingShip.DrawingWarmlyShip;
import Entities.EntityShip;
import Entities.EntityWarmlyShip;
import java.awt.*;
import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
public class AdditionalCollections <T extends EntityShip, U extends IDifferentDecks>{

View File

@ -7,5 +7,8 @@ public interface ICollectionGenericObjects<T>
int Insert(T obj);
T Remove(int position);
T Get(int position);
CollectionType GetCollectionType();
Iterable<T> GetItems();
void ClearCollection();
}

View File

@ -1,9 +1,10 @@
package CollectionGenericObjects;
import java.util.ArrayList;
import java.util.List;
import java.util.*;
public class ListGenericObjects<T> implements ICollectionGenericObjects<T> {
private List<T> _collection;
private CollectionType collectionType = CollectionType.List;
private int _maxCount;
public int getCount() {
return _collection.size();
@ -18,6 +19,10 @@ public class ListGenericObjects<T> implements ICollectionGenericObjects<T> {
_collection = new ArrayList<T>();
}
@Override
public CollectionType GetCollectionType() {
return collectionType;
}
@Override
public T Get(int position)
{
if (position >= getCount() || position < 0) return null;
@ -38,4 +43,35 @@ public class ListGenericObjects<T> implements ICollectionGenericObjects<T> {
_collection.remove(position);
return obj;
}
@Override
public Iterable<T> GetItems() {
return new Iterable<T>() {
@Override
public Iterator<T> iterator() {
return new Iterator<T>() {
private int currentIndex = 0;
//нужен ли count
private int count = 0;
@Override
public boolean hasNext() {
return currentIndex < getCount();
}
@Override
public T next() {
if (hasNext()) {
count++;
return _collection.get(currentIndex++);
}
throw new NoSuchElementException();
}
};
}
};
}
@Override
public void ClearCollection() {
for (T ship : _collection) {
Review

У коллекций есть метод очистки - Clear

У коллекций есть метод очистки - Clear
ship = null;
}
}
}

View File

@ -3,10 +3,12 @@ package CollectionGenericObjects;
import DrawingShip.DrawingShip;
import java.lang.reflect.Array;
import java.util.*;
public class MassiveGenericObjects<T> implements ICollectionGenericObjects<T>{
private T[] _collection = null;
private int Count;
private CollectionType collectionType = CollectionType.Massive;
@Override
public void SetMaxCount(int size) {
if (size > 0) {
@ -21,6 +23,10 @@ public class MassiveGenericObjects<T> implements ICollectionGenericObjects<T>{
return Count;
}
@Override
public CollectionType GetCollectionType() {
return collectionType;
}
@Override
public int Insert(T obj) {
int index = 0;
while (index < getCount())
@ -47,4 +53,35 @@ public class MassiveGenericObjects<T> implements ICollectionGenericObjects<T>{
if (position >= getCount() || position < 0) return null;
return (T) _collection[position];
}
@Override
public Iterable<T> GetItems() {
return new Iterable<T>() {
@Override
public Iterator<T> iterator() {
return new Iterator<T>() {
private int currentIndex = 0;
//нужен ли count
private int count = 0;
@Override
public boolean hasNext() {
return currentIndex < getCount();
}
@Override
public T next() {
if (hasNext()) {
count++;
return _collection[currentIndex++];
}
throw new NoSuchElementException();
}
};
}
};
}
@Override
public void ClearCollection() {
for (T ship : _collection) {
ship = null;
}
}
}

View File

@ -1,10 +1,12 @@
package CollectionGenericObjects;
import DrawingShip.DrawingShip;
import DrawingShip.ExtentionDrawningShip;
import java.io.*;
import java.util.*;
public class StorageCollection<T> {
public class StorageCollection<T extends DrawingShip> {
private Map<String, ICollectionGenericObjects<T>> _storages;
public StorageCollection()
{
@ -40,4 +42,153 @@ public class StorageCollection<T> {
return _storages.get(name).Remove(position);
return null;
}
private String _collectionKey = "CollectionsStorage";
private String _collectionName = "StorageCollection";
private String _separatorForKeyValueS = "|";
private String _separatorForKeyValue = "\\|";
private String _separatorItemsS = ";";
private String _separatorItems = "\\;";
public boolean SaveData(String filename) {
if (_storages.isEmpty()) return false;
File file = new File(filename);
if (file.exists()) file.delete();
try {
file.createNewFile();
FileWriter writer = new FileWriter(file);
writer.write(_collectionKey);
writer.write("\n");
for (Map.Entry<String, ICollectionGenericObjects<T>> value : _storages.entrySet()) {
StringBuilder sb = new StringBuilder();
sb.append(value.getKey());
sb.append(_separatorForKeyValueS);
sb.append(value.getValue().GetCollectionType());
sb.append(_separatorForKeyValueS);
sb.append(value.getValue().getCount());
sb.append(_separatorForKeyValueS);
for (T ship : value.getValue().GetItems()) {
String data = ExtentionDrawningShip.GetDataForSave((DrawingShip) ship);
if (data.isEmpty()) continue;
sb.append(data);
sb.append(_separatorItemsS);
}
sb.append("\n");
writer.write(String.valueOf(sb));
}
writer.close();
} catch (IOException e) {
throw new RuntimeException(e);
}
return true;
}
public boolean SaveOneCollection(String filename, String name) {
if (_storages.isEmpty()) return false;
File file = new File(filename);
if (file.exists()) file.delete();
try {
file.createNewFile();
FileWriter writer = new FileWriter(file);
writer.write(_collectionName);
writer.write("\n");
ICollectionGenericObjects<T> value = _storages.get(name);
StringBuilder sb = new StringBuilder();
sb.append(name);
sb.append(_separatorForKeyValueS);
sb.append(value.GetCollectionType());
sb.append(_separatorForKeyValueS);
sb.append(value.getCount());
sb.append(_separatorForKeyValueS);
for (T ship : value.GetItems()) {
String data = ExtentionDrawningShip.GetDataForSave((DrawingShip) ship);
if (data.isEmpty()) continue;
sb.append(data);
sb.append(_separatorItemsS);
}
writer.append(sb);
writer.close();
} catch (IOException e) {
throw new RuntimeException(e);
}
return true;
}
public boolean LoadData(String filename) {
File file = new File(filename);
if (!file.exists()) return false;
try (BufferedReader fs = new BufferedReader(new FileReader(filename))) {
String s = fs.readLine();
if (s == null || s.isEmpty() || !s.startsWith(_collectionKey))
return false;
_storages.clear();
s = "";
while ((s = fs.readLine()) != null) {
String[] record = s.split(_separatorForKeyValue);
if (record.length != 4) {
continue;
}
ICollectionGenericObjects<T> collection = CreateCollection(record[1]);
if (collection == null)
{
return false;
}
collection.SetMaxCount(Integer.parseInt(record[2]));
String[] set = record[3].split(_separatorItems);
for (String elem : set) {
DrawingShip ship = ExtentionDrawningShip.CreateDrawingShip(elem);
if (collection.Insert((T) ship) == -1)
{
return false;
}
}
_storages.put(record[0], collection);
}
return true;
}
catch (IOException e) {
throw new RuntimeException(e);
}
}
public boolean LoadOneCollection(String filename) {
File file = new File(filename);
if (!file.exists()) return false;
try (BufferedReader fs = new BufferedReader(new FileReader(filename))) {
String s = fs.readLine();
if (s == null || s.isEmpty() || !s.startsWith(_collectionName))
return false;
if (_storages.containsKey(s)) {
_storages.get(s).ClearCollection();
}
s = fs.readLine();
String[] record = s.split(_separatorForKeyValue);
if (record.length != 4) {
return false;
}
ICollectionGenericObjects<T> collection = CreateCollection(record[1]);
if (collection == null)
{
return false;
}
collection.SetMaxCount(Integer.parseInt(record[2]));
String[] set = record[3].split(_separatorItems);
for (String elem : set) {
DrawingShip ship = ExtentionDrawningShip.CreateDrawingShip(elem);
if (collection.Insert((T) ship) == -1)
{
return false;
}
}
_storages.put(record[0], collection);
Review

Смысл делать проверку и очищать коллекцию, если тут же ее удаляешь?

Смысл делать проверку и очищать коллекцию, если тут же ее удаляешь?
return true;
}
catch (IOException e) {
throw new RuntimeException(e);
}
}
public ICollectionGenericObjects<T> CreateCollection(String s) {
switch (s) {
case "Massive":
return new MassiveGenericObjects<T>();
case "List":
return new ListGenericObjects<T>();
}
return null;
}
}

View File

@ -1,8 +1,11 @@
package DrawingShip;
import DiffetentsDrawingDecks.DrawingDecksType2;
import DiffetentsDrawingDecks.DrawingDecksType3;
import DiffetentsDrawingDecks.IDifferentDecks;
import Entities.EntityShip;
import DiffetentsDrawingDecks.DrawingDecksType1;
import javax.swing.*;
import java.awt.*;
@ -131,4 +134,16 @@ public class DrawingShip extends JPanel {
g.fillPolygon(poly);
drawingShipHeight = y + 50 - _StartPosY;
}
public String[] GetStringRepresentationDecks() {
if (drawingDecks instanceof DrawingDecksType1) {
return new String[]{String.valueOf(drawingDecks.getNumberOfDecks().getNumdecks()), "DrawingDecksType1"};
}
else if (drawingDecks instanceof DrawingDecksType2) {
return new String[]{String.valueOf(drawingDecks.getNumberOfDecks().getNumdecks()), "DrawingDecksType2"};
}
else if (drawingDecks instanceof DrawingDecksType3) {
return new String[]{String.valueOf(drawingDecks.getNumberOfDecks().getNumdecks()), "DrawingDecksType3"};
}
return null;
}
}

View File

@ -0,0 +1,74 @@
package DrawingShip;
import DiffetentsDrawingDecks.DrawingDecksType1;
import DiffetentsDrawingDecks.DrawingDecksType2;
import DiffetentsDrawingDecks.DrawingDecksType3;
import DiffetentsDrawingDecks.IDifferentDecks;
import Entities.EntityShip;
import Entities.EntityWarmlyShip;
import java.util.ArrayList;
import java.util.Collections;
public class ExtentionDrawningShip {
private static String _separatorForObjectS = ":";
private static String _separatorForObject = "\\:";
public static DrawingShip CreateDrawingShip(String info) {
String[] strs = info.split(_separatorForObject);
EntityShip ship;
IDifferentDecks decks = null;
if (strs.length == 8)
{
String s = strs[8];
switch (s) {
case "DrawingDecksType1":
decks = new DrawingDecksType1();
case "DrawingDecksType2":
decks = new DrawingDecksType2();
case "DrawingDecksType3":
decks = new DrawingDecksType3();
}
if (decks != null) decks.setNumberOfDecks(Integer.parseInt(strs[7]));
}
else if (strs.length == 6) {
String s = strs[5];
switch (s) {
case "DrawingDecksType1":
decks = new DrawingDecksType1();
case "DrawingDecksType2":
decks = new DrawingDecksType2();
case "DrawingDecksType3":
decks = new DrawingDecksType3();
}
if (decks != null) decks.setNumberOfDecks(Integer.parseInt(strs[4]));
}
ship = EntityWarmlyShip.CreateEntityWarmlyShip(strs);
if (ship != null)
{
return new DrawingWarmlyShip((EntityWarmlyShip)ship, decks);
}
ship = EntityShip.CreateEntityShip(strs);
if (ship != null)
{
return new DrawingShip(ship, decks);
}
return null;
}
public static String GetDataForSave(DrawingShip drawningShip)
{
if (drawningShip == null) return "";
String[] array1 = drawningShip.EntityShip.GetStringRepresentation();
String[] array2 = drawningShip.GetStringRepresentationDecks();
if (array1 == null)
{
return "";
}
ArrayList<String> list = new ArrayList<>();
Collections.addAll(list, array1);
if (array2 == null) {
Collections.addAll(list, "0", " ");
}
else Collections.addAll(list, array2);
return String.join(_separatorForObjectS, list);
}
}

View File

@ -1,12 +1,15 @@
package Entities;
import java.awt.*;
import java.util.Objects;
public class EntityShip {
private int Speed;
private Integer Speed;
public void setSpeed(int speed) {Speed = speed;}
private double Weight;
public Integer getSpeed() {return Speed;}
private Double Weight;
public void setWeight(double weight) {Weight = weight;}
public Double getWeight() {return Weight;}
private Color BodyColor;
public Color getBodyColor() {return BodyColor;}
public void setBodyColor(Color color) {BodyColor = color;}
@ -18,4 +21,22 @@ public class EntityShip {
BodyColor = bodycolor;
Step = Speed * 100 / Weight;
}
public String[] GetStringRepresentation()
{
return new String[]{"EntityShip", Speed.toString(), Weight.toString(), colorToHexString(BodyColor)};
}
public static EntityShip CreateEntityShip(String[] strs)
{
if (strs.length != 6 || !Objects.equals(strs[0], "EntityShip"))
{
return null;
}
return new EntityShip(Integer.parseInt(strs[1]), Double.parseDouble(strs[2]), hexStringToColor(strs[3]));
}
public static String colorToHexString(Color color) {
return String.format("#%02x%02x%02x", color.getRed(), color.getGreen(), color.getBlue());
}
public static Color hexStringToColor(String hexString) {
return Color.decode(hexString);
}
}

View File

@ -1,6 +1,8 @@
package Entities;
import java.awt.*;
import java.util.Objects;
public class EntityWarmlyShip extends EntityShip{
public Color AdditionalColor;
public Color getAdditionalColor() {return AdditionalColor;}
@ -17,4 +19,20 @@ public class EntityWarmlyShip extends EntityShip{
ShipPipes = sheeppipes;
FuelTank = fueltank;
}
@Override
public String[] GetStringRepresentation()
{
return new String[]{"EntityWarmlyShip", getSpeed().toString(), getWeight().toString(),
colorToHexString(getBodyColor()), colorToHexString(getAdditionalColor()),
String.valueOf(ShipPipes), String.valueOf(FuelTank)};
}
public static EntityWarmlyShip CreateEntityWarmlyShip(String[] strs)
{
if (strs.length != 9 || !Objects.equals(strs[0], "EntityWarmlyShip"))
{
return null;
}
return new EntityWarmlyShip(Integer.parseInt(strs[1]), Double.parseDouble(strs[2]), hexStringToColor(strs[3]),
hexStringToColor(strs[4]), Boolean.parseBoolean(strs[5]), Boolean.parseBoolean(strs[6]));
}
}

View File

@ -36,6 +36,12 @@ public class FormShipCollection extends JFrame{
private JButton RefreshButton = new JButton("Refresh");
private JComboBox ComboBoxCollections = new JComboBox(new String[]{"", "Хранилище"});
private JFormattedTextField MaskedTextField;
private JMenuBar menuBar = new JMenuBar();
private JMenu fileMenu = new JMenu("File");
private JMenuItem loadItem = new JMenuItem("Load");
private JMenuItem saveItem = new JMenuItem("Save");
private JMenuItem loadCollection = new JMenuItem("Load coll");
private JMenuItem saveCollection = new JMenuItem("Save coll");
public FormShipCollection(String title, Dimension dimension) {
this.title = title;
this.dimension = dimension;
@ -224,11 +230,50 @@ public class FormShipCollection extends JFrame{
}
});
saveItem.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
SaveFile();
}
});
loadItem.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
LoadFile();
}
});
saveCollection.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
System.out.println("Save coll");
SaveCollection();
}
});
loadCollection.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
System.out.println("Load coll");
LoadCollection();
}
});
JLabel labelCollectionName = new JLabel("Название коллекции");
ButtonGroup radiobuttonsGroup = new ButtonGroup();
radiobuttonsGroup.add(radioButtonMassive);
radiobuttonsGroup.add(radioButtonList);
fileMenu.add(loadItem);
fileMenu.add(saveItem);
fileMenu.add(loadCollection);
fileMenu.add(saveCollection);
fileMenu.addSeparator();
menuBar.add(fileMenu);
setJMenuBar(menuBar);
_canvasWarmlyShip.setBounds(0, 0, getWidth()-200, getHeight());
labelCollectionName.setBounds(getWidth()-190, 10, 150, 20);
textBoxCollection.setBounds(getWidth()-190, 32, 150, 25);
@ -245,7 +290,7 @@ public class FormShipCollection extends JFrame{
GoToCheckButton.setBounds(getWidth()-190, 435, 150, 30);
RandomButton.setBounds(getWidth()-190, 470, 150, 30);
RemoveObjectsButton.setBounds(getWidth()-190, 505, 150, 30);
RefreshButton.setBounds(getWidth()-190, getHeight()-90, 150, 30);
RefreshButton.setBounds(getWidth()-190, getHeight()-100, 150, 30);
setSize(dimension.width,dimension.height);
setLayout(null);
@ -268,6 +313,60 @@ public class FormShipCollection extends JFrame{
add(RefreshButton);
setVisible(true);
}
private String SaveWindow() {
FileDialog fileDialog = new FileDialog(this, "Save File", FileDialog.SAVE);
fileDialog.setVisible(true);
String directory = fileDialog.getDirectory();
String file = fileDialog.getFile();
if (directory == null || file == null) return null;
return directory + file;
}
private void SaveFile() {
String filename = SaveWindow();
if (_storageCollection.SaveData(filename)) {
JOptionPane.showMessageDialog(null, "Сохранено");
}
else JOptionPane.showMessageDialog(null, "Ошибка сохранения");
}
private void SaveCollection() {
String filename = SaveWindow();
if (filename == null) {
JOptionPane.showMessageDialog(null, "Файл не выбран");
return;
}
if (listBoxCollection.getSelectedIndex() < 0 || listBoxCollection.getSelectedValue() == null) {
JOptionPane.showMessageDialog(null, "Коллекция не выбрана");
}
if (_storageCollection.SaveOneCollection(filename, listBoxCollection.getSelectedValue().toString())) {
JOptionPane.showMessageDialog(null, "Коллекция сохранена");
}
else JOptionPane.showMessageDialog(null, "Ошибка сохранения");
}
private String LoadWindow() {
FileDialog fileDialog = new FileDialog(this, "Save File", FileDialog.LOAD);
fileDialog.setVisible(true);
String directory = fileDialog.getDirectory();
String file = fileDialog.getFile();
if (directory == null || file == null) return null;
return directory + file;
}
private void LoadFile() {
String filename = LoadWindow();
if (_storageCollection.LoadData(filename)) {
JOptionPane.showMessageDialog(null, "Загрузка прошла успешно");
RerfreshListBoxItems();
}
else JOptionPane.showMessageDialog(null, "Не загрузилось");
}
private void LoadCollection() {
String filename = LoadWindow();
if (_storageCollection.LoadOneCollection(filename)) {
JOptionPane.showMessageDialog(null, "Коллекция загружена");
RerfreshListBoxItems();
}
else JOptionPane.showMessageDialog(null, "Не загрузилось");
}
private void RerfreshListBoxItems()
{
DefaultListModel<String> list = new DefaultListModel<String>();

View File

@ -36,7 +36,7 @@ public class FormShipConfig extends JFrame {
private JLabel labelBeamsDeck = new JLabel("Beams Deck", SwingConstants.CENTER);
private JLabel labelWindowDeck = new JLabel("Window Deck", SwingConstants.CENTER);
private JLabel labelAdditionalColor = new JLabel("Additi Color", SwingConstants.CENTER);
private JLabel labelNumberOfDecks = new JLabel("Numb od decks");
private JLabel labelNumberOfDecks = new JLabel("Numb Of decks");
private JSpinner spinnerSpeed = new JSpinner();
private JSpinner spinnerWeight = new JSpinner();
private JSpinner spinnerNumberOfDecks = new JSpinner();