diff --git a/ProjectElectricLocomotive/ExtentionDrawingLoco.java b/ProjectElectricLocomotive/ExtentionDrawingLoco.java new file mode 100644 index 0000000..3229b26 --- /dev/null +++ b/ProjectElectricLocomotive/ExtentionDrawingLoco.java @@ -0,0 +1,89 @@ +package ProjectElectricLocomotive; + +import java.awt.*; +import java.util.Objects; + +public class ExtentionDrawingLoco { + public static DrawingLocomotive CreateDrawingLocomotive(String info, String separatorForObject, int width, int height) + { + String[] strs = info.split(separatorForObject); + if (strs.length == 7) { + DrawingLocomotive drawingLoco = new DrawingLocomotive( + Integer.parseInt(strs[0]), + Double.parseDouble(strs[1]), + new Color( + Integer.parseInt(strs[2]), + Integer.parseInt(strs[3]), + Integer.parseInt(strs[4]) + ), + width, height + ); + if (Objects.equals(strs[5], "DrawingWheel")) { + drawingLoco._drawingWheels = new DrawingWheel(); + } else if (Objects.equals(strs[5], "DrawingEmptyWheels")) { + drawingLoco._drawingWheels = new DrawingEmptyWheels(); + } else if (Objects.equals(strs[5], "DrawingWheelsBlueCrom")) { + drawingLoco._drawingWheels = new DrawingWheelsBlueCrom(); + } + drawingLoco.SetWheelsCount(Integer.parseInt(strs[6])); + return drawingLoco; + } + if (strs.length == 12) { + DrawingLocomotive drawingLoco = new DrawingElectricLocomotive( + Integer.parseInt(strs[0]), + Double.parseDouble(strs[1]), + new Color( + Integer.parseInt(strs[2]), + Integer.parseInt(strs[3]), + Integer.parseInt(strs[4]) + ), + new Color( + Integer.parseInt(strs[7]), + Integer.parseInt(strs[8]), + Integer.parseInt(strs[9]) + ), + Boolean.parseBoolean(strs[10]), + Boolean.parseBoolean(strs[11]), + width, height + ); + if (Objects.equals(strs[5], "DrawingWheel")) { + drawingLoco._drawingWheels = new DrawingWheel(); + } else if (Objects.equals(strs[5], "DrawingEmptyWheels")) { + drawingLoco._drawingWheels = new DrawingEmptyWheels(); + } else if (Objects.equals(strs[5], "DrawingWheelsBlueCrom")) { + drawingLoco._drawingWheels = new DrawingWheelsBlueCrom(); + } + drawingLoco.SetWheelsCount(Integer.parseInt(strs[6])); + return drawingLoco; + } + return null; + } + + public static String GetDataForSave(DrawingLocomotive drawingLoco, String separatorForObject) { + var loco = drawingLoco.EntityLocomotive; + if (loco == null) { + return ""; + } + String str = loco.Speed + + separatorForObject + + loco.Weight + + separatorForObject + + loco.BodyColor.getRed() + separatorForObject + + loco.BodyColor.getGreen() + separatorForObject + + loco.BodyColor.getBlue() + separatorForObject + + (drawingLoco._drawingWheels.GetWheelsCount() == null ? "null" : drawingLoco._drawingWheels.getClass()) + separatorForObject + + (drawingLoco._drawingWheels.GetWheelsCount() == null ? "0" : drawingLoco._drawingWheels.GetWheelsCount().count); + if (!(loco instanceof EntityElectricLocomotive electroLoco)) { + return str; + } + return str + + separatorForObject + + electroLoco.AdditionalColor.getRed() + separatorForObject + + electroLoco.AdditionalColor.getGreen() + separatorForObject + + electroLoco.AdditionalColor.getBlue() + separatorForObject + + electroLoco.Horns + + separatorForObject + + electroLoco.SeifBatteries; + } + +} diff --git a/ProjectElectricLocomotive/FormLocomotiveCollections.java b/ProjectElectricLocomotive/FormLocomotiveCollections.java index 96d1640..3c99704 100644 --- a/ProjectElectricLocomotive/FormLocomotiveCollections.java +++ b/ProjectElectricLocomotive/FormLocomotiveCollections.java @@ -2,11 +2,11 @@ package ProjectElectricLocomotive; import javax.swing.*; import javax.swing.event.ListSelectionEvent; +import javax.swing.filechooser.FileNameExtensionFilter; import java.awt.*; +import java.io.File; import java.util.Stack; -//готовая лаба 3 - public class FormLocomotiveCollections { FormElectricLocomotive formElectricLocomotive; FormLocomotiveConfig formLocomotiveConfig; @@ -165,6 +165,85 @@ public class FormLocomotiveCollections { } + public JMenuBar getMenuBar() { + JMenuBar menuBar = new JMenuBar(); + JMenu fileMenu = new JMenu("Файл"); + JMenuItem openItem = new JMenuItem("Загрузить"); + openItem.addActionListener( + e -> { + JFileChooser fileChooser = new JFileChooser(); + 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( + 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( + e -> { + JFileChooser fileChooser = new JFileChooser(); + 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( + e -> { + if (listBoxStorage.getSelectedValue() == null) { + JOptionPane.showMessageDialog(null, "Коллекция не выбрана", "Ошибка", JOptionPane.ERROR_MESSAGE); + return; + } + JFileChooser fileChooser = new JFileChooser(); + fileChooser.setFileFilter(new FileNameExtensionFilter("Текстовые файлы (*.txt)", "txt")); + fileChooser.setDialogTitle("Выберите файл для сохранения данных"); + if (fileChooser.showSaveDialog(null) == JFileChooser.APPROVE_OPTION) { + File selectedFile = fileChooser.getSelectedFile(); + if (_storage.SaveDataSingle(selectedFile.getAbsolutePath(), (String) listBoxStorage.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); + return menuBar; + } + private void ReloadObjects() { int index = listBoxStorage.getSelectedIndex(); listBoxStorage.setListData(_storage.Keys().toArray()); diff --git a/ProjectElectricLocomotive/FrameLocomotiveCollection.java b/ProjectElectricLocomotive/FrameLocomotiveCollection.java index 189aba5..5fb166f 100644 --- a/ProjectElectricLocomotive/FrameLocomotiveCollection.java +++ b/ProjectElectricLocomotive/FrameLocomotiveCollection.java @@ -9,6 +9,7 @@ public class FrameLocomotiveCollection extends JFrame { setTitle("Коллекция");setDefaultCloseOperation(EXIT_ON_CLOSE); _formLocomotiveCollections = new FormLocomotiveCollections(); setContentPane(_formLocomotiveCollections.getPictureBoxCollections()); + this.setJMenuBar(_formLocomotiveCollections.getMenuBar()); setDefaultLookAndFeelDecorated(false); setLocation(400, 50); pack(); diff --git a/ProjectElectricLocomotive/LocomotiveGenericCollection.java b/ProjectElectricLocomotive/LocomotiveGenericCollection.java index 7b3b154..e58fc66 100644 --- a/ProjectElectricLocomotive/LocomotiveGenericCollection.java +++ b/ProjectElectricLocomotive/LocomotiveGenericCollection.java @@ -24,6 +24,10 @@ public class LocomotiveGenericCollection(width*height); } + public Iterable GetLocomotives(){ + return _collection.GetEnumerator(); + } + /// Перегрузка оператора сложения //да емае, почему в яве все по-другому?... public int AddOverload(T obj){ @@ -87,4 +91,8 @@ public class LocomotiveGenericCollection> _locomotiveStorage; - public List Keys() - { + + public List Keys() { return _locomotiveStorage.keySet().stream().toList(); } + private final int _pictureWidth; private final int _pictureHeight; + public LocomotivesGenericStorage(int pictureWidth, int pictureHeight) { _locomotiveStorage = new HashMap<>(); _pictureWidth = pictureWidth; _pictureHeight = pictureHeight; } - public void AddSet(String name) - { - if (!(_locomotiveStorage.containsKey(name))) - { + public void AddSet(String name) { + if (!(_locomotiveStorage.containsKey(name))) { _locomotiveStorage.put(name, new LocomotiveGenericCollection(_pictureWidth, _pictureHeight)); } } - public void DelSet(String name) - { - if (_locomotiveStorage.keySet().contains(name)) - { + public void DelSet(String name) { + if (_locomotiveStorage.keySet().contains(name)) { _locomotiveStorage.remove(name); } } - public LocomotiveGenericCollection get(String ind) - { - if (_locomotiveStorage.keySet().contains(ind)) - { - return _locomotiveStorage.get(ind); - } - return null; + public LocomotiveGenericCollection get(String ind) { + if (_locomotiveStorage.keySet().contains(ind)) { + return _locomotiveStorage.get(ind); + } + return null; } - public DrawingObjectLocomotive get(String name, int ind) - { - if (_locomotiveStorage.keySet().contains(ind)) - { + public DrawingObjectLocomotive get(String name, int ind) { + if (_locomotiveStorage.keySet().contains(ind)) { return _locomotiveStorage.get(name).GetU(ind); } return null; } + + public boolean SaveDataSingle(String filename, String key) { + var file = new File(filename); + if (file.exists()) { + file.delete(); + } + StringBuilder data = new StringBuilder(); + data.append(key).append("\n"); + for (DrawingLocomotive elem : _locomotiveStorage.get(key).GetLocomotives()) + data.append(elem != null ? ExtentionDrawingLoco.GetDataForSave(elem, _separatorForObjectSingle) + "\n" : ""); + if (data.isEmpty()) { + return false; + } + try (BufferedWriter writer = new BufferedWriter(new FileWriter(filename))) { + writer.write(_keywordSingle + System.lineSeparator() + data); + } catch (IOException e) { + 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.isEmpty()) + return false; + if (!s.startsWith(_keywordSingle)) + return false; + String key = reader.readLine(); + if (key == null || key.isEmpty()) + return false; + LocomotiveGenericCollection collection; + if (_locomotiveStorage.containsKey(key)){ + collection = _locomotiveStorage.get(key); + collection.clear(); + } + else + collection = new LocomotiveGenericCollection<>(_pictureWidth, _pictureHeight); + List plainsStrings = new ArrayList<>(); + s = reader.readLine(); + while (s != null && !s.isEmpty()){ + plainsStrings.add(s); + s = reader.readLine(); + } + Collections.reverse(plainsStrings); + for (String elem : plainsStrings) { + DrawingLocomotive plane = ExtentionDrawingLoco.CreateDrawingLocomotive( + elem, + _separatorForObjectSingle, + _pictureWidth, + _pictureHeight + ); + if (plane == null || collection.AddOverload(plane) == -1) + return false; + } + _locomotiveStorage.put(key, collection); + } catch (IOException e) { + return false; + } + return true; + } + + public boolean SaveData(String filename) { + var file = new File(filename); + if (file.exists()) { + file.delete(); + } + StringBuilder data = new StringBuilder(); + for (Map.Entry> record : _locomotiveStorage.entrySet()) { + StringBuilder records = new StringBuilder(); + for (DrawingLocomotive elem : record.getValue().GetLocomotives()) { + records.append(elem != null ? ExtentionDrawingLoco.GetDataForSave(elem, _separatorForObject) + _separatorRecords : ""); + } + data.append(record.getKey()).append(_separatorForKeyValue).append(records).append("\n"); + } + if (data.isEmpty()) { + return false; + } + try (BufferedWriter writer = new BufferedWriter(new FileWriter(filename))) { + writer.write(_keyword + System.lineSeparator() + data); + } catch (IOException e) { + return false; + } + return true; + } + + public boolean LoadData(String filename) { + var file = new File(filename); + if (!file.exists()) { + return false; + } + try (BufferedReader reader = new BufferedReader(new FileReader(filename))) { + String s = reader.readLine(); + if (s == null || s.isEmpty()) + return false; + + if (!s.startsWith(_keyword)) { + return false; + } + _locomotiveStorage.clear(); + s = reader.readLine(); + while (s != null && !s.isEmpty()) { + String[] record = s.split(_separatorForKeyValue); + s = reader.readLine(); + if (record.length != 2) { + continue; + } + LocomotiveGenericCollection collection = new LocomotiveGenericCollection<>(_pictureWidth, _pictureHeight); + String[] set = record[1].split(_separatorRecords); + List reversedSet = Arrays.asList(set); + Collections.reverse(reversedSet); + for (String elem : reversedSet) { + DrawingLocomotive plane = ExtentionDrawingLoco.CreateDrawingLocomotive( + elem, + _separatorForObject, + _pictureWidth, _pictureHeight + ); + if (plane == null || collection.AddOverload(plane) == -1) + return false; + } + _locomotiveStorage.put(record[0], collection); + } + } catch (IOException e) { + return false; + } + return true; + } } diff --git a/ProjectElectricLocomotive/SetGeneric.java b/ProjectElectricLocomotive/SetGeneric.java index f731887..062252a 100644 --- a/ProjectElectricLocomotive/SetGeneric.java +++ b/ProjectElectricLocomotive/SetGeneric.java @@ -66,4 +66,7 @@ public class SetGeneric{ return _places; } + public void clear() { + _places.clear(); + } } \ No newline at end of file