From 73d340a2d5942838c6d898802936435d98a7d7b7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=94=D0=B0=D0=BD=D0=B8=D0=B8=D0=BB=20=D0=9F=D1=83=D1=82?= =?UTF-8?q?=D0=B8=D0=BD=D1=86=D0=B5=D0=B2?= Date: Tue, 19 Dec 2023 16:27:34 +0400 Subject: [PATCH] =?UTF-8?q?=D0=93=D0=BE=D1=82=D0=BE=D0=B2=D0=B0=D1=8F=206?= =?UTF-8?q?=20=D1=83=D1=81=D0=BB=D0=BE=D0=B6=D0=BD=D0=B5=D0=BD=D0=BD=D0=B0?= =?UTF-8?q?=D1=8F=20=D0=BB=D0=B0=D0=B1=D0=BE=D1=80=D0=B0=D1=82=D0=BE=D1=80?= =?UTF-8?q?=D0=BD=D0=B0=D1=8F?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../ExtentionDrawningTruck.java | 80 +++++++++ src/RoadTrain/FormTruckCollection.java | 103 ++++++++++++ src/RoadTrain/Generics/SetGeneric.java | 3 +- .../Generics/TrucksGenericCollection.java | 2 + .../Generics/TrucksGenericStorage.java | 153 +++++++++++++++++- 5 files changed, 338 insertions(+), 3 deletions(-) create mode 100644 src/RoadTrain/DrawingObjects/ExtentionDrawningTruck.java diff --git a/src/RoadTrain/DrawingObjects/ExtentionDrawningTruck.java b/src/RoadTrain/DrawingObjects/ExtentionDrawningTruck.java new file mode 100644 index 0000000..91aba58 --- /dev/null +++ b/src/RoadTrain/DrawingObjects/ExtentionDrawningTruck.java @@ -0,0 +1,80 @@ +package RoadTrain.DrawingObjects; + +import RoadTrain.Entities.EntityRoadTrain; +import RoadTrain.Entities.EntityTruck; +import RoadTrain.Extra.IDrawingWheels; + +import java.awt.*; + +public class ExtentionDrawningTruck{ + public static DrawingTruck CreateDrawingTruck(String info, String separatorForObject, int width, int height) + { + String[] strs = info.split(separatorForObject); + if (strs.length == 5) + { + String[] colorValues = strs[2].split(","); + + DrawingTruck drawingTruck = new DrawingTruck(Integer.parseInt(strs[0]), (double)Integer.parseInt(strs[1]), + new Color( + Integer.parseInt(colorValues[0].replaceAll("\\D", "")), + Integer.parseInt(colorValues[1].replaceAll("\\D", "")), + Integer.parseInt(colorValues[2].replaceAll("\\D", "")) + ), + width, height, + Integer.parseInt(strs[3])); + try{ + drawingTruck.drawingWheels = (IDrawingWheels) Class.forName(strs[4]).getDeclaredConstructor().newInstance(); + drawingTruck.drawingWheels.SetWheelNumber(drawingTruck.entityTruck.Numwheel); + } + catch(Exception e){ + return null; + } + return drawingTruck; + } + if (strs.length == 8) + { + String[] colorValues = strs[2].split(","); + String[] colorValues2 = strs[5].split(","); + DrawingRoadTrain drawingRoadTrain = new DrawingRoadTrain( + Integer.parseInt(strs[0]), + (double)Integer.parseInt(strs[1]), + new Color( + Integer.parseInt(colorValues[0].replaceAll("\\D", "")), + Integer.parseInt(colorValues[1].replaceAll("\\D", "")), + Integer.parseInt(colorValues[2].replaceAll("\\D", "")) + ), + new Color( + Integer.parseInt(colorValues2[0].replaceAll("\\D", "")), + Integer.parseInt(colorValues2[1].replaceAll("\\D", "")), + Integer.parseInt(colorValues2[2].replaceAll("\\D", "")) + ), + strs[6].equals("true"), + strs[7].equals("true"), + width, height, + Integer.parseInt(strs[3])); + try{ + drawingRoadTrain.drawingWheels = (IDrawingWheels) Class.forName(strs[4]).getDeclaredConstructor().newInstance(); + drawingRoadTrain.drawingWheels.SetWheelNumber(drawingRoadTrain.entityTruck.Numwheel); + } + catch(Exception e){ + return null; + } + return drawingRoadTrain; + } + return null; + } + public static String GetDataForSave(DrawingTruck drawingTruck, String separatorForObject) + { + EntityTruck truck = drawingTruck.entityTruck; + if (truck == null) + { + return null; + } + String str = "" + truck.GetSpeed() + separatorForObject + (int)truck.GetWeight() + separatorForObject + truck.GetBodyColor() + separatorForObject + truck.Numwheel + separatorForObject + drawingTruck.drawingWheels.getClass().getName(); + if (!(truck instanceof EntityRoadTrain)) + { + return str; + } + return str + separatorForObject + ((EntityRoadTrain)truck).GetAdditionalColor().toString()+separatorForObject+((EntityRoadTrain)truck).GetWaterContainer()+separatorForObject+((EntityRoadTrain)truck).GetSweepingBrush(); + } +} diff --git a/src/RoadTrain/FormTruckCollection.java b/src/RoadTrain/FormTruckCollection.java index c16dc80..8436b86 100644 --- a/src/RoadTrain/FormTruckCollection.java +++ b/src/RoadTrain/FormTruckCollection.java @@ -7,9 +7,11 @@ import RoadTrain.DrawingObjects.*; import javax.swing.*; import javax.swing.event.ListSelectionEvent; import javax.swing.event.ListSelectionListener; +import javax.swing.filechooser.FileNameExtensionFilter; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; +import java.io.File; import java.util.*; public class FormTruckCollection { @@ -211,6 +213,105 @@ public class FormTruckCollection { } } ); + JMenuBar menuBar = new JMenuBar(); + + JMenu fileMenu = new JMenu("Файл"); + + JMenuItem openItem = new JMenuItem("Загрузить"); + openItem.addActionListener( + new ActionListener() { + public void actionPerformed(ActionEvent e){ + JFileChooser fileChooser = new JFileChooser(); + + fileChooser.setDialogTitle("Выберите файл для загрузки данных"); + + fileChooser.setFileFilter(new FileNameExtensionFilter("Текстовые файлы (*.txt)", "txt")); + + fileChooser.setDialogTitle("Выберите файл для загрузки данных"); + if (fileChooser.showOpenDialog(null) == JFileChooser.APPROVE_OPTION) { + File selectedFile = fileChooser.getSelectedFile(); + if (_storage.LoadData(selectedFile.getAbsolutePath())) { + JOptionPane.showMessageDialog(null, "Загрузка прошла успешно", "Результат", JOptionPane.INFORMATION_MESSAGE); + } else { + JOptionPane.showMessageDialog(null, "Не загрузилось", "Результат", JOptionPane.ERROR_MESSAGE); + } + } + ReloadObjects(); + } + } + ); + JMenuItem saveItem = new JMenuItem("Сохранить"); + saveItem.addActionListener( + new ActionListener() { + public void actionPerformed(ActionEvent e){ + JFileChooser fileChooser = new JFileChooser(); + fileChooser.setDialogTitle("Выберите файл для сохранения данных"); + + fileChooser.setFileFilter(new FileNameExtensionFilter("Текстовые файлы (*.txt)", "txt")); + + if (fileChooser.showSaveDialog(null) == JFileChooser.APPROVE_OPTION) { + File selectedFile = fileChooser.getSelectedFile(); + if (_storage.SaveData(selectedFile.getAbsolutePath())) + JOptionPane.showMessageDialog(null, "Сохранение прошло успешно", "Результат", JOptionPane.INFORMATION_MESSAGE); + else + JOptionPane.showMessageDialog(null, "Не сохранилось", "Результат", JOptionPane.ERROR_MESSAGE); + } + } + } + ); + JMenuItem openItemSingle = new JMenuItem("Загрузить одиночный"); + openItemSingle.addActionListener( + new ActionListener() { + public void actionPerformed(ActionEvent e){ + JFileChooser fileChooser = new JFileChooser(); + + fileChooser.setDialogTitle("Выберите файл для загрузки данных"); + + fileChooser.setFileFilter(new FileNameExtensionFilter("Текстовые файлы (*.txt)", "txt")); + + fileChooser.setDialogTitle("Выберите файл для загрузки данных"); + if (fileChooser.showOpenDialog(null) == JFileChooser.APPROVE_OPTION) { + File selectedFile = fileChooser.getSelectedFile(); + if (_storage.LoadDataSingle(selectedFile.getAbsolutePath())) { + JOptionPane.showMessageDialog(null, "Загрузка прошла успешно", "Результат", JOptionPane.INFORMATION_MESSAGE); + } else { + JOptionPane.showMessageDialog(null, "Не загрузилось", "Результат", JOptionPane.ERROR_MESSAGE); + } + } + ReloadObjects(); + } + } + ); + JMenuItem saveItemSingle = new JMenuItem("Сохранить одиночный"); + saveItemSingle.addActionListener( + new ActionListener() { + public void actionPerformed(ActionEvent e){ + if (jListStorage.getSelectedValue() == null){ + JOptionPane.showMessageDialog(null, "Не выбран гараж", "Ошибка", JOptionPane.ERROR_MESSAGE); + return; + } + + JFileChooser fileChooser = new JFileChooser(); + fileChooser.setDialogTitle("Выберите файл для сохранения данных"); + + fileChooser.setFileFilter(new FileNameExtensionFilter("Текстовые файлы (*.txt)", "txt")); + + if (fileChooser.showSaveDialog(null) == JFileChooser.APPROVE_OPTION) { + File selectedFile = fileChooser.getSelectedFile(); + if (_storage.SaveDataSingle(selectedFile.getAbsolutePath(), jListStorage.getSelectedValue())) + JOptionPane.showMessageDialog(null, "Сохранение прошло успешно", "Результат", JOptionPane.INFORMATION_MESSAGE); + else + JOptionPane.showMessageDialog(null, "Не сохранилось", "Результат", JOptionPane.ERROR_MESSAGE); + } + } + } + ); + fileMenu.add(openItem); + fileMenu.add(saveItem); + fileMenu.add(openItemSingle); + fileMenu.add(saveItemSingle); + + menuBar.add(fileMenu); Frame.setSize (880, 520); Frame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE); @@ -221,6 +322,7 @@ public class FormTruckCollection { ButtonRemoveTruck.setBounds(pictureBoxWidth, 60, 160, 20); ButtonRefreshCollection.setBounds(pictureBoxWidth, 90, 160, 20); FormTruckGenerate.setBounds(pictureBoxWidth, 120, 160, 20); + menuBar.setBounds(pictureBoxWidth, 360, 160, 20); buttonAddSet.setBounds(pictureBoxWidth, 150, 160, 20); textBoxSetName.setBounds(pictureBoxWidth, 180, 160, 20); @@ -238,6 +340,7 @@ public class FormTruckCollection { Frame.add(textBoxSetName); Frame.add(jListStorage); Frame.add(buttonRemoveSet); + Frame.add(menuBar); Frame.add(buttonGetRemoved); Frame.setVisible(true); diff --git a/src/RoadTrain/Generics/SetGeneric.java b/src/RoadTrain/Generics/SetGeneric.java index 62ca44f..72fd7a6 100644 --- a/src/RoadTrain/Generics/SetGeneric.java +++ b/src/RoadTrain/Generics/SetGeneric.java @@ -17,7 +17,7 @@ public class SetGeneric { if (_places.size() >= _maxCount) return -1; _places.add(0, train); - return 0; + return 1; } public boolean Insert(T train, int position) { if (_places.size() >= _maxCount) @@ -74,4 +74,5 @@ public class SetGeneric { } }; } + public void clear(){ _places.clear(); } } diff --git a/src/RoadTrain/Generics/TrucksGenericCollection.java b/src/RoadTrain/Generics/TrucksGenericCollection.java index b2f9c49..1f7e370 100644 --- a/src/RoadTrain/Generics/TrucksGenericCollection.java +++ b/src/RoadTrain/Generics/TrucksGenericCollection.java @@ -25,6 +25,7 @@ public class TrucksGenericCollection(width * height); } + public Iterable getTrucks(final Integer maxTrucks) { return _collection.GetTrucks(maxTrucks); } // Перегрузка оператора сложения public int Add(T obj) { @@ -84,4 +85,5 @@ public class TrucksGenericCollection Keys(){return _truckStorages.keySet().stream().collect(Collectors.toList());} private int _pictureWidth; private int _pictureHeight; + // Разделитель для записи ключа и значения элемента словаря + private static String _separatorForKeyValueWR = "|"; + private static String _separatorForKeyValue = "\\|"; + // Разделитель для записей коллекции данных в файл + private String _separatorRecordsWR = ";"; + private String _separatorRecords = "\\;"; + // Разделитель для записи информации по объекту в файл + private static String _separatorForObjectWR = ":"; + private static String _separatorForObject = "\\:"; public TrucksGenericStorage(int pictureWidth, int pictureHeight) { _truckStorages = new HashMap>(); _pictureWidth = pictureWidth; _pictureHeight = pictureHeight; } + public boolean SaveDataSingle(String filename, String key){ + if (new File(filename).exists()) { + new File(filename).delete(); + } + + StringBuilder data = new StringBuilder(); + data.append(key).append("\n"); + for (DrawingTruck elem : _truckStorages.get(key).getTrucks(100)) { + if (_truckStorages.get(key) == null) + return false; + data.append(elem != null ? ExtentionDrawningTruck.GetDataForSave(elem, _separatorForObjectWR) + "\n" : ""); + } + + if (data.length() == 0) + return false; + + try (BufferedWriter writer = new BufferedWriter(new FileWriter(filename))) { + writer.write("TruckStorageSingle" + System.lineSeparator() + data.toString()); + } catch (IOException e) { + e.printStackTrace(); + return false; + } + + return true; + } + + public boolean LoadDataSingle(String filename){ + if (!new File(filename).exists()) { + return false; + } + + try (BufferedReader reader = new BufferedReader(new FileReader(filename))) { + String s = reader.readLine(); + if (s == null || s.length() == 0) + return false; + + if (!s.startsWith("TruckStorageSingle")) + return false; + + String key = reader.readLine(); + if (key == null || key.length() == 0) + return false; + + TrucksGenericCollection collection; + if (_truckStorages.containsKey(key)){ + collection = _truckStorages.get(key); + collection.clear(); + } + else + collection = new TrucksGenericCollection<>(_pictureWidth, _pictureHeight); + + List trainsStrings = new ArrayList(); + + s = reader.readLine(); + while (s != null && s.length() != 0){ + trainsStrings.add(s); + s = reader.readLine(); + } + + Collections.reverse(trainsStrings); + for (String elem : trainsStrings) { + DrawingTruck train = ExtentionDrawningTruck.CreateDrawingTruck(elem, _separatorForObject, _pictureWidth, _pictureHeight); + if (train == null || collection.Add(train) == -1) + return false; + } + + _truckStorages.put(key, collection); + } catch (IOException e) { + e.printStackTrace(); + return false; + } + + return true; + } + public boolean SaveData(String filename) + { + if (new File(filename).exists()) { + new File(filename).delete(); + } + + StringBuilder data = new StringBuilder(); + + for (Map.Entry> record : _truckStorages.entrySet()) { + StringBuilder records = new StringBuilder(); + for (DrawingTruck elem : record.getValue().getTrucks(100)) { + records.append(elem != null ? ExtentionDrawningTruck.GetDataForSave(elem, _separatorForObjectWR) + _separatorRecordsWR : ""); + } + data.append(record.getKey()).append(_separatorForKeyValueWR).append(records).append("\n"); + } + + if (data.length() == 0) + return false; + + try (BufferedWriter writer = new BufferedWriter(new FileWriter(filename))) { + writer.write("TruckStorage" + System.lineSeparator() + data.toString()); + } catch (IOException e) { + e.printStackTrace(); + return false; + } + + return true; + } + public boolean LoadData(String filename) { + if (!new File(filename).exists()) { + return false; + } + + try (BufferedReader reader = new BufferedReader(new FileReader(filename))) { + String s = reader.readLine(); + if (s == null || s.length() == 0) + return false; + + if (!s.startsWith("TruckStorage")) + return false; + + _truckStorages.clear(); + s = reader.readLine(); + while (s != null && s.length() != 0) { + String[] record = s.split(_separatorForKeyValue); + s = reader.readLine(); + if (record.length != 2) { + continue; + } + TrucksGenericCollection collection = new TrucksGenericCollection<>(_pictureWidth, _pictureHeight); + String[] set = record[1].split(_separatorRecords); + List reversedSet = Arrays.asList(set); + Collections.reverse(reversedSet); + for (String elem : reversedSet) { + DrawingTruck truck = ExtentionDrawningTruck.CreateDrawingTruck(elem, _separatorForObject, _pictureWidth, _pictureHeight); + if (truck == null || collection.Add(truck) == -1) + return false; + } + _truckStorages.put(record[0], collection); + } + } catch (IOException e) { + e.printStackTrace(); + return false; + } + return true; + } public void AddSet(String name) { if (_truckStorages.containsKey(name))