looks like a ready lab 6

This commit is contained in:
ekallin 2023-12-18 00:49:42 +04:00
parent c958114545
commit a81842346b
4 changed files with 287 additions and 45 deletions

View File

@ -1,55 +1,89 @@
package ProjectElectricLocomotive;
import java.awt.*;
import java.util.Objects;
public class ExtentionDrawingLoco {
public static DrawingLocomotive CreateDrawingLocomotive(String info, char separatorForObject, int width, int height)
public static DrawingLocomotive CreateDrawingLocomotive(String info, String separatorForObject, int width, int height)
{
String[] strs = info.split(String.valueOf(separatorForObject));
if(strs.length == 3){
return new DrawingLocomotive(
Integer.parseInt(strs[0]),
Integer.parseInt(strs[1]),
Color.getColor(strs[2]),
width,
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 == 6){
return new DrawingElectricLocomotive(
Integer.parseInt(strs[0]),
Integer.parseInt(strs[1]),
Color.getColor(strs[2]),
Color.getColor(strs[3]),
strs[4].equals(true),
strs[5].equals(true),
width,
height
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, char separatorForObject)
{
public static String GetDataForSave(DrawingLocomotive drawingLoco, String separatorForObject) {
var loco = drawingLoco.EntityLocomotive;
if (loco == null)
{
return null;
if (loco == null) {
return "";
}
String str = loco.Speed + separatorForObject + loco.Weight + separatorForObject + loco.BodyColor.toString();
if (!(loco instanceof EntityElectricLocomotive electroLoco))
{
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;
}
else
{
return str + separatorForObject + electroLoco.AdditionalColor.toString() + separatorForObject +
electroLoco.Horns + separatorForObject + electroLoco.SeifBatteries;
}
return str +
separatorForObject +
electroLoco.AdditionalColor.getRed() + separatorForObject +
electroLoco.AdditionalColor.getGreen() + separatorForObject +
electroLoco.AdditionalColor.getBlue() + separatorForObject +
electroLoco.Horns +
separatorForObject +
electroLoco.SeifBatteries;
}
}

View File

@ -2,7 +2,9 @@ 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
@ -165,6 +167,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());

View File

@ -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();

View File

@ -1,17 +1,24 @@
package ProjectElectricLocomotive;
import javax.xml.crypto.dsig.keyinfo.KeyValue;
import java.io.*;
import java.util.*;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.util.HashMap;
import java.util.List;
import java.io.IOException;
public class LocomotivesGenericStorage {
public final char _separatorForKeyValue = '|';
public final char _separatorRecords = ';';
public final char _separatorForObject = ':';
private static final String _separatorForKeyValue = "@";
private static final String _separatorRecords = ";";
private static final String _separatorForObject = ":";
private static final String _separatorForObjectSingle = "::";
private static final String _keyword = "PlanesStorage";
private static final String _keywordSingle = "PlanesStorageSingle";
final HashMap<String, LocomotiveGenericCollection<DrawingLocomotive, DrawingObjectLocomotive>> _locomotiveStorage;
public List<String> Keys() {
@ -53,14 +60,133 @@ public class LocomotivesGenericStorage {
return null;
}
public boolean SaveData(String filename) {
if (new File(filename).exists()) {
new File(filename).delete();
public boolean SaveDataSingle(String filename, String key) {
var file = new File(filename);
if (file.exists()) {
file.delete();
}
StringBuilder data = new StringBuilder();
// for(KeyValue<String, LocomotiveGenericCollection<DrawingLocomotive, DrawingObjectLocomotive>> record : _locomotiveStorage)
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<DrawingLocomotive, DrawingObjectLocomotive> collection;
if (_locomotiveStorage.containsKey(key)){
collection = _locomotiveStorage.get(key);
// collection.clear(); // what is the wtf???
}
else
collection = new LocomotiveGenericCollection<>(_pictureWidth, _pictureHeight);
List<String> 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<String, LocomotiveGenericCollection<DrawingLocomotive, DrawingObjectLocomotive>> 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<DrawingLocomotive, DrawingObjectLocomotive> collection = new LocomotiveGenericCollection<>(_pictureWidth, _pictureHeight);
String[] set = record[1].split(_separatorRecords);
List<String> 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;
}
}