5 Commits

Author SHA1 Message Date
6df97d8386 reload 2022-12-26 04:32:24 +04:00
b29d0761a5 Resend 2022-12-26 03:58:12 +04:00
728e355b50 Fix 2022-11-29 08:44:44 +04:00
112a806373 Choose style by Drag&Drop 2022-11-29 03:49:33 +04:00
691a60e11d Drag&Drop + Events 2022-11-29 03:22:14 +04:00
21 changed files with 900 additions and 101 deletions

View File

@@ -0,0 +1,24 @@
package com.example.doubledeckerbus;
public class BusNotFoundException extends Exception {
public BusNotFoundException(int num)
{
super("Object not found by position " + num);
}
public BusNotFoundException()
{
super();
}
public BusNotFoundException(String message)
{
super(message);
}
public BusNotFoundException(String message, Throwable cause)
{
super(message, cause);
}
public BusNotFoundException(Throwable cause)
{
super(cause);
}
}

View File

@@ -146,7 +146,7 @@ public class ControllerBus {
BorderChanged();
}
@FXML
private void ButtonSelectBus_Click(ActionEvent event) throws IOException {
private void ButtonSelectBus_Click(ActionEvent event) throws IOException, StorageOverflowException {
SelectedBus = _bus;
if (SelectedBus == null) {

View File

@@ -0,0 +1,187 @@
package com.example.doubledeckerbus;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.scene.canvas.Canvas;
import javafx.scene.canvas.GraphicsContext;
import javafx.scene.control.Button;
import javafx.scene.control.CheckBox;
import javafx.scene.control.Label;
import javafx.scene.control.Spinner;
import javafx.scene.input.*;
import javafx.scene.layout.Background;
import javafx.scene.layout.Region;
import javafx.scene.paint.Color;
import javafx.scene.paint.Paint;
import javafx.stage.Stage;
import java.util.function.Consumer;
public class ControllerBusConfig {
DataFormat colorFormat = DataFormat.lookupMimeType("SerializableColor");
DataFormat additionalElementFormat = DataFormat.lookupMimeType("IDrawningAdditionalElement");
private Stage _stage;
private DrawingBus _bus = null;
private Event<DrawingBus> addBus;
public void SetStage(Stage stage)
{
_stage = stage;
}
public void AddEvent(Consumer<DrawingBus> ev)
{
addBus.AddListener(ev);
}
private void DrawBus()
{
GraphicsContext gc = canvasObject.getGraphicsContext2D();
gc.clearRect(0, 0, canvasObject.getWidth(), canvasObject.getHeight());
if (_bus == null)
{
return;
}
_bus.SetPosition(5, 5, (int)canvasObject.getWidth(), (int)canvasObject.getHeight());
_bus.DrawTransport(gc);
}
@FXML
private Canvas canvasObject;
@FXML
private CheckBox checkBoxSecondStage;
@FXML
private CheckBox checkBoxLadder;
@FXML
private Spinner<Integer> spinnerSpeed = new Spinner<>();
@FXML
private Spinner<Integer> spinnerDoors = new Spinner<>();
@FXML
private Spinner<Integer> spinnerWeight = new Spinner<>();
@FXML
public void initialize()
{
if (colorFormat == null)
{
colorFormat = new DataFormat("SerializableColor");
}
if (additionalElementFormat == null)
{
additionalElementFormat = new DataFormat("IDrawningAdditionalElement");
}
addBus = new Event<>();
}
@FXML
void ButtonOk_Click(ActionEvent event) {
if (_bus != null)
{
addBus.Broadcast(_bus);
}
if (_stage != null)
{
_stage.close();
}
}
@FXML
void CanvasObject_OnDragDropped(DragEvent event) {
Dragboard db = event.getDragboard();
switch (db.getString())
{
case "labelSimpleObject" -> _bus = new DrawingBus(spinnerSpeed.getValue(),
spinnerWeight.getValue(), Color.WHITE, spinnerDoors.getValue());
case "labelModifiedObject" -> _bus = new DrawingDDB(spinnerSpeed.getValue(),
spinnerWeight.getValue(), Color.WHITE, spinnerDoors.getValue(), Color.BLACK,
checkBoxSecondStage.isSelected(), checkBoxLadder.isSelected());
case "labelTriangle" -> _bus.ChangeDoor(new DrawingTriangleDoors());
case "labelOval" -> _bus.ChangeDoor(new DrawingEllipsoidDoors());
case "labelRect" -> _bus.ChangeDoor(new DrawingDoors());
}
DrawBus();
event.consume();
}
@FXML
void CanvasObject_OnDragOver(DragEvent event) {
if (event.getDragboard().hasString())
{
event.acceptTransferModes(TransferMode.COPY_OR_MOVE);
}
event.consume();
}
@FXML
void LabelBaseColor_OnDragDropped(DragEvent event) {
if (_bus == null)
{
return;
}
Dragboard db = event.getDragboard();
_bus.Bus.BodyColor = ((SerializableColor)(db.getContent(colorFormat))).getFXColor();
event.consume();
DrawBus();
}
@FXML
void LabelColor_OnDragOver(DragEvent event) {
if (event.getDragboard().hasContent(colorFormat))
{
event.acceptTransferModes(TransferMode.COPY_OR_MOVE);
}
event.consume();
}
@FXML
void LabelDopColor_OnDragDropped(DragEvent event) {
if (_bus == null || !(_bus.Bus instanceof EntityDDB ddb))
{
return;
}
Dragboard db = event.getDragboard();
ddb.ExtraColor = ((SerializableColor)(db.getContent(colorFormat))).getFXColor();
event.consume();
DrawBus();
}
@FXML
void LabelObject_OnDragDetected(MouseEvent event) {
Label labelObject = (Label)(event.getSource());
Dragboard db = labelObject.startDragAndDrop(TransferMode.ANY);
ClipboardContent content = new ClipboardContent();
content.putString(((Label)(event.getSource())).getId());
db.setContent(content);
event.consume();
}
@FXML
void RegionColor_OnDragDetected(MouseEvent event) {
Region region = (Region)(event.getSource());
Dragboard db = region.startDragAndDrop(TransferMode.ANY);
Background regionBackground = region.getBackground();
Paint regionPaint = regionBackground.getFills().get(0).getFill();
if (regionPaint instanceof Color)
{
ClipboardContent content = new ClipboardContent();
content.put(colorFormat, new SerializableColor((Color)regionPaint));
db.setContent(content);
}
event.consume();
}
}

View File

@@ -1,6 +1,5 @@
package com.example.doubledeckerbus;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
@@ -12,23 +11,28 @@ 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.IOException;
import java.util.HashMap;
import java.util.Objects;
import java.util.Optional;
import java.io.*;
import java.util.*;
import org.apache.logging.log4j.Level;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
public class ControllerMapWithSetBus {
static MapWithSetBusesGeneric<DrawingObjectBus, AbstractMap> _mapBusesCollectionGeneric;
private HashMap<String, AbstractMap> _mapsDict = new HashMap<>();
private final HashMap<String, AbstractMap> _mapsDict = new HashMap<>();
{
_mapsDict.put("Простая карта", new SimpleMap());
_mapsDict.put("Водная карта", new WaterMap());
}
AbstractMap map = new SimpleMap();
private final Logger _logger = LogManager.getLogger(ControllerMapWithSetBus.class);
public static int AddNewBus (DrawingObjectBus bus) {
public static int AddNewBus (DrawingObjectBus bus) throws StorageOverflowException {
return _mapsCollection.GetId(selected).add(bus);
}
static public MapsCollection _mapsCollection;
@@ -39,32 +43,11 @@ public class ControllerMapWithSetBus {
protected ObservableList<String> countOfMap = FXCollections.observableArrayList("Простая карта", "Водная карта");
@FXML
private Button buttonAddBus;
@FXML
private Button buttonDown;
private Canvas canvasBus;
@FXML
private Button buttonLeft;
@FXML
private Button buttonRemoveCar;
@FXML
private Button buttonRight;
@FXML
private Button buttonShowMap;
@FXML
private Button buttonShowStorage;
@FXML
private Button buttonUp;
@FXML
private Canvas canvasBus;
@FXML
private ChoiceBox<String> comboBoxSelectorMap;
@@ -81,29 +64,31 @@ public class ControllerMapWithSetBus {
private TextField TextFieldMap;
@FXML
private void initialize(){
private void initialize() throws FileNotFoundException {
gc = canvasBus.getGraphicsContext2D();
if (selected != null) {
showStorage();
}
Properties prop = new Properties();
// InputStream = new FileInputStream("/home/user/IdeaProjects/PIbd-21_Zaharchenko_M.I._DoubleDeckerBus._Hard/DoubleDeckerBus/src/main/resources/com/example/doubledeckerbus/log4j2.xml");
Logger log = LogManager.getLogger(ControllerMapWithSetBus.class);
if (_mapsCollection == null)
_mapsCollection = new MapsCollection((int) canvasBus.getWidth(), (int) canvasBus.getHeight());
comboBoxSelectorMap.setItems(countOfMap);
comboBoxSelectorMap.setValue(map_name);
listViewMaps.getSelectionModel().selectedItemProperty()
.addListener(new ChangeListener<String>() {
@Override
public void changed(ObservableValue<? extends String> observableValue, String s, String t1) {
selected = t1;
showStorage();
}
.addListener((observableValue, s, t1) -> {
selected = t1;
_logger.info("Another Map has been chosen");
showStorage();
});
listViewMaps.setItems(_mapsCollection.toObserveList());
}
GraphicsContext gc;
private void FirstIncome() {
if (comboBoxSelectorMap.getValue() != map_name) {
if (!Objects.equals(comboBoxSelectorMap.getValue(), map_name)) {
map_name = comboBoxSelectorMap.getValue();
switch (map_name) {
case "Простая карта" -> map = new SimpleMap();
@@ -118,17 +103,14 @@ public class ControllerMapWithSetBus {
ObservableList<String> listMaps = FXCollections.observableArrayList();
for (int i = 0; i < _mapsCollection.Keys().size(); i++)
{
listMaps.add(_mapsCollection.Keys().get(i));
}
listMaps.addAll(_mapsCollection.Keys());
listViewMaps.setItems(listMaps);
if (listMaps.size() > 0 && (index == -1 || index >= listMaps.size()))
{
listViewMaps.getSelectionModel().select(0);
}
else if (listMaps.size() > 0 && index > -1 && index < listMaps.size())
else if (listMaps.size() > 0 && index > -1)
{
listViewMaps.getSelectionModel().select(index);
}
@@ -136,14 +118,53 @@ public class ControllerMapWithSetBus {
@FXML
private void ButtonAddBus_Click(ActionEvent event) throws IOException {
FXMLLoader fxmlLoader = new FXMLLoader(Form.class.getResource("FormBus.fxml"));
Scene scene = new Scene(fxmlLoader.load());
Form.myStage.setTitle("DoubleDeckerBus");
Form.myStage.setScene(scene);
Form.myStage.show();
if (listViewMaps.getSelectionModel().selectedItemProperty().isNull().get())
{
return;
}
Stage busStage = new Stage();
FXMLLoader fxmlLoader = new FXMLLoader(Form.class.getResource("FormBusConfig.fxml"));
Scene sceneBus = new Scene(fxmlLoader.load());
busStage.setScene(sceneBus);
busStage.show();
ControllerBusConfig controllerBusConfig = fxmlLoader.getController();
controllerBusConfig.AddEvent(this::AddBus);
controllerBusConfig.SetStage(busStage);
FirstIncome();
}
private void AddBus(DrawingBus bus) {
if (listViewMaps.getSelectionModel().selectedItemProperty().isNull().get())
{
return;
}
DrawingObjectBus objectBus = new DrawingObjectBus(bus);
String selectedMapName = listViewMaps.getSelectionModel().getSelectedItem();
Alert alert;
try {
if (selectedMapName != null && selectedMapName.length() != 0 && _mapsCollection.get(selectedMapName).add(objectBus) != -1)
{
alert = new Alert(Alert.AlertType.INFORMATION, "Объект добавлен", ButtonType.OK);
_mapsCollection.get(selectedMapName).ShowSet(gc);
_logger.info("Bus added");
}
else
{
alert = new Alert(Alert.AlertType.ERROR, "Не удалось добавить объект", ButtonType.OK);
_logger.warn("Bus not added");
}
} catch (StorageOverflowException e) {
_logger.warn("StorageOverFlow");
alert = new Alert(Alert.AlertType.ERROR, "Хранилище переполнено");
}
showStorage();
alert.showAndWait();
}
@FXML
private void ButtonAddMap_Click(ActionEvent event)
{
@@ -175,6 +196,7 @@ public class ControllerMapWithSetBus {
return;
}
_mapsCollection.DelMap(listViewMaps.getSelectionModel().getSelectedItem());
_logger.info("Map was deleted");
ReloadMaps();
showStorage();
}
@@ -185,7 +207,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"));
@@ -194,6 +216,7 @@ public class ControllerMapWithSetBus {
Form.myStage.setScene(scene);
Form.myStage.show();
}
_logger.info("Bus Edited");
}
@FXML
@@ -216,27 +239,42 @@ public class ControllerMapWithSetBus {
int pos;
try {
pos = Integer.parseInt(textBoxPosition.getText());
if (pos < 1 || pos > _mapsCollection.GetId(selected).getCount()) return;
}
catch (Exception e) {
return;
}
if (_mapsCollection.GetId(selected).remove(pos) != null)
{
alert = new Alert(Alert.AlertType.WARNING);
alert.setTitle("RemoveBus");
alert.setContentText("Вы удалили объект");
option = alert.showAndWait();
if (pos < 1 || pos > _mapsCollection.GetId(selected).getCount()) return;
if (_mapsCollection.GetId(selected).remove(pos) != null)
{
alert = new Alert(Alert.AlertType.WARNING);
alert.setTitle("RemoveBus");
alert.setContentText("Вы удалили объект");
option = alert.showAndWait();
_logger.info("Bus removed");
}
else
{
alert = new Alert(Alert.AlertType.WARNING);
alert.setTitle("RemoveBus");
alert.setContentText("Не удалось удалить объект");
option = alert.showAndWait();
}
showStorage();
}
else
{
catch (BusNotFoundException e) {
alert = new Alert(Alert.AlertType.WARNING);
alert.setTitle("RemoveBus");
alert.setContentText("Не удалось удалить объект");
option = alert.showAndWait();
_logger.warn("bus not found");
}
showStorage();
catch (Exception e) {
alert = new Alert(Alert.AlertType.WARNING);
alert.setTitle("RemoveBus");
alert.setContentText("Не удалось удалить объект");
option = alert.showAndWait();
_logger.warn("strange error");
}
}
@FXML
@@ -244,10 +282,11 @@ public class ControllerMapWithSetBus {
{
FirstIncome();
showStorage();
_logger.info("show storage");
}
@FXML
private void ButtonShowOnMap_Click(ActionEvent event) {
private void ButtonShowOnMap_Click(ActionEvent event) throws StorageOverflowException, BusNotFoundException {
FirstIncome();
if (selected == null) {
return;
@@ -255,6 +294,7 @@ public class ControllerMapWithSetBus {
gc.setFill(Color.WHITE);
gc.fillRect(0, 0, canvasBus.getWidth(), canvasBus.getHeight());
_mapsCollection.GetId(selected).ShowOnMap(gc);
_logger.info("show on map");
}
@FXML
@@ -274,6 +314,105 @@ public class ControllerMapWithSetBus {
case "buttonRight" -> dir = Direction.Right;
}
_mapsCollection.GetId(selected).MoveObject(dir);
_logger.info("Button move click");
}
@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)
{
try {
String filepath = selectedDirectory.getPath();
_mapsCollection.SaveData(filepath);
infoAlert = new Alert(Alert.AlertType.INFORMATION, "Save was successful", ButtonType.OK);
_logger.info("Save was successful");
}
catch (Exception e) {
infoAlert = new Alert(Alert.AlertType.INFORMATION, "Exception " + e.getMessage(), ButtonType.OK);
_logger.warn("Save wasnt successful");
}
}
else
{
infoAlert = new Alert(Alert.AlertType.INFORMATION, "The file was not saved", ButtonType.OK);
_logger.info("Not saved");
}
infoAlert.showAndWait();
}
@FXML
private void ButtonLoad_Click(ActionEvent event) throws IOException, StorageOverflowException {
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)
{
try {
String filepath = selectedDirectory.getPath();
_mapsCollection.LoadData(filepath);
infoAlert = new Alert(Alert.AlertType.INFORMATION, "Load was successful", ButtonType.OK);
_logger.info("Load was successful");
ReloadMaps();
} catch (Exception e) {
infoAlert = new Alert(Alert.AlertType.ERROR, "StrangeException: " + e.getMessage(), ButtonType.OK);
_logger.warn("StrangeException");
}
}
else
{
infoAlert = new Alert(Alert.AlertType.INFORMATION, "The file was not loaded", ButtonType.OK);
_logger.info("The file was not loaded");
}
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)
{
try {
String filepath = selectedDirectory.getPath();
_mapsCollection.SaveStorage(filepath, listViewMaps.getSelectionModel().getSelectedItem());
infoAlert = new Alert(Alert.AlertType.INFORMATION, "Save was successful", ButtonType.OK);
_logger.info("Save storage was successful");
}
catch (Exception e) {
infoAlert = new Alert(Alert.AlertType.INFORMATION, "Exseption " + e.getMessage() , ButtonType.OK);
_logger.warn("Save storage wasnt successful");
}
}
else
{
infoAlert = new Alert(Alert.AlertType.INFORMATION, "The file was not saved", ButtonType.OK);
_logger.info("Save storage wasnt successful");
}
infoAlert.showAndWait();
}
private void showStorage() {
@@ -284,8 +423,10 @@ public class ControllerMapWithSetBus {
gc.setFill(Color.WHITE);
gc.fillRect(0, 0, pictureBoxBus.getWidth(), pictureBoxBus.getHeight());
_mapsCollection.GetId(selected).ShowSet(gc);
_logger.info("showStorage");
}
}

View File

@@ -129,7 +129,7 @@ public class ControllerPolymorph {
BorderChanged();
}
@FXML
private void ButtonSelectBus_Click(ActionEvent event) throws IOException {
private void ButtonSelectBus_Click(ActionEvent event) throws IOException, StorageOverflowException {
SelectedBus = _bus;
if (SelectedBus == null) {

View File

@@ -9,10 +9,10 @@ public class DrawingBus {
public EntityBus Bus;
public IDrawingDoors Doors;
public EntityBus getBus() {
return Bus;
}
int _speed;
float _weight;
Color _bodyColor;
int _countOfDoors = 3;
private static final int _null = -1000;
protected float _startPosX;
@@ -23,15 +23,42 @@ public class DrawingBus {
private static final int _busHeight = 50;
public DrawingBus(int speed, float weight, Color bodyColor, int countOfDoors) {
Bus = new EntityBus(speed, weight, bodyColor);
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;
_bodyColor = bodyColor;
_countOfDoors = countOfDoors;
EntityBus bus = new EntityBus(speed, weight, bodyColor);
switch (new Random().nextInt(3)) {
case 0 -> Doors = new DrawingTriangleDoors();
case 1 -> Doors = new DrawingDoors();
case 2 -> Doors = new DrawingEllipsoidDoors();
}
Doors.setCountOfDoors(countOfDoors);
return bus;
}
public void ChangeDoor(IDrawingDoors door) {
Doors = door;
Doors.setCountOfDoors(_countOfDoors);
}
public DrawingBus(int speed, float weight, Color bodyColor) {
Bus = new EntityBus(speed, weight, bodyColor);
}

View File

@@ -4,9 +4,32 @@ import javafx.scene.canvas.GraphicsContext;
import javafx.scene.paint.Color;
public class DrawingDDB extends DrawingBus{
public DrawingDDB(int speed, float weight, Color bodyColor, int countOfDoors, Color extraColor, boolean ladder, boolean secondStage) {
Color _extraColor;
boolean _ladder;
boolean _secondStage;
public DrawingDDB(int speed, float weight, Color bodyColor, int countOfDoors,
Color extraColor, boolean ladder, boolean secondStage) {
super(speed, weight, bodyColor, countOfDoors);
Bus = new EntityDDB(speed, weight, bodyColor, extraColor, ladder, secondStage);
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;
_weight = weight;
_bodyColor = bodyColor;
_countOfDoors = countOfDoors;
_extraColor = extraColor;
_ladder = ladder;
_secondStage = secondStage;
return new EntityDDB(speed, weight, bodyColor, extraColor, ladder, secondStage);
}
public DrawingDDB(int speed, float weight, Color bodyColor, Color extraColor, boolean ladder, boolean secondStage) {

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,17 @@
package com.example.doubledeckerbus;
import java.util.HashSet;
import java.util.Set;
import java.util.function.Consumer;
public class Event<T> {
private final Set<Consumer<T>> listeners = new HashSet<>();
public void AddListener(Consumer<T> listener) {
listeners.add(listener);
}
public void Broadcast(T args) {
listeners.forEach(x -> x.accept(args));
}
}

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

@@ -29,13 +29,11 @@ public class MapWithSetBusesGeneric<T extends IDrawingObject, U extends Abstract
_map = map;
}
public int add(T bus)
{
public int add(T bus) throws StorageOverflowException {
return _setBuses.Insert(bus);
}
public T remove(int position)
{
public T remove(int position) throws BusNotFoundException {
T deletedBus = _setBuses.Remove(position);
_deletedBuses.push(deletedBus);
return deletedBus;
@@ -53,8 +51,7 @@ public class MapWithSetBusesGeneric<T extends IDrawingObject, U extends Abstract
DrawBuses(gc);
}
public void ShowOnMap(GraphicsContext gc)
{
public void ShowOnMap(GraphicsContext gc) throws StorageOverflowException, BusNotFoundException {
Shaking();
for (var bus: _setBuses.GetBuses())
{
@@ -74,8 +71,7 @@ public class MapWithSetBusesGeneric<T extends IDrawingObject, U extends Abstract
}
}
private void Shaking()
{
private void Shaking() throws StorageOverflowException, BusNotFoundException {
int j = _setBuses.Count() - 1;
for (int i = 0; i < _setBuses.Count(); i++)
{
@@ -144,8 +140,35 @@ public class MapWithSetBusesGeneric<T extends IDrawingObject, U extends Abstract
return _setBuses.Count();
}
public T getBus(int ind){
public T getBus(int ind) throws BusNotFoundException {
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) throws StorageOverflowException {
for (String items : data)
{
_setBuses.Insert((T)(DrawingObjectBus.Create(items)));
}
}
@SuppressWarnings("unchecked")
public void LoadData(String data) throws StorageOverflowException {
_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) throws BusNotFoundException {
if (_mapStorages.containsKey(name))
{
return _mapStorages.get(name).getBus(id);
@@ -62,4 +68,111 @@ 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")) {
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();
}
}
else {
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;
};
_mapStorages.put(elem[0], new MapWithSetBusesGeneric<>(_pictureWidth, _pictureHeight, map));
if (elem.length == 3) {
_mapStorages.get(elem[0]).LoadData(elem[2].split(String.format("%c", separatorData)));
}
}
}
} catch (StorageOverflowException e) {
throw new RuntimeException(e);
}
return true;
}
}

View File

@@ -0,0 +1,26 @@
package com.example.doubledeckerbus;
import java.io.Serializable;
import javafx.scene.paint.Color;
public class SerializableColor implements Serializable
{
private final double red;
private final double green;
private final double blue;
private final double alpha;
public SerializableColor(Color color)
{
red = color.getRed();
green = color.getGreen();
blue = color.getBlue();
alpha = color.getOpacity();
}
public Color getFXColor()
{
return new Color(red, green, blue, alpha);
}
}

View File

@@ -17,13 +17,16 @@ class SetBusesGeneric<T> {
_places = new ArrayList<>();
}
public int Insert(T bus)
{
public int Insert(T bus) throws StorageOverflowException {
return Insert(bus, 0);
}
public int Insert(T bus, int position)
{
public int Insert(T bus, int position) throws StorageOverflowException {
if (_places.size() == _maxCount)
{
throw new StorageOverflowException(_places.size());
}
if (position < 0 || position >= _maxCount || BusyPlaces == _maxCount) return -1;
BusyPlaces++;
@@ -31,17 +34,20 @@ class SetBusesGeneric<T> {
return position;
}
public T Remove(int position)
{
if (position < 0 || position >= _maxCount) return null;
public T Remove(int position) throws BusNotFoundException {
if (position < 0 || position >= _maxCount)
throw new BusNotFoundException();
T savedBus = _places.get(position - 1);
if (savedBus == null) {
throw new BusNotFoundException();
}
_places.set(position - 1, null);
return savedBus;
}
public T Get(int position)
{
if (position < 0 || position >= _maxCount) return null;
public T Get(int position) throws BusNotFoundException {
if (position < 0 || position >= _maxCount)
throw new BusNotFoundException();
return _places.get(position);
}
@@ -55,9 +61,14 @@ class SetBusesGeneric<T> {
}
return result;
}
public int Count() {
return _places.size();
}
public void Clear() {
_places.clear();
}
}

View File

@@ -0,0 +1,25 @@
package com.example.doubledeckerbus;
public class StorageOverflowException extends Exception
{
public StorageOverflowException(int count)
{
super("The set exceeded the allowed number of elements: " + count);
}
public StorageOverflowException()
{
super();
}
public StorageOverflowException(String message)
{
super(message);
}
public StorageOverflowException(String message, Throwable cause)
{
super(message, cause);
}
public StorageOverflowException(Throwable cause)
{
super(cause);
}
}

View File

@@ -5,6 +5,8 @@ module com.example.doubledeckerbus {
requires org.controlsfx.controls;
requires org.kordamp.bootstrapfx.core;
requires javafx.graphics;
requires org.apache.logging.log4j;
requires org.apache.log4j;
opens com.example.doubledeckerbus to javafx.fxml;
exports com.example.doubledeckerbus;

View File

@@ -0,0 +1,76 @@
<?xml version="1.0" encoding="UTF-8"?>
<?import javafx.scene.canvas.Canvas?>
<?import javafx.scene.control.Button?>
<?import javafx.scene.control.CheckBox?>
<?import javafx.scene.control.Label?>
<?import javafx.scene.control.Spinner?>
<?import javafx.scene.control.SpinnerValueFactory.IntegerSpinnerValueFactory?>
<?import javafx.scene.layout.Pane?>
<?import javafx.scene.layout.Region?>
<?import javafx.scene.layout.StackPane?>
<Pane fx:id="root" prefHeight="395.0" prefWidth="642.0" xmlns="http://javafx.com/javafx/18" xmlns:fx="http://javafx.com/fxml/1" fx:controller="com.example.doubledeckerbus.ControllerBusConfig">
<Pane layoutX="5.0" layoutY="5.0" prefHeight="379.0" prefWidth="307">
<Label layoutX="18.0" layoutY="18.0" text="Скорость">
Speed:
</Label>
<Label layoutX="181.0" layoutY="18.0" text="Вес:">
Weight:
</Label>
<Spinner fx:id="spinnerSpeed" layoutX="90.0" layoutY="14.0" prefWidth="70">
<valueFactory>
<SpinnerValueFactory.IntegerSpinnerValueFactory initialValue="100" max="300" min="100" />
</valueFactory>
</Spinner>
<Spinner fx:id="spinnerWeight" layoutX="222.0" layoutY="14.0" prefWidth="70">
<valueFactory>
<SpinnerValueFactory.IntegerSpinnerValueFactory initialValue="100" max="2000" min="1000" />
</valueFactory>
</Spinner>
<Pane layoutX="12.0" layoutY="131.0" prefHeight="126.0" prefWidth="280.0">
<Region layoutX="25.0" layoutY="9.0" onDragDetected="#RegionColor_OnDragDetected" prefHeight="46.0" prefWidth="46.0" style="-fx-background-color: orangered;" />
<Region layoutX="79.0" layoutY="9.0" onDragDetected="#RegionColor_OnDragDetected" prefHeight="46.0" prefWidth="46.0" style="-fx-background-color: yellowgreen;" />
<Region layoutX="140.0" layoutY="9.0" onDragDetected="#RegionColor_OnDragDetected" prefHeight="46.0" prefWidth="46.0" style="-fx-background-color: cornflowerblue;" />
<Region layoutX="197.0" layoutY="9.0" onDragDetected="#RegionColor_OnDragDetected" prefHeight="46.0" prefWidth="46.0" style="-fx-background-color: yellow;" />
<Region layoutX="25.0" layoutY="66.0" onDragDetected="#RegionColor_OnDragDetected" prefHeight="46.0" prefWidth="46.0" style="-fx-background-color: white;" />
<Region layoutX="79.0" layoutY="66.0" onDragDetected="#RegionColor_OnDragDetected" prefHeight="46.0" prefWidth="46.0" style="-fx-background-color: gray;" />
<Region layoutX="140.0" layoutY="66.0" onDragDetected="#RegionColor_OnDragDetected" prefHeight="46.0" prefWidth="46.0" style="-fx-background-color: black;" />
<Region layoutX="197.0" layoutY="66.0" onDragDetected="#RegionColor_OnDragDetected" prefHeight="46.0" prefWidth="46.0" style="-fx-background-color: purple;" />
</Pane>
<CheckBox fx:id="checkBoxLadder" layoutX="188.0" layoutY="110.0" text="Второй этаж" />
<CheckBox fx:id="checkBoxSecondStage" layoutX="8" layoutY="110" prefHeight="18.0" prefWidth="135.0" text="Лестница" />
<Label fx:id="labelSimpleObject" alignment="CENTER" layoutX="14.0" layoutY="282.0" onDragDetected="#LabelObject_OnDragDetected" prefHeight="30" prefWidth="127.0" style="-fx-border-color: black;" textOverrun="CLIP">
Simple
</Label>
<Label fx:id="labelModifiedObject" alignment="CENTER" layoutX="165.0" layoutY="282.0" onDragDetected="#LabelObject_OnDragDetected" prefHeight="30" prefWidth="135.0" style="-fx-border-color: black;">
Modified
</Label>
<Label layoutX="101.0" layoutY="56.0" text="Двери">
Track rollers
</Label>
<Spinner fx:id="spinnerDoors" layoutX="150.0" layoutY="52.0" prefWidth="70">
<valueFactory>
<SpinnerValueFactory.IntegerSpinnerValueFactory initialValue="1" max="5" min="3" />
</valueFactory>
</Spinner>
<Label fx:id="labelTriangle" alignment="CENTER" layoutX="14.0" layoutY="331.0" onDragDetected="#LabelObject_OnDragDetected" prefHeight="30" prefWidth="97.0" style="-fx-border-color: black;" text="Треугольник" textOverrun="CLIP" />
<Label fx:id="labelOval" alignment="CENTER" layoutX="128.0" layoutY="331.0" onDragDetected="#LabelObject_OnDragDetected" prefHeight="30" prefWidth="52.0" style="-fx-border-color: black;" text="Овал" textOverrun="CLIP" />
<Label fx:id="labelRect" alignment="CENTER" layoutX="199.0" layoutY="331.0" onDragDetected="#LabelObject_OnDragDetected" prefHeight="30" prefWidth="90.0" style="-fx-border-color: black;" text="Квадрат" textOverrun="CLIP" />
</Pane>
<Label alignment="CENTER" layoutX="356.0" layoutY="52.0" onDragDropped="#LabelBaseColor_OnDragDropped" onDragOver="#LabelColor_OnDragOver" prefHeight="30" prefWidth="127.0" style="-fx-border-color: black;" text="Цвет">
Color
</Label>
<Label alignment="CENTER" layoutX="499.0" layoutY="52.0" onDragDropped="#LabelDopColor_OnDragDropped" onDragOver="#LabelColor_OnDragOver" prefHeight="30" prefWidth="119.0" style="-fx-border-color: black;" text="Доп цвет">
Dop Color
</Label>
<StackPane layoutX="352.0" layoutY="137.0" onDragDropped="#CanvasObject_OnDragDropped" onDragOver="#CanvasObject_OnDragOver" prefHeight="152.0" prefWidth="262.0" style="-fx-border-color: #b8becc; -fx-border-radius: 5; -fx-border-width: 2;">
<Canvas fx:id="canvasObject" height="152.0" width="267.0" />
</StackPane>
<Button fx:id="buttonAdd" layoutX="367.0" layoutY="350.0" onAction="#ButtonOk_Click" prefHeight="26" prefWidth="90" text="Создать">
Add
</Button>
<Button fx:id="buttonCancel" layoutX="522.0" layoutY="350.0" prefHeight="26" prefWidth="90" text="Отмена">
Cancel
</Button>
</Pane>

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" />

View File

@@ -0,0 +1,19 @@
<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="INFO">
<Appenders>
<File name="InfoFile" fileName="info.log" immediateFlush="false" append="true">
<PatternLayout pattern="[%-4level]: %msg (date-%d{yyy.MM.dd})%n"/>
<LevelRangeFilter minLevel="INFO" maxLevel="INFO" onMatch="ACCEPT" onMismatch="DENY"/>
</File>
<File name="WarnErrorFatalFile" fileName="warn.log" immediateFlush="false" append="true">
<PatternLayout pattern="[%.5level]: %msg (date-%d{yyy.MM.dd})%n"/>
<LevelRangeFilter minLevel="FATAL" maxLevel="WARN" onMatch="ACCEPT" onMismatch="DENY"/>
</File>
</Appenders>
<Loggers>
<Root level="debug">
<AppenderRef ref="InfoFile" level="info"/>
<AppenderRef ref="WarnErrorFatalFile" level="warn"/>
</Root>
</Loggers>
</Configuration>