LabWork6 Zacharchenko PIbd-21 #8

Closed
shadowik wants to merge 1 commits from LabWork6 into LabWork5
11 changed files with 369 additions and 30 deletions
Showing only changes of commit b29d0761a5 - Show all commits

View File

@ -10,8 +10,10 @@ import javafx.scene.canvas.GraphicsContext;
import javafx.scene.control.*;
import javafx.scene.layout.AnchorPane;
import javafx.scene.paint.Color;
import javafx.stage.FileChooser;
import javafx.stage.Stage;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Objects;
@ -40,6 +42,9 @@ public class ControllerMapWithSetBus {
@FXML
private Canvas canvasBus;
@FXML
private Button buttonLeft;
@FXML
private ChoiceBox<String> comboBoxSelectorMap;
@ -59,7 +64,7 @@ public class ControllerMapWithSetBus {
private void initialize(){
gc = canvasBus.getGraphicsContext2D();
if (selected != null) {
ShowStorage();
showStorage();
}
if (_mapsCollection == null)
_mapsCollection = new MapsCollection((int) canvasBus.getWidth(), (int) canvasBus.getHeight());
@ -68,7 +73,7 @@ public class ControllerMapWithSetBus {
listViewMaps.getSelectionModel().selectedItemProperty()
.addListener((observableValue, s, t1) -> {
selected = t1;
ShowStorage();
showStorage();
});
listViewMaps.setItems(_mapsCollection.toObserveList());
}
@ -109,16 +114,16 @@ public class ControllerMapWithSetBus {
{
return;
}
Stage stageBus = new Stage();
Stage busStage = new Stage();
FXMLLoader fxmlLoader = new FXMLLoader(Form.class.getResource("FormBusConfig.fxml"));
Scene sceneBus = new Scene(fxmlLoader.load());
stageBus.setScene(sceneBus);
stageBus.show();
busStage.setScene(sceneBus);
busStage.show();
ControllerBusConfig controller = fxmlLoader.getController();
controller.AddEvent(this::AddBus);
controller.SetStage(stageBus);
ControllerBusConfig controllerBusConfig = fxmlLoader.getController();
controllerBusConfig.AddEvent(this::AddBus);
controllerBusConfig.SetStage(busStage);
FirstIncome();
}
@ -136,14 +141,13 @@ public class ControllerMapWithSetBus {
{
alert = new Alert(Alert.AlertType.INFORMATION, "Объект добавлен", ButtonType.OK);
_mapsCollection.get(selectedMapName).ShowSet(gc);
ShowStorage();
}
else
{
alert = new Alert(Alert.AlertType.ERROR, "Не удалось добавить объект", ButtonType.OK);
}
showStorage();
alert.showAndWait();
}
@FXML
@ -167,7 +171,7 @@ public class ControllerMapWithSetBus {
}
_mapsCollection.AddMap(TextFieldMap.getText(), _mapsDict.get(comboBoxSelectorMap.getValue()));
ReloadMaps();
ShowStorage();
showStorage();
}
@FXML
private void ButtonDeleteMap_Click(ActionEvent event)
@ -178,7 +182,7 @@ public class ControllerMapWithSetBus {
}
_mapsCollection.DelMap(listViewMaps.getSelectionModel().getSelectedItem());
ReloadMaps();
ShowStorage();
showStorage();
}
@FXML
@ -187,7 +191,7 @@ public class ControllerMapWithSetBus {
{
return;
}
DrawingObjectBus deleteBus = _mapsCollection.get(selected).getDeletedBus();
DrawingObjectBus deleteBus = (DrawingObjectBus) _mapsCollection.get(selected).getDeletedBus();
if (deleteBus != null) {
ControllerBus._bus = deleteBus.getBus();
FXMLLoader fxmlLoader = new FXMLLoader(Form.class.getResource("FormBus.fxml"));
@ -238,23 +242,19 @@ public class ControllerMapWithSetBus {
alert.setContentText("Не удалось удалить объект");
option = alert.showAndWait();
}
ShowStorage();
showStorage();
}
@FXML
private void ButtonShowStorage_Click(ActionEvent event)
{
FirstIncome();
ShowStorage();
showStorage();
}
@FXML
private void ButtonShowOnMap_Click(ActionEvent event) {
FirstIncome();
ShowMap();
}
private void ShowMap() {
if (selected == null) {
return;
}
@ -282,16 +282,110 @@ public class ControllerMapWithSetBus {
_mapsCollection.GetId(selected).MoveObject(dir);
}
private void ShowStorage() {
@FXML
private void ButtonSave_Click(ActionEvent event) throws IOException {
Alert infoAlert;
Stage stage = (Stage)(canvasBus.getScene().getWindow());
FileChooser fileChooser = new FileChooser();
fileChooser.setTitle("Save");
FileChooser.ExtensionFilter fileExtensions = new FileChooser.ExtensionFilter("TEXT files (*.txt)",
"*.txt");
fileChooser.getExtensionFilters().add(fileExtensions);
File selectedDirectory = fileChooser.showSaveDialog(stage);
if (selectedDirectory != null)
{
String filepath = selectedDirectory.getPath();
if (_mapsCollection.SaveData(filepath))
{
infoAlert = new Alert(Alert.AlertType.INFORMATION, "Save was successful", ButtonType.OK);
}
else
{
infoAlert = new Alert(Alert.AlertType.INFORMATION, "The file was not saved", ButtonType.OK);
}
}
else
{
infoAlert = new Alert(Alert.AlertType.INFORMATION, "The file was not saved", ButtonType.OK);
}
infoAlert.showAndWait();
}
@FXML
private void ButtonLoad_Click(ActionEvent event) throws IOException {
Alert infoAlert;
Stage stage = (Stage)(buttonLeft.getScene().getWindow());
FileChooser fileChooser = new FileChooser();
fileChooser.setTitle("Load");
FileChooser.ExtensionFilter fileExtensions = new FileChooser.ExtensionFilter("TEXT files (*.txt)", "*.txt");
fileChooser.getExtensionFilters().add(fileExtensions);
File selectedDirectory = fileChooser.showOpenDialog(stage);
if (selectedDirectory != null)
{
String filepath = selectedDirectory.getPath();
if (_mapsCollection.LoadData(filepath))
{
infoAlert = new Alert(Alert.AlertType.INFORMATION, "Load was successful", ButtonType.OK);
ReloadMaps();
}
else
{
infoAlert = new Alert(Alert.AlertType.INFORMATION, "The file was not loaded", ButtonType.OK);
}
}
else
{
infoAlert = new Alert(Alert.AlertType.INFORMATION, "The file was not loaded", ButtonType.OK);
}
infoAlert.showAndWait();
}
@FXML
private void ButtonSaveStorage_Click(ActionEvent event) throws IOException {
Alert infoAlert;
Stage stage = (Stage)(canvasBus.getScene().getWindow());
FileChooser fileChooser = new FileChooser();
fileChooser.setTitle("Save");
FileChooser.ExtensionFilter fileExtensions = new FileChooser.ExtensionFilter("TEXT files (*.txt)",
"*.txt");
fileChooser.getExtensionFilters().add(fileExtensions);
File selectedDirectory = fileChooser.showSaveDialog(stage);
if (selectedDirectory != null)
{
String filepath = selectedDirectory.getPath();
if (_mapsCollection.SaveStorage(filepath, listViewMaps.getSelectionModel().getSelectedItem()))
{
infoAlert = new Alert(Alert.AlertType.INFORMATION, "Save was successful", ButtonType.OK);
}
else
{
infoAlert = new Alert(Alert.AlertType.INFORMATION, "The file was not saved", ButtonType.OK);
}
}
else
{
infoAlert = new Alert(Alert.AlertType.INFORMATION, "The file was not saved", ButtonType.OK);
}
infoAlert.showAndWait();
}
private void showStorage() {
if (selected == null)
{
return;
}
gc.setFill(Color.WHITE);
gc.clearRect(0, 0, canvasBus.getWidth(), canvasBus.getHeight());
gc.fillRect(0, 0, pictureBoxBus.getWidth(), pictureBoxBus.getHeight());
_mapsCollection.GetId(selected).ShowSet(gc);
}
}

View File

@ -26,6 +26,17 @@ public class DrawingBus {
Bus = CreateBus(speed, weight, bodyColor, countOfDoors);
}
public DrawingBus(int speed, float weight, Color bodyColor, int countOfDoors, IDrawingDoors TypeDoors) {
_speed = speed;
_weight = weight;
_bodyColor = bodyColor;
_countOfDoors = countOfDoors;
EntityBus bus = new EntityBus(speed, weight, bodyColor);
Doors = TypeDoors;
Doors.setCountOfDoors(countOfDoors);
Bus = bus;
}
private EntityBus CreateBus(int speed, float weight, Color bodyColor, int countOfDoors) {
_speed = speed;
_weight = weight;

View File

@ -14,6 +14,12 @@ public class DrawingDDB extends DrawingBus{
Bus = CreateDDB(speed, weight, bodyColor, countOfDoors, extraColor, ladder, secondStage);
}
public DrawingDDB(int speed, float weight, Color bodyColor, int countOfDoors, IDrawingDoors typeDoor,
Color extraColor, boolean ladder, boolean secondStage) {
super(speed, weight, bodyColor, countOfDoors, typeDoor);
Bus = CreateDDB(speed, weight, bodyColor, countOfDoors, extraColor, ladder, secondStage);
}
private EntityDDB CreateDDB(int speed, float weight, Color bodyColor, int countOfDoors,
Color extraColor, boolean ladder, boolean secondStage) {
_speed = speed;

View File

@ -25,6 +25,11 @@ public class DrawingObjectBus implements IDrawingObject {
return null;
}
@Override
public String GetInfo() {
return ExtensionBus.GetDataForSave(_bus);
}
public void MoveObject(Direction direction)
{
_bus.MoveTransport(direction);
@ -43,4 +48,8 @@ public class DrawingObjectBus implements IDrawingObject {
public DrawingBus getBus() {
return _bus;
}
public static IDrawingObject Create(String data) {
return new DrawingObjectBus(ExtensionBus.CreateDrawingBus(data));
}
}

View File

@ -14,10 +14,10 @@ public class DrawingPolymorphBus<T extends EntityBus, U extends IDrawingDoors> {
doors = new Object[doorsCount];
}
public int AddEntity(T boat)
public int AddEntity(T bus)
{
if(busesCount < buses.length){
buses[busesCount] = boat;
buses[busesCount] = bus;
return busesCount++;
}
return -1;

View File

@ -0,0 +1,62 @@
package com.example.doubledeckerbus;
import javafx.scene.paint.Color;
public class ExtensionBus {
private static char _separatorForObject = ':';
public static DrawingBus CreateDrawingBus(String info) {
String[] strs = info.split(String.valueOf(_separatorForObject));
if (strs.length == 5) {
return new DrawingBus(Integer.parseInt(strs[0]),
Float.parseFloat(strs[1].replace(',', '.')), Color.web(strs[2]),
Integer.parseInt(strs[3]), CreateDoors(strs[4]));
}
if (strs.length == 8) {
return new DrawingDDB(Integer.parseInt(strs[0]), Float.parseFloat(strs[1].replace(',', '.')),
Color.web(strs[2]), Integer.parseInt(strs[3]), CreateDoors(strs[4]),
Color.web(strs[5]), Boolean.parseBoolean(strs[6]),
Boolean.parseBoolean(strs[7]));
}
return null;
}
private static IDrawingDoors CreateDoors(String name) {
switch (name) {
case "Triangle" -> {
return new DrawingTriangleDoors();
}
case "Oval" -> {
return new DrawingEllipsoidDoors();
}
case "Rect" -> {
return new DrawingDoors();
}
}
return new DrawingDoors();
}
private static String CreateDoors(IDrawingDoors doors) {
if (doors instanceof DrawingEllipsoidDoors) {
return "Oval";
}
else if (doors instanceof DrawingTriangleDoors) {
return "Triangle";
}
else {
return "Rect";
}
}
public static String GetDataForSave(DrawingBus drawingBus)
{
var bus = drawingBus.Bus;
var str = String.format("%d:%f:%s:%d:%s", bus.Speed, bus.Weight, bus.BodyColor.toString(),
drawingBus._countOfDoors, CreateDoors(drawingBus.Doors));;
if (!(bus instanceof EntityDDB ddb))
{
return str;
}
return str + String.format(":%s:%b:%b", ddb.ExtraColor.toString(), ddb.Ladder, ddb.SecondStage);
}
}

View File

@ -12,4 +12,6 @@ public interface IDrawingObject {
void DrawingObject(GraphicsContext g);
Position GetCurrentPosition();
String GetInfo();
}

View File

@ -147,5 +147,34 @@ public class MapWithSetBusesGeneric<T extends IDrawingObject, U extends Abstract
public T getBus(int ind){
return _setBuses.Get(ind);
}
public String GetData(char separatorType, char separatorData)
{
StringBuilder data = new StringBuilder(String.format("%s%c", _map.getClass().getSimpleName(), separatorType));
for (T bus : _setBuses.GetBuses())
{
data.append(String.format("%s%c", bus.GetInfo(), separatorData));
}
return data.toString();
}
@SuppressWarnings("unchecked")
public void LoadData(String[] data)
{
for (String items : data)
{
_setBuses.Insert((T)(DrawingObjectBus.Create(items)));
}
}
@SuppressWarnings("unchecked")
public void LoadData(String data)
{
_setBuses.Insert((T)(DrawingObjectBus.Create(data)));
}
public void Clear() {
_setBuses.Clear();
}
}

View File

@ -3,11 +3,17 @@ package com.example.doubledeckerbus;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import java.util.HashMap;
import java.util.List;
import java.io.*;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.*;
public class MapsCollection {
HashMap<String, MapWithSetBusesGeneric<DrawingObjectBus, AbstractMap>> _mapStorages;
HashMap<String, MapWithSetBusesGeneric<IDrawingObject, AbstractMap>> _mapStorages;
private final char separatorDict = '|';
private final char separatorData = ';';
public List<String> Keys() {
return _mapStorages.keySet().stream().toList();
@ -27,7 +33,7 @@ public class MapsCollection {
public void AddMap(String name, AbstractMap map)
{
if (Keys().contains(name)) return;
_mapStorages.put(name, new MapWithSetBusesGeneric<DrawingObjectBus, AbstractMap>(_pictureWidth, _pictureHeight, map));
_mapStorages.put(name, new MapWithSetBusesGeneric<IDrawingObject, AbstractMap>(_pictureWidth, _pictureHeight, map));
}
public void DelMap(String name)
@ -35,7 +41,7 @@ public class MapsCollection {
_mapStorages.remove(name);
}
public MapWithSetBusesGeneric<DrawingObjectBus, AbstractMap> GetId(String id)
public MapWithSetBusesGeneric<IDrawingObject, AbstractMap> GetId(String id)
{
return _mapStorages.get(id);
}
@ -46,7 +52,7 @@ public class MapsCollection {
return result;
}
public MapWithSetBusesGeneric<DrawingObjectBus, AbstractMap> get(String id) {
public MapWithSetBusesGeneric<IDrawingObject, AbstractMap> get(String id) {
if (_mapStorages.containsKey(id))
{
return _mapStorages.get(id);
@ -54,7 +60,7 @@ public class MapsCollection {
return null;
}
public DrawingObjectBus get(String name, int id) {
public IDrawingObject get(String name, int id) {
if (_mapStorages.containsKey(name))
{
return _mapStorages.get(name).getBus(id);
@ -62,4 +68,108 @@ public class MapsCollection {
return null;
}
public boolean SaveData(String filename) throws IOException
{
Files.deleteIfExists(Paths.get(filename));
try (Writer writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(filename),
StandardCharsets.UTF_8)))
{
writer.write("MapsCollection" + System.lineSeparator());
for (String storageKey : _mapStorages.keySet())
{
MapWithSetBusesGeneric<IDrawingObject, AbstractMap> storage = _mapStorages.get(storageKey);
writer.write(String.format("%s|%s\n", storageKey, storage.GetData(separatorDict, separatorData)));
}
}
return true;
}
static String[] reverse(String myArray[])
{
Collections.reverse(Arrays.asList(myArray));
return (String[]) Arrays.stream(myArray).toArray();
}
public boolean SaveStorage(String filename, String key) throws IOException
{
Files.deleteIfExists(Paths.get(filename));
try (Writer writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(filename),
StandardCharsets.UTF_8)))
{
writer.write("MapsCollectionStorage" + System.lineSeparator());
MapWithSetBusesGeneric<IDrawingObject, AbstractMap> storage = _mapStorages.get(key);
if (storage == null) {
return false;
}
String[] data = storage.GetData(separatorDict, separatorData).split("\\|");
writer.write(key + ":" + data[0] + System.lineSeparator());
var buses = data[1].split(";");
for (int i = buses.length - 1; i >= 0; i--) {
writer.write(buses[i]);
writer.write(System.lineSeparator());
}
}
return true;
}
public boolean LoadData(String filename) throws IOException
{
File file = new File(filename);
if(!file.exists() || file.isDirectory())
{
return false;
}
try (BufferedReader reader = new BufferedReader(new FileReader(filename)))
{
String str = reader.readLine();
if (str == null || (!str.contains("MapsCollection") && !str.contains("MapsCollectionStorage")))
{
return false;
}
if (!str.contains("MapsCollectionStorage")) {
while ((str = reader.readLine()) != null) {
String[] elem = str.split(String.format("\\%c", separatorDict));
AbstractMap map = switch (elem[1]) {
case "SimpleMap" -> new SimpleMap();
case "WaterMap" -> new WaterMap();
default -> null;
};
if (elem.length == 3) {
_mapStorages.get(elem[0]).LoadData(elem[2].split(String.format("%c", separatorData)));
}
}
}
else {
String[] data = reader.readLine().split(":");
AbstractMap map = switch (data[1]) {
case "SimpleMap" -> new SimpleMap();
case "WaterMap" -> new WaterMap();
default -> null;
};
if (_mapStorages.containsKey(data[0])) {
_mapStorages.get(data[0]).Clear();
}
else {
_mapStorages.put(data[0], new MapWithSetBusesGeneric<>(_pictureWidth, _pictureHeight, map));
}
String k = reader.readLine();
while (k != null) {
_mapStorages.get(data[0]).LoadData(k);
k = reader.readLine();
}
}
}
return true;
}
}

View File

@ -59,6 +59,10 @@ class SetBusesGeneric<T> {
public int Count() {
return _places.size();
}
public void Clear() {
_places.clear();
}
}

View File

@ -6,6 +6,7 @@
<?import javafx.scene.control.ChoiceBox?>
<?import javafx.scene.control.ListView?>
<?import javafx.scene.control.TextField?>
<?import javafx.scene.control.TitledPane?>
<?import javafx.scene.image.Image?>
<?import javafx.scene.image.ImageView?>
<?import javafx.scene.layout.AnchorPane?>
@ -25,6 +26,17 @@
<AnchorPane fx:id="pictureBoxBus" prefHeight="9.9999999E7" prefWidth="9.9999999E7">
<children>
<Canvas fx:id="canvasBus" height="745.0" width="573.0" />
<TitledPane text="Сохранение">
<content>
<AnchorPane minHeight="0.0" minWidth="0.0" prefHeight="180.0" prefWidth="200.0">
<children>
<Button fx:id="ButtonSave" layoutX="-1.0" mnemonicParsing="false" onAction="#ButtonSave_Click" prefHeight="50.0" prefWidth="202.0" text="Сохранить" />
<Button fx:id="ButtonLoad" layoutX="-1.0" layoutY="50.0" mnemonicParsing="false" onAction="#ButtonLoad_Click" prefHeight="50.0" prefWidth="202.0" text="Загрузить" />
<Button fx:id="ButtonLoad1" layoutX="-1.0" layoutY="100.0" mnemonicParsing="false" onAction="#ButtonSaveStorage_Click" prefHeight="50.0" prefWidth="202.0" text="Сохранить хранилище" />
</children>
</AnchorPane>
</content>
</TitledPane>
</children>
</AnchorPane>
<Group GridPane.columnIndex="1" />