Лабораторная работа №6

This commit is contained in:
insideq 2024-05-11 19:26:59 +04:00
parent d4678adf15
commit 1b3cbfe35e
10 changed files with 467 additions and 8 deletions

View File

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

View File

@ -1,9 +1,9 @@
package CollectionGenericObjects; package CollectionGenericObjects;
import java.util.ArrayList; import java.util.*;
import java.util.List;
public class ListGenericObjects<T> implements ICollectionGenericObjects<T> { public class ListGenericObjects<T> implements ICollectionGenericObjects<T> {
private List<T> _collection; private List<T> _collection;
private CollectionType collectionType = CollectionType.List;
private int _maxCount; private int _maxCount;
public int getCount() { public int getCount() {
return _collection.size(); return _collection.size();
@ -18,6 +18,10 @@ public class ListGenericObjects<T> implements ICollectionGenericObjects<T> {
_collection = new ArrayList<T>(); _collection = new ArrayList<T>();
} }
@Override @Override
public CollectionType GetCollectionType() {
return collectionType;
}
@Override
public T Get(int position) public T Get(int position)
{ {
if (position >= getCount() || position < 0) return null; if (position >= getCount() || position < 0) return null;
@ -38,4 +42,34 @@ public class ListGenericObjects<T> implements ICollectionGenericObjects<T> {
_collection.remove(position); _collection.remove(position);
return obj; return obj;
} }
@Override
public Iterable<T> GetItems() {
return new Iterable<T>() {
@Override
public Iterator<T> iterator() {
return new Iterator<T>() {
private int currentIndex = 0;
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 bulldozer : _collection) {
bulldozer = null;
}
}
} }

View File

@ -2,9 +2,11 @@ package CollectionGenericObjects;
import Drawings.DrawingBulldozer; import Drawings.DrawingBulldozer;
import java.lang.reflect.Array; import java.lang.reflect.Array;
import java.util.*;
public class MassiveGenericObjects<T> implements ICollectionGenericObjects<T>{ public class MassiveGenericObjects<T> implements ICollectionGenericObjects<T>{
private T[] _collection = null; private T[] _collection = null;
private CollectionType collectionType = CollectionType.Massive;
private int Count; private int Count;
@Override @Override
public void SetMaxCount(int size) { public void SetMaxCount(int size) {
@ -20,6 +22,10 @@ public class MassiveGenericObjects<T> implements ICollectionGenericObjects<T>{
return Count; return Count;
} }
@Override @Override
public CollectionType GetCollectionType() {
return collectionType;
}
@Override
public int Insert(T obj) { public int Insert(T obj) {
int index = 0; int index = 0;
while (index < getCount()) while (index < getCount())
@ -46,4 +52,35 @@ public class MassiveGenericObjects<T> implements ICollectionGenericObjects<T>{
if (position >= getCount() || position < 0) return null; if (position >= getCount() || position < 0) return null;
return (T) _collection[position]; 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 bulldozer : _collection) {
bulldozer = null;
}
}
} }

View File

@ -1,8 +1,12 @@
package CollectionGenericObjects; package CollectionGenericObjects;
import Drawings.DrawingBulldozer;
import Drawings.ExtensionDrawingBulldozer;
import java.io.*;
import java.util.*; import java.util.*;
public class StorageCollection<T> { public class StorageCollection<T extends DrawingBulldozer> {
private Map<String, ICollectionGenericObjects<T>> _storages; private Map<String, ICollectionGenericObjects<T>> _storages;
public StorageCollection() public StorageCollection()
{ {
@ -38,4 +42,154 @@ public class StorageCollection<T> {
return _storages.get(name).Remove(position); return _storages.get(name).Remove(position);
return null; 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 bulldozer : value.getValue().GetItems()) {
String data = ExtensionDrawingBulldozer.GetDataForSave((DrawingBulldozer) bulldozer);
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 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) {
DrawingBulldozer bulldozer = ExtensionDrawingBulldozer.CreateDrawingBulldozer(elem);
if (collection.Insert((T) bulldozer) == -1)
{
return false;
}
}
_storages.put(record[0], collection);
}
return true;
}
catch (IOException e) {
throw new RuntimeException(e);
}
}
public boolean SaveCollection(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 bulldozer : value.GetItems()) {
String data = ExtensionDrawingBulldozer.GetDataForSave((DrawingBulldozer) bulldozer);
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 LoadCollection(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) {
DrawingBulldozer bulldozer = ExtensionDrawingBulldozer.CreateDrawingBulldozer(elem);
if (collection.Insert((T) bulldozer) == -1)
{
return false;
}
}
_storages.put(record[0], collection);
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,5 +1,8 @@
package Drawings; package Drawings;
import DifferentRollers.DrawingRollersCross;
import DifferentRollers.DrawingRollersPlus;
import DifferentRollers.DrawingRollersStar;
import DifferentRollers.IDifferentRollers; import DifferentRollers.IDifferentRollers;
import Entities.EntityBulldozer; import Entities.EntityBulldozer;
@ -117,6 +120,19 @@ public class DrawingBulldozer extends JPanel {
} }
} }
public String[] GetStringRepresentationRollers() {
if (drawingRollers instanceof DrawingRollersPlus) {
return new String[]{String.valueOf(drawingRollers.getRollersCount().getNumOfRollers()), "DrawingRollersPlus"};
}
else if (drawingRollers instanceof DrawingRollersCross) {
return new String[]{String.valueOf(drawingRollers.getRollersCount().getNumOfRollers()), "DrawingRollersCross"};
}
else if (drawingRollers instanceof DrawingRollersStar) {
return new String[]{String.valueOf(drawingRollers.getRollersCount().getNumOfRollers()), "DrawingRollersStar"};
}
return null;
}
// Отрисовка Экскаватора // Отрисовка Экскаватора
public void DrawTransport(Graphics2D g){ public void DrawTransport(Graphics2D g){
if (EntityBulldozer == null || _startPosX == null || _startPosY == null){ if (EntityBulldozer == null || _startPosX == null || _startPosY == null){

View File

@ -0,0 +1,80 @@
package Drawings;
import DifferentRollers.DrawingRollersStar;
import DifferentRollers.DrawingRollersPlus;
import DifferentRollers.DrawingRollersCross;
import DifferentRollers.IDifferentRollers;
import Entities.*;
import java.util.ArrayList;
import java.util.Collections;
public class ExtensionDrawingBulldozer {
private static String _separatorForObjectS = ":";
private static String _separatorForObject = "\\:";
public static DrawingBulldozer CreateDrawingBulldozer(String info) {
String[] strs = info.split(_separatorForObject);
EntityBulldozer bulldozer;
IDifferentRollers rollers = null;
if (strs.length == 9)
{
String s = strs[8];
switch (s) {
case "DrawingRollersStar":
rollers = new DrawingRollersStar();
break;
case "DrawingRollersPlus":
rollers = new DrawingRollersPlus();
break;
case "DrawingRollersCross":
rollers = new DrawingRollersCross();
break;
}
if (rollers != null) rollers.setRollersCount(Integer.parseInt(strs[7]));
}
else if (strs.length == 6) {
String s = strs[5];
switch (s) {
case "DrawingRollersStar":
rollers = new DrawingRollersStar();
break;
case "DrawingRollersPlus":
rollers = new DrawingRollersPlus();
break;
case "DrawingRollersCross":
rollers = new DrawingRollersCross();
break;
}
if (rollers != null) rollers.setRollersCount(Integer.parseInt(strs[4]));
}
bulldozer = EntityExcavator.CreateEntityExcavator(strs);
if (bulldozer != null)
{
return new DrawingExcavator((EntityExcavator)bulldozer, rollers);
}
bulldozer = EntityBulldozer.CreateEntityBulldozer(strs);
if (bulldozer != null)
{
return new DrawingBulldozer(bulldozer, rollers);
}
return null;
}
public static String GetDataForSave(DrawingBulldozer drawingBulldozer)
{
if (drawingBulldozer == null) return "";
String[] arrayEntity = drawingBulldozer.EntityBulldozer.GetStringRepresentation();
String[] arrayRollers = drawingBulldozer.GetStringRepresentationRollers();
if (arrayEntity == null)
{
return "";
}
ArrayList<String> list = new ArrayList<>();
Collections.addAll(list, arrayEntity);
if (arrayRollers == null) {
Collections.addAll(list, "0", " ");
}
else Collections.addAll(list, arrayRollers);
return String.join(_separatorForObjectS, list);
}
}

View File

@ -1,12 +1,14 @@
package Entities; package Entities;
import java.awt.*; import java.awt.*;
import java.util.Objects;
public class EntityBulldozer { public class EntityBulldozer {
private Integer Speed; private Integer Speed;
public Integer getSpeed() {return Speed;}
public void setSpeed(int speed) {Speed = speed;} public void setSpeed(int speed) {Speed = speed;}
private Double Weight; private Double Weight;
public Double getWeight() {return Weight;}
public void setWeight(double weight) {Weight = weight;} public void setWeight(double weight) {Weight = weight;}
private Color BodyColor; private Color BodyColor;
@ -22,4 +24,22 @@ public class EntityBulldozer {
BodyColor = bodyColor; BodyColor = bodyColor;
Step = Speed * 100 / Weight; Step = Speed * 100 / Weight;
} }
public String[] GetStringRepresentation()
{
return new String[]{"EntityBulldozer", Speed.toString(), Weight.toString(), colorToHexString(BodyColor)};
}
public static EntityBulldozer CreateEntityBulldozer(String[] strs)
{
if (strs.length != 6 || !Objects.equals(strs[0], "EntityBulldozer"))
{
return null;
}
return new EntityBulldozer(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,7 @@
package Entities; package Entities;
import java.awt.*; import java.awt.*;
import java.util.Objects;
public class EntityExcavator extends EntityBulldozer{ public class EntityExcavator extends EntityBulldozer{
private Color AdditionalColor; private Color AdditionalColor;
@ -25,4 +26,20 @@ public class EntityExcavator extends EntityBulldozer{
Prop = prop; Prop = prop;
Ladle = ladle; Ladle = ladle;
} }
@Override
public String[] GetStringRepresentation()
{
return new String[]{"EntityExcavator", getSpeed().toString(), getWeight().toString(),
colorToHexString(getBodyColor()), colorToHexString(getAdditionalColor()),
String.valueOf(Prop), String.valueOf(Ladle)};
}
public static EntityExcavator CreateEntityExcavator(String[] strs)
{
if (strs.length != 9 || !Objects.equals(strs[0], "EntityExcavator"))
{
return null;
}
return new EntityExcavator(Integer.parseInt(strs[1]), Double.parseDouble(strs[2]), hexStringToColor(strs[3]),
hexStringToColor(strs[4]), Boolean.parseBoolean(strs[5]), Boolean.parseBoolean(strs[6]));
}
} }

View File

@ -34,6 +34,13 @@ public class FormBulldozerCollection extends JFrame{
private JButton RefreshButton = new JButton("Обновить"); private JButton RefreshButton = new JButton("Обновить");
private JComboBox ComboBoxCollections = new JComboBox(new String[]{"", "Хранилище"}); private JComboBox ComboBoxCollections = new JComboBox(new String[]{"", "Хранилище"});
private JFormattedTextField MaskedTextField; private JFormattedTextField MaskedTextField;
private JMenuBar menuBar = new JMenuBar();
private JMenu fileMenu = new JMenu("Файл");
private JMenuItem saveItem = new JMenuItem("Сохранить");
private JMenuItem loadItem = new JMenuItem("Загрузить");
private JMenuItem saveCollection = new JMenuItem("Сохранить коллекцию");
private JMenuItem loadCollection = new JMenuItem("Загрузить коллекцию");
public FormBulldozerCollection(String title, Dimension dimension) { public FormBulldozerCollection(String title, Dimension dimension) {
this.title = title; this.title = title;
this.dimension = dimension; this.dimension = dimension;
@ -129,7 +136,6 @@ public class FormBulldozerCollection extends JFrame{
} }
FormAdditionalCollection form = new FormAdditionalCollection(); FormAdditionalCollection form = new FormAdditionalCollection();
form.setCompany(_company); form.setCompany(_company);
form.setLocationRelativeTo(null);
} }
}); });
@ -220,7 +226,37 @@ public class FormBulldozerCollection extends JFrame{
} }
FormExcavator form = new FormExcavator("Экскаватор", new Dimension(900,565)); FormExcavator form = new FormExcavator("Экскаватор", new Dimension(900,565));
form.Init(bulldozer); form.Init(bulldozer);
form.setLocationRelativeTo(null); }
});
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("Сохранение коллекции");
SaveCollection();
}
});
loadCollection.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
System.out.println("Загрузка коллекции");
LoadCollection();
} }
}); });
@ -229,6 +265,13 @@ public class FormBulldozerCollection extends JFrame{
radioButtonsGroup.add(radioButtonMassive); radioButtonsGroup.add(radioButtonMassive);
radioButtonsGroup.add(radioButtonList); radioButtonsGroup.add(radioButtonList);
fileMenu.add(saveItem);
fileMenu.add(loadItem);
fileMenu.add(saveCollection);
fileMenu.add(loadCollection);
menuBar.add(fileMenu);
setJMenuBar(menuBar);
_canvasExcavator.setBounds(0, 0, getWidth()-200, getHeight()); _canvasExcavator.setBounds(0, 0, getWidth()-200, getHeight());
labelCollectionName.setBounds(getWidth()-190, 30, 150, 20); labelCollectionName.setBounds(getWidth()-190, 30, 150, 20);
textBoxCollection.setBounds(getWidth()-190, 52, 150, 25); textBoxCollection.setBounds(getWidth()-190, 52, 150, 25);
@ -245,7 +288,7 @@ public class FormBulldozerCollection extends JFrame{
GoToCheckButton.setBounds(getWidth()-190, 440, 150, 30); GoToCheckButton.setBounds(getWidth()-190, 440, 150, 30);
RandomButton.setBounds(getWidth()-190, 480, 150, 30); RandomButton.setBounds(getWidth()-190, 480, 150, 30);
RemoveObjectsButton.setBounds(getWidth()-190, 520, 150, 30); RemoveObjectsButton.setBounds(getWidth()-190, 520, 150, 30);
RefreshButton.setBounds(getWidth()-190, getHeight()-90, 150, 30); RefreshButton.setBounds(getWidth()-190, getHeight()-100, 150, 30);
setSize(dimension.width,dimension.height); setSize(dimension.width,dimension.height);
setLayout(null); setLayout(null);
@ -280,4 +323,59 @@ public class FormBulldozerCollection extends JFrame{
} }
listBoxCollection.setModel(list); listBoxCollection.setModel(list);
} }
private String SaveWindow() {
FileDialog fileDialog = new FileDialog(this, "Сохранить файл", 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.SaveCollection(filename, listBoxCollection.getSelectedValue().toString())) {
JOptionPane.showMessageDialog(null, "Коллекция сохранена");
}
else JOptionPane.showMessageDialog(null, "Ошибка сохранения");
}
private String LoadWindow() {
FileDialog fileDialog = new FileDialog(this, "Загрузить файл", 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, "Загрузка прошла успешно");
RefreshListBoxItems();
}
else JOptionPane.showMessageDialog(null, "Не загрузилось");
}
private void LoadCollection() {
String filename = LoadWindow();
if (_storageCollection.LoadCollection(filename)) {
JOptionPane.showMessageDialog(null, "Коллекция загружена");
RefreshListBoxItems();
}
else JOptionPane.showMessageDialog(null, "Ошибка загрузки");
}
} }

View File

@ -2,7 +2,7 @@ import java.awt.*;
public class Program { public class Program {
public static void main(String[] args) { public static void main(String[] args) {
FormBulldozerCollection form = new FormBulldozerCollection("Коллекция экскаваторов", new Dimension(1100, 650)); FormBulldozerCollection form = new FormBulldozerCollection("Коллекция экскаваторов", new Dimension(1100, 660));
form.Init(); form.Init();
form.setLocationRelativeTo(null); form.setLocationRelativeTo(null);
} }