lab 4 done

This commit is contained in:
ZakenChannel 2024-04-19 12:12:51 +04:00
parent 1da5f03ecc
commit 2596f35e5c
6 changed files with 390 additions and 44 deletions

View File

@ -7,6 +7,7 @@ import javafx.application.Application;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.fxml.Initializable;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.canvas.Canvas;
@ -17,8 +18,10 @@ import javafx.scene.input.KeyEvent;
import javafx.stage.Stage;
import java.io.IOException;
import java.net.URL;
import java.util.ResourceBundle;
public class FormAirFighter extends Application {
public class FormAirFighter extends Application implements Initializable {
private AbstractStrategy strategy;
private DrawningWarPlane drawningWarPlane;
@ -106,7 +109,6 @@ public class FormAirFighter extends Application {
Parent root = loader.load();
canvasAirFighter = (Canvas) loader.getNamespace().get("canvasAirFighter");
comboBoxStrategy = (ComboBox<String>) loader.getNamespace().get("comboBoxStrategy");
initComboBox();
strategy = null;
Scene scene = new Scene(root, 800, 400);
@ -115,11 +117,12 @@ public class FormAirFighter extends Application {
primaryStage.show();
}
public void initComboBox() {
comboBoxStrategy.getItems().addAll("К центру", "К краю");
}
public static void main(String[] args) {
launch(args);
}
@Override
public void initialize(URL url, ResourceBundle resourceBundle) {
comboBoxStrategy.getItems().addAll("К центру", "К краю");
}
}

View File

@ -1,14 +1,13 @@
package com.projectairfighter;
import com.projectairfighter.collectiongenericobjects.AbstractCompany;
import com.projectairfighter.collectiongenericobjects.Hangar;
import com.projectairfighter.collectiongenericobjects.MassiveGenericObjects;
import com.projectairfighter.collectiongenericobjects.*;
import com.projectairfighter.drawnings.DrawningAirFighter;
import com.projectairfighter.drawnings.DrawningWarPlane;
import javafx.application.Application;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.fxml.Initializable;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.Parent;
@ -21,9 +20,16 @@ import javafx.scene.paint.Color;
import javafx.stage.Stage;
import java.io.IOException;
import java.net.URL;
import java.util.Random;
import java.util.ResourceBundle;
import java.util.Stack;
public class FormWarPlaneCollection extends Application implements Initializable {
private StorageCollection<DrawningWarPlane> storageCollection;
private Stack<DrawningWarPlane> removedPlanesStack;
public class FormWarPlaneCollection extends Application {
private AbstractCompany company;
// Окно отрисовки
@ -36,6 +42,21 @@ public class FormWarPlaneCollection extends Application {
@FXML
private TextField textBox;
@FXML
private SplitPane splitPane;
@FXML
private TextField textFieldCollectionName;
@FXML
private RadioButton radioButtonMassive;
@FXML
private RadioButton radioButtonList;
@FXML
private ListView<String> listViewCollection;
private static FormWarPlaneCollection formWarPlaneCollection;
public static void setFormWarPlaneCollection(FormWarPlaneCollection controller) {
@ -46,14 +67,15 @@ public class FormWarPlaneCollection extends Application {
return formWarPlaneCollection;
}
@Override
public void initialize(URL location, ResourceBundle resources) {
storageCollection = new StorageCollection<>();
removedPlanesStack = new Stack<>();
}
@FXML
private void comboBoxSelectorCompany(ActionEvent event) {
String selectedCompany = comboBox.getValue();
switch (selectedCompany) {
case "Хранилище":
company = new Hangar((int) canvasWarPlane.getWidth(), (int) canvasWarPlane.getHeight(), new MassiveGenericObjects<>());
break;
}
splitPane.getItems().get(1).setDisable(true);
}
private void createObject(String type) {
@ -108,6 +130,7 @@ public class FormWarPlaneCollection extends Application {
int pos = Integer.parseInt(text);
DrawningWarPlane removedPlane = company.removePlane(pos);
if (removedPlane != null) {
removedPlanesStack.push(removedPlane);
showAlert("Объект удален");
company.show(canvasWarPlane);
} else {
@ -118,7 +141,7 @@ public class FormWarPlaneCollection extends Application {
}
@FXML
private void buttonRefresh(ActionEvent event){
private void buttonRefresh(ActionEvent event) {
if (company == null) return;
company.show(canvasWarPlane);
@ -148,7 +171,7 @@ public class FormWarPlaneCollection extends Application {
}
@FXML
private void buttonGoToCheck(ActionEvent event){
private void buttonGoToCheck(ActionEvent event) {
if (company == null) return;
DrawningWarPlane warPlane = null;
@ -163,22 +186,11 @@ public class FormWarPlaneCollection extends Application {
if (warPlane == null) return;
try {
FXMLLoader loader = new FXMLLoader(getClass().getResource("FormAirFighter.fxml"));
Parent root = loader.load();
FormAirFighter controller = loader.getController();
controller.setWarPlane(warPlane);
controller.initComboBox();
Stage stage = new Stage();
stage.setScene(new Scene(root));
stage.showAndWait();
} catch (IOException e) {
e.printStackTrace();
}
goToFormAirFighter(warPlane);
}
@FXML
private void buttonGoFormInfo(ActionEvent event){
private void buttonGoFormConstructor(ActionEvent event) {
if (company == null) return;
try {
@ -189,13 +201,112 @@ public class FormWarPlaneCollection extends Application {
stage.setScene(new Scene(root));
controller.start(stage);
FormWarPlaneCollection.setFormWarPlaneCollection(this);
stage.show();
} catch (IOException e) {
e.printStackTrace();
}
}
@FXML
private void buttonGoToFormWithDeleteObject(ActionEvent event){
if (!removedPlanesStack.isEmpty()) {
goToFormAirFighter(removedPlanesStack.get(new Random().nextInt(0, removedPlanesStack.size())));
} else {
showAlert("Стек удаленных объектов пуст.");
}
}
private void goToFormAirFighter(DrawningWarPlane plane){
try {
FXMLLoader loader = new FXMLLoader(getClass().getResource("FormAirFighter.fxml"));
Parent root = loader.load();
FormAirFighter controller = loader.getController();
controller.setWarPlane(plane);
Stage stage = new Stage();
stage.setScene(new Scene(root));
stage.showAndWait();
} catch (IOException e) {
e.printStackTrace();
}
}
@FXML
void ButtonCollectionAdd(ActionEvent event) {
if (textFieldCollectionName.getText().isEmpty() || (!radioButtonList.isSelected() && !radioButtonMassive.isSelected())) {
showError("Не все данные заполнены");
return;
}
CollectionType collectionType = CollectionType.None;
if (radioButtonMassive.isSelected()) {
collectionType = CollectionType.Massive;
} else if (radioButtonList.isSelected()) {
collectionType = CollectionType.List;
}
storageCollection.addCollection(textFieldCollectionName.getText(), collectionType);
refreshListBoxItems();
}
@FXML
void ButtonCollectionDel(ActionEvent event) {
if (listViewCollection.getSelectionModel().getSelectedIndex() < 0 || listViewCollection.getSelectionModel().getSelectedItem() == null) {
showError("Коллекция не выбрана");
return;
}
Alert confirmDialog = new Alert(Alert.AlertType.CONFIRMATION);
confirmDialog.setTitle("Удаление");
confirmDialog.setHeaderText(null);
confirmDialog.setContentText("Удалить коллекцию?");
if (confirmDialog.showAndWait().orElse(ButtonType.CANCEL) != ButtonType.OK) {
return;
}
storageCollection.delCollection(listViewCollection.getSelectionModel().getSelectedItem());
refreshListBoxItems();
}
private void refreshListBoxItems() {
listViewCollection.getItems().clear();
for (String colName : storageCollection.Keys()) {
if (colName != null && !colName.isEmpty()) {
listViewCollection.getItems().add(colName);
}
}
}
@FXML
void ButtonCreateCompany(ActionEvent event) {
if (listViewCollection.getSelectionModel().getSelectedIndex() < 0 || listViewCollection.getSelectionModel().getSelectedItem() == null) {
showAlert("Коллекция не выбрана");
return;
}
ICollectionGenericObjects<DrawningWarPlane> collection = storageCollection.get(listViewCollection.getSelectionModel().getSelectedItem());
if (collection == null) {
showAlert("Коллекция не проинициализирована");
return;
}
String selectedCompany = comboBox.getValue();
if (comboBox.getValue() == null) {
showError("Не выбрано хранилище");
return;
}
switch (selectedCompany) {
case "Хранилище":
company = new Hangar((int) canvasWarPlane.getWidth(), (int) canvasWarPlane.getHeight(), collection);
break;
}
splitPane.getItems().get(1).setDisable(false);
refreshListBoxItems();
}
private void showAlert(String message) {
Alert alert = new Alert(Alert.AlertType.INFORMATION);
alert.setTitle("Сообщение");
@ -204,6 +315,15 @@ public class FormWarPlaneCollection extends Application {
alert.showAndWait();
}
private void showError(String message) {
Alert alert = new Alert(Alert.AlertType.INFORMATION);
alert.setTitle("Ошибка");
alert.setHeaderText(null);
alert.setContentText(message);
alert.showAndWait();
}
// Создание объекта
@FXML
private void createAiFighter(ActionEvent event) {
@ -225,7 +345,7 @@ public class FormWarPlaneCollection extends Application {
canvasWarPlane = (Canvas) loader.getNamespace().get("canvasWarPlane");
comboBox = (ComboBox<String>) loader.getNamespace().get("comboBox");
comboBox.getItems().addAll("Хранилище");
Scene scene = new Scene(root, 1250, 700);
Scene scene = new Scene(root, 1292, 765);
primaryStage.setTitle("Истребитель");
primaryStage.setScene(scene);
primaryStage.show();

View File

@ -0,0 +1,19 @@
package com.projectairfighter.collectiongenericobjects;
public enum CollectionType {
/**
Неопределно
*/
None,
/**
Массив
*/
Massive,
/**
Список
*/
List
}

View File

@ -0,0 +1,63 @@
package com.projectairfighter.collectiongenericobjects;
import java.util.ArrayList;
import java.util.List;
public class ListGenericObjects<T> implements ICollectionGenericObjects<T> {
private final List<T> collection;
private int maxCount;
@Override
public int getCount() {
return collection.size();
}
@Override
public void setMaxCount(int value) {
if (value > 0) {
maxCount = value;
}
}
public ListGenericObjects() {
collection = new ArrayList<>();
}
@Override
public T get(int position) {
if (position >= 0 && position < getCount()) {
return collection.get(position);
} else {
return null;
}
}
@Override
public int insert(T obj) {
if (getCount() == maxCount) {
return -1;
}
collection.add(obj);
return getCount();
}
@Override
public int insert(T obj, int position) {
if (position < 0 || position >= getCount() || getCount() == maxCount) {
return -1;
}
collection.add(position, obj);
return position;
}
@Override
public T remove(int position) {
if (position >= getCount() || position < 0) {
return null;
}
T obj = collection.get(position);
collection.remove(position);
return obj;
}
}

View File

@ -0,0 +1,89 @@
package com.projectairfighter.collectiongenericobjects;
import java.util.*;
/**
* Класс-хранилище коллекций.
*
* @param <T> Тип элементов коллекций.
*/
public class StorageCollection<T> {
/**
* Словарь (хранилище) с коллекциями.
*/
private final Map<String, ICollectionGenericObjects<T>> storages;
/**
* Возвращение списка названий коллекций.
*
* @return Список названий коллекций.
*/
public List<String> Keys() {
return new ArrayList<>(storages.keySet());
}
/**
* Конструктор.
*/
public StorageCollection() {
storages = new HashMap<>();
}
/**
* Добавление коллекции в хранилище.
*
* @param name Название коллекции.
* @param collectionType Тип коллекции.
*/
public void addCollection(String name, CollectionType collectionType) {
if (name == null || storages.containsKey(name)) {
return;
}
switch (collectionType) {
case None:
return;
case Massive:
storages.put(name, new MassiveGenericObjects<>());
return;
case List:
storages.put(name, new ListGenericObjects<>());
return;
}
}
/**
* Удаление коллекции из хранилища.
*
* @param name Название коллекции.
*/
public void delCollection(String name) {
if (name == null || !storages.containsKey(name)) {
return;
}
storages.remove(name);
}
/**
* Доступ к коллекции по её названию.
*
* @param name Название коллекции.
* @return Коллекция или null, если коллекция с данным названием отсутствует.
*/
public ICollectionGenericObjects<T> get(String name) {
if (name == null || !storages.containsKey(name)) {
return null;
}
return storages.get(name);
}
/**
* Доступ к элементу коллекции по названию коллекции и индексу элемента.
*
* @param name Название коллекции.
* @param index Индекс элемента в коллекции.
* @return Элемент коллекции или null, если коллекция с данным названием отсутствует или индекс некорректен.
*/
public T getElement(String name, int index) {
return this.get(name).get(index);
}
}

View File

@ -5,19 +5,71 @@
<?import javafx.scene.layout.*?>
<?import javafx.scene.text.*?>
<SplitPane dividerPositions="0.8076923076923077" maxHeight="-Infinity" maxWidth="-Infinity" minHeight="-Infinity" minWidth="-Infinity" prefHeight="700.0" prefWidth="1250.0" xmlns="http://javafx.com/javafx/17.0.2-ea" xmlns:fx="http://javafx.com/fxml/1" fx:controller="com.projectairfighter.FormWarPlaneCollection">
<SplitPane dividerPositions="0.811965811965812" maxHeight="-Infinity" maxWidth="-Infinity" minHeight="-Infinity" minWidth="-Infinity" prefHeight="765.0" prefWidth="1292.0" xmlns="http://javafx.com/javafx/17.0.2-ea" xmlns:fx="http://javafx.com/fxml/1" fx:controller="com.projectairfighter.FormWarPlaneCollection">
<AnchorPane minHeight="0.0" minWidth="0.0" prefHeight="698.0" prefWidth="965.0">
<Canvas fx:id="canvasWarPlane" height="700.0" width="1005.0" />
<Canvas fx:id="canvasWarPlane" height="763.0" width="1044.0" />
</AnchorPane>
<AnchorPane minHeight="0.0" minWidth="0.0" prefHeight="160.0" prefWidth="196.0">
<ComboBox fx:id="comboBox" layoutX="6.0" layoutY="26.0" onAction="#comboBoxSelectorCompany" prefHeight="25.0" prefWidth="224.0" />
<Button alignment="CENTER" contentDisplay="CENTER" layoutX="6.0" layoutY="75.0" mnemonicParsing="false" onAction="#createAiFighter" prefHeight="42.0" prefWidth="224.0" text="Добавление истребителя" />
<Button alignment="CENTER" contentDisplay="CENTER" layoutX="7.0" layoutY="140.0" mnemonicParsing="false" onAction="#createWarPlane" prefHeight="45.0" prefWidth="224.0" text="Добавление военного самолета" />
<TextField fx:id="textBox" layoutX="5.0" layoutY="261.0" prefHeight="25.0" prefWidth="224.0" />
<Button alignment="CENTER" contentDisplay="CENTER" layoutX="6.0" layoutY="295.0" mnemonicParsing="false" onAction="#buttonRemovePlaneClicked" prefHeight="42.0" prefWidth="224.0" text="Удалить истребитель" />
<Button alignment="CENTER" contentDisplay="CENTER" layoutX="8.0" layoutY="407.0" mnemonicParsing="false" onAction="#buttonGoToCheck" prefHeight="42.0" prefWidth="224.0" text="Передать на тесты" />
<Button alignment="CENTER" contentDisplay="CENTER" layoutX="8.0" layoutY="642.0" mnemonicParsing="false" onAction="#buttonRefresh" prefHeight="42.0" prefWidth="224.0" text="Обновить" />
<Text layoutX="14.0" layoutY="19.0" strokeType="OUTSIDE" strokeWidth="0.0" text="Инструменты" AnchorPane.leftAnchor="14.0" AnchorPane.topAnchor="6.0" />
<Button alignment="CENTER" contentDisplay="CENTER" layoutX="8.0" layoutY="531.0" mnemonicParsing="false" onAction="#buttonGoFormInfo" prefHeight="42.0" prefWidth="224.0" text="Добавить через конструктор" />
<SplitPane dividerPositions="0.43889618922470436" orientation="VERTICAL" prefHeight="763.0" prefWidth="237.0">
<AnchorPane minHeight="0.0" minWidth="0.0" prefHeight="100.0" prefWidth="160.0">
<Text strokeType="OUTSIDE" strokeWidth="0.0" text="Инструменты" AnchorPane.leftAnchor="14.0"
AnchorPane.topAnchor="6.0"/>
<TextField fx:id="textFieldCollectionName" layoutX="6.0" layoutY="49.0" prefHeight="25.0"
prefWidth="224.0"/>
<RadioButton fx:id="radioButtonMassive" layoutX="25.0" layoutY="77.0" mnemonicParsing="false"
text="Массив">
<toggleGroup>
<ToggleGroup fx:id="toggle"/>
</toggleGroup>
</RadioButton>
<RadioButton fx:id="radioButtonList" layoutX="141.0" layoutY="77.0" mnemonicParsing="false"
text="Список" toggleGroup="$toggle"/>
<Button layoutX="6.0" layoutY="101.0" mnemonicParsing="false" onAction="#ButtonCollectionAdd"
prefHeight="25.0" prefWidth="224.0" text="Добавить в коллекцию"/>
<Button layoutX="6.0" layoutY="299.0" mnemonicParsing="false" onAction="#ButtonCollectionDel"
prefHeight="25.0" prefWidth="224.0" text="Удалить коллекцию"/>
<ListView fx:id="listViewCollection" layoutX="6.0" layoutY="136.0" prefHeight="155.0"
prefWidth="224.0"/>
<Label layoutX="56.0" layoutY="26.0" text="Название коллекции"/>
</AnchorPane>
<AnchorPane minHeight="0.0" minWidth="0.0" prefHeight="100.0" prefWidth="160.0">
<SplitPane fx:id="splitPane" dividerPositions="0.18691588785046728" layoutY="-8.0"
orientation="VERTICAL" prefHeight="430.0" prefWidth="237.0">
<AnchorPane minHeight="0.0" minWidth="0.0" prefHeight="116.0" prefWidth="235.0">
<ComboBox fx:id="comboBox" layoutX="6.0" layoutY="15.0"
onAction="#comboBoxSelectorCompany" prefHeight="25.0" prefWidth="224.0"/>
<Button layoutX="6.0" layoutY="46.0" mnemonicParsing="false"
onAction="#ButtonCreateCompany" prefHeight="25.0" prefWidth="224.0"
text="Создать компанию"/>
</AnchorPane>
<AnchorPane disable="true" minHeight="0.0" minWidth="0.0" prefHeight="312.0"
prefWidth="235.0">
<Button alignment="CENTER" contentDisplay="CENTER" layoutX="5.0" layoutY="6.0"
mnemonicParsing="false" onAction="#createAiFighter" prefHeight="35.0"
prefWidth="224.0" text="Добавление истребителя"/>
<Button alignment="CENTER" contentDisplay="CENTER" layoutX="5.0" layoutY="48.0"
mnemonicParsing="false" onAction="#createWarPlane" prefHeight="35.0"
prefWidth="224.0" text="Добавление военного самолета"/>
<TextField fx:id="textBox" layoutX="6.0" layoutY="132.0" prefHeight="25.0"
prefWidth="224.0"/>
<Button alignment="CENTER" contentDisplay="CENTER" layoutX="6.0" layoutY="162.0"
mnemonicParsing="false" onAction="#buttonRemovePlaneClicked"
prefHeight="35.0" prefWidth="224.0" text="Удалить истребитель"/>
<Button alignment="CENTER" contentDisplay="CENTER" layoutX="6.0" layoutY="215.0"
mnemonicParsing="false" onAction="#buttonGoToCheck" prefHeight="35.0"
prefWidth="224.0" text="Передать на тесты"/>
<Button alignment="CENTER" contentDisplay="CENTER" layoutX="6.0" layoutY="300.0"
mnemonicParsing="false" onAction="#buttonRefresh" prefHeight="35.0"
prefWidth="224.0" text="Обновить"/>
<Button alignment="CENTER" contentDisplay="CENTER" layoutX="6.0" layoutY="90.0"
mnemonicParsing="false" onAction="#buttonGoFormConstructor"
prefHeight="35.0" prefWidth="224.0" text="Добавить через конструктор"/>
<Button layoutX="6.0" layoutY="257.0" mnemonicParsing="false"
onAction="#buttonGoToFormWithDeleteObject" prefHeight="35.0"
text="Передать на тесты удаленный объект"/>
</AnchorPane>
</SplitPane>
</AnchorPane>
</SplitPane>
</AnchorPane>
</SplitPane>