Compare commits

...

13 Commits

Author SHA1 Message Date
IlyasValiulov
bc5cce4b55 Лабараторная работа №7 1 2024-05-10 12:11:23 +04:00
IlyasValiulov
1b17183c14 Лабараторная работа №6 1 2024-04-25 21:27:57 +04:00
IlyasValiulov
aa2c3827ef Лабараторная работа №5 1 2024-04-25 21:09:03 +04:00
IlyasValiulov
b143d60656 Лабараторная работа №5 1 2024-04-25 21:08:12 +04:00
IlyasValiulov
b30f5254c1 Лабараторная работа №4 1 2024-04-04 18:50:39 +04:00
IlyasValiulov
8404340fc4 Лабараторная работа №4 1 2024-04-04 12:01:27 +04:00
IlyasValiulov
e021aac7e7 Лабараторная работа №3 1 2024-04-04 11:46:31 +04:00
IlyasValiulov
cb4a9332af Лабараторная работа №2 3 2024-04-04 11:39:57 +04:00
IlyasValiulov
bc4761841a Лабараторная работа №3 1 2024-04-04 11:35:29 +04:00
IlyasValiulov
cc0082b6c9 Лабараторная работа №2 1 2024-03-14 20:03:10 +04:00
IlyasValiulov
fb2d9e01db Лабараторная работа №2 1 2024-03-14 20:00:25 +04:00
IlyasValiulov
bf991f6eed Лабараторная работа №1 2024-02-25 22:38:36 +04:00
IlyasValiulov
fe5cdc68d5 Лабараторная работа №1 2024-02-22 19:27:05 +04:00
44 changed files with 2588 additions and 1 deletions

1
WarmlyShip/.idea/.name Normal file
View File

@ -0,0 +1 @@
Main.java

View File

@ -7,5 +7,23 @@
</content> </content>
<orderEntry type="inheritedJdk" /> <orderEntry type="inheritedJdk" />
<orderEntry type="sourceFolder" forTests="false" /> <orderEntry type="sourceFolder" forTests="false" />
<orderEntry type="module-library">
<library>
<CLASSES>
<root url="jar://$USER_HOME$/Downloads/bin/log4j-api-2.23.1.jar!/" />
</CLASSES>
<JAVADOC />
<SOURCES />
</library>
</orderEntry>
<orderEntry type="module-library">
<library>
<CLASSES>
<root url="jar://$USER_HOME$/Downloads/jar_files/log4j-core-2.20.0.jar!/" />
</CLASSES>
<JAVADOC />
<SOURCES />
</library>
</orderEntry>
</component> </component>
</module> </module>

View File

@ -0,0 +1,61 @@
package CollectionAdditionalObjects;
import DiffetentsDrawingDecks.IDifferentDecks;
import DrawingShip.DrawingShip;
import DrawingShip.DrawingWarmlyShip;
import Entities.EntityShip;
import Entities.EntityWarmlyShip;
import java.lang.reflect.Array;
import java.util.Random;
public class AdditionalCollections <T extends EntityShip, U extends IDifferentDecks>{
public T[] _collectionEntity;
public U[] _collectionDecks;
public AdditionalCollections(int size, Class<T> type1, Class<T> type2) {
_collectionEntity = (T[]) Array.newInstance(type1, size);
_collectionDecks = (U[]) Array.newInstance(type2, size);
CountEntities = size;
CountDecks = size;
}
public int CountEntities;
public int CountDecks;
public int Insert(T entity) {
int index = 0;
while (index < CountEntities) {
if (_collectionEntity[index] == null)
{
_collectionEntity[index] = entity;
return index;
}
++index;
}
return -1;
}
public int Insert(U decks) {
int index = 0;
while (index < CountDecks) {
if (_collectionDecks[index] == null)
{
_collectionDecks[index] = decks;
return index;
}
++index;
}
return -1;
}
public DrawingShip CreateAdditionalCollectionShip() {
Random random = new Random();
if (_collectionEntity == null || _collectionDecks == null) return null;
T entity = _collectionEntity[random.nextInt(CountEntities)];
U decks = _collectionDecks[random.nextInt(CountDecks)];
DrawingShip drawingShip = null;
if (entity instanceof EntityWarmlyShip) {
drawingShip = new DrawingWarmlyShip((EntityWarmlyShip) entity, decks);
}
else {
drawingShip = new DrawingShip(entity, decks);
}
return drawingShip;
}
}

View File

@ -0,0 +1,35 @@
package CollectionGenericObjects;
import DrawingShip.DrawingShip;
import Exceptions.ObjectNotFoundException;
import Exceptions.PositionOutOfCollectionException;
import java.awt.*;
public abstract class AbstractCompany {
protected int _placeSizeWidth = 210;
protected int _placeSizeHeight = 150;
protected int _pictureWidth;
protected int _pictureHeight;
public ICollectionGenericObjects<DrawingShip> _collection = null;
private int GetMaxCount() {
return _pictureWidth * _pictureHeight / (_placeSizeWidth * _placeSizeHeight);
}
public AbstractCompany(int picWidth, int picHeight, ICollectionGenericObjects<DrawingShip> collection)
{
_pictureWidth = picWidth;
_pictureHeight = picHeight;
_collection = collection;
_collection.SetMaxCount(GetMaxCount());
}
//перегрузка операторов в джаве не возможна
public DrawingShip GetRandomObject() throws PositionOutOfCollectionException, ObjectNotFoundException {
return _collection.Get((int)(Math.random()*GetMaxCount() + 0));
}
public void SetPosition()
{
SetObjectsPosition();
}
public abstract void DrawBackgound(Graphics graphics);
protected abstract void SetObjectsPosition();
}

View File

@ -0,0 +1,7 @@
package CollectionGenericObjects;
public enum CollectionType {
None,
Massive,
List
}

View File

@ -0,0 +1,18 @@
package CollectionGenericObjects;
import Exceptions.CollectionOverflowException;
import Exceptions.ObjectNotFoundException;
import Exceptions.PositionOutOfCollectionException;
public interface ICollectionGenericObjects<T>
{
int getCount();
void SetMaxCount(int count);
int Insert(T obj) throws CollectionOverflowException;
T Remove(int position) throws PositionOutOfCollectionException, ObjectNotFoundException;
T Get(int position) throws PositionOutOfCollectionException, ObjectNotFoundException;
CollectionType GetCollectionType();
Iterable<T> GetItems();
void ClearCollection();
}

View File

@ -0,0 +1,77 @@
package CollectionGenericObjects;
import Exceptions.CollectionOverflowException;
import Exceptions.PositionOutOfCollectionException;
import java.util.*;
public class ListGenericObjects<T> implements ICollectionGenericObjects<T> {
private List<T> _collection;
private CollectionType collectionType = CollectionType.List;
private int _maxCount;
public int getCount() {
return _collection.size();
}
@Override
public void SetMaxCount(int size) {
if (size > 0) {
_maxCount = size;
}
}
public ListGenericObjects() {
_collection = new ArrayList<T>();
}
@Override
public CollectionType GetCollectionType() {
return collectionType;
}
@Override
public T Get(int position) throws PositionOutOfCollectionException {
if (position >= getCount() || position < 0) throw new PositionOutOfCollectionException(position);
return _collection.get(position);
}
@Override
public int Insert(T obj) throws CollectionOverflowException {
if (getCount() == _maxCount) throw new CollectionOverflowException(getCount());
_collection.add(obj);
return getCount();
}
@Override
public T Remove(int position) throws PositionOutOfCollectionException {
if (position >= getCount() || position < 0) throw new PositionOutOfCollectionException(position);
T obj = _collection.get(position);
_collection.remove(position);
return obj;
}
@Override
public Iterable<T> GetItems() {
return new Iterable<T>() {
@Override
public Iterator<T> iterator() {
return new Iterator<T>() {
private int currentIndex = 0;
//нужен ли count
private int count = 0;
@Override
public boolean hasNext() {
return currentIndex < getCount();
}
@Override
public T next() {
if (hasNext()) {
count++;
return _collection.get(currentIndex++);
}
throw new NoSuchElementException();
}
};
}
};
}
@Override
public void ClearCollection() {
for (T ship : _collection) {
ship = null;
}
}
}

View File

@ -0,0 +1,92 @@
package CollectionGenericObjects;
import DrawingShip.DrawingShip;
import Exceptions.CollectionOverflowException;
import Exceptions.ObjectNotFoundException;
import Exceptions.PositionOutOfCollectionException;
import java.lang.reflect.Array;
import java.util.*;
public class MassiveGenericObjects<T> implements ICollectionGenericObjects<T>{
private T[] _collection = null;
private int Count;
private CollectionType collectionType = CollectionType.Massive;
@Override
public void SetMaxCount(int size) {
if (size > 0) {
if (_collection == null) {
_collection = (T[]) Array.newInstance((Class) DrawingShip.class, size);
Count = size;
}
}
}
@Override
public int getCount() {
return Count;
}
@Override
public CollectionType GetCollectionType() {
return collectionType;
}
@Override
public int Insert(T obj) throws CollectionOverflowException {
int index = 0;
while (index < getCount())
{
if (_collection[index] == null)
{
_collection[index] = obj;
return index;
}
++index;
}
throw new CollectionOverflowException(Count);
}
@Override
public T Remove(int position) throws PositionOutOfCollectionException, ObjectNotFoundException {
if (position >= getCount() || position < 0)
throw new PositionOutOfCollectionException(position);
if (_collection[position] == null) throw new ObjectNotFoundException(position);
T obj = (T) _collection[position];
_collection[position] = null;
return obj;
}
@Override
public T Get(int position) throws PositionOutOfCollectionException, ObjectNotFoundException {
if (position >= getCount() || position < 0) throw new PositionOutOfCollectionException(position);
if (_collection[position] == null) throw new ObjectNotFoundException(position);
return (T) _collection[position];
}
@Override
public Iterable<T> GetItems() {
return new Iterable<T>() {
@Override
public Iterator<T> iterator() {
return new Iterator<T>() {
private int currentIndex = 0;
//нужен ли count
private int count = 0;
@Override
public boolean hasNext() {
return currentIndex < getCount();
}
@Override
public T next() {
if (hasNext()) {
count++;
return _collection[currentIndex++];
}
throw new NoSuchElementException();
}
};
}
};
}
@Override
public void ClearCollection() {
for (T ship : _collection) {
ship = null;
}
}
}

View File

@ -0,0 +1,53 @@
package CollectionGenericObjects;
import DrawingShip.DrawingShip;
import java.awt.*;
public class ShipPortService extends AbstractCompany{
public ShipPortService(int picWidth, int picHeight, ICollectionGenericObjects<DrawingShip> collection) {
super(picWidth, picHeight, collection);
}
@Override
public void DrawBackgound(Graphics g) {
//рисуем пристань
int width = _pictureWidth / _placeSizeWidth;
int height = _pictureHeight / _placeSizeHeight;
g.setColor(Color.BLACK);
for (int i = 0; i < width; i++)
{
for (int j = 0; j < height + 1; ++j)
{
g.drawLine(i * _placeSizeWidth, j * _placeSizeHeight,
i * _placeSizeWidth + _placeSizeWidth - 5, j * _placeSizeHeight );
}
}
}
@Override
protected void SetObjectsPosition() {
int width = _pictureWidth / _placeSizeWidth;
int height = _pictureHeight / _placeSizeHeight;
int curWidth = width - 1;
int curHeight = 0;
for (int i = 0; i < (_collection.getCount()); i++) {
try {
if (_collection.Get(i) != null) {
_collection.Get(i).SetPictureSize(_pictureWidth, _pictureHeight);
_collection.Get(i).SetPosition(_placeSizeWidth * curWidth + 20, curHeight * _placeSizeHeight + 4);
}
}
catch (Exception ex) {}
if (curWidth > 0)
curWidth--;
else {
curWidth = width - 1;
curHeight++;
}
if (curHeight > height) {
return;
}
}
}
}

View File

@ -0,0 +1,207 @@
package CollectionGenericObjects;
import DrawingShip.DrawingShip;
import DrawingShip.ExtentionDrawningShip;
import Exceptions.CollectionOverflowException;
import Exceptions.ObjectNotFoundException;
import Exceptions.PositionOutOfCollectionException;
import java.io.*;
import java.util.*;
public class StorageCollection<T extends DrawingShip> {
private Map<String, ICollectionGenericObjects<T>> _storages;
public StorageCollection()
{
_storages = new HashMap<String, ICollectionGenericObjects<T>>();
}
public Set<String> Keys() {
Set<String> keys = _storages.keySet();
return keys;
}
public void AddCollection(String name, CollectionType collectionType)
{
if (_storages.containsKey(name)) return;
if (collectionType == CollectionType.None) return;
else if (collectionType == CollectionType.Massive)
_storages.put(name, new MassiveGenericObjects<T>());
else if (collectionType == CollectionType.List)
_storages.put(name, new ListGenericObjects<T>());
}
public void DelCollection(String name)
{
if (_storages.containsKey(name))
_storages.remove(name);
}
// в джаве отсутствуют индикаторы
public ICollectionGenericObjects<T> getCollectionObject(String name) {
if (_storages.containsKey(name))
return _storages.get(name);
return null;
}
//дополнительное задание номер 1
public T Get(String name, int position) throws ObjectNotFoundException, PositionOutOfCollectionException {
if(_storages.containsKey(name))
return _storages.get(name).Remove(position);
return null;
}
private String _collectionKey = "CollectionsStorage";
private String _collectionName = "StorageCollection";
private String _separatorForKeyValueS = "|";
private String _separatorForKeyValue = "\\|";
private String _separatorItemsS = ";";
private String _separatorItems = "\\;";
public void SaveData(String filename) throws Exception {
if (_storages.isEmpty()) throw new Exception("В хранилище отсутствуют коллекции для сохранения");
File file = new File(filename);
if (file.exists()) file.delete();
try {
file.createNewFile();
FileWriter writer = new FileWriter(file);
writer.write(_collectionKey);
writer.write("\n");
for (Map.Entry<String, ICollectionGenericObjects<T>> value : _storages.entrySet()) {
StringBuilder sb = new StringBuilder();
sb.append(value.getKey());
sb.append(_separatorForKeyValueS);
sb.append(value.getValue().GetCollectionType());
sb.append(_separatorForKeyValueS);
sb.append(value.getValue().getCount());
sb.append(_separatorForKeyValueS);
for (T ship : value.getValue().GetItems()) {
String data = ExtentionDrawningShip.GetDataForSave((DrawingShip) ship);
if (data.isEmpty()) continue;
sb.append(data);
sb.append(_separatorItemsS);
}
sb.append("\n");
writer.write(String.valueOf(sb));
}
writer.close();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
public void SaveOneCollection(String filename, String name) throws Exception {
if (_storages.isEmpty()) throw new Exception("В хранилище отсутствуют коллекции для сохранения");
File file = new File(filename);
if (file.exists()) file.delete();
try {
file.createNewFile();
FileWriter writer = new FileWriter(file);
writer.write(_collectionName);
writer.write("\n");
ICollectionGenericObjects<T> value = _storages.get(name);
StringBuilder sb = new StringBuilder();
sb.append(name);
sb.append(_separatorForKeyValueS);
sb.append(value.GetCollectionType());
sb.append(_separatorForKeyValueS);
sb.append(value.getCount());
sb.append(_separatorForKeyValueS);
for (T ship : value.GetItems()) {
String data = ExtentionDrawningShip.GetDataForSave((DrawingShip) ship);
if (data.isEmpty()) continue;
sb.append(data);
sb.append(_separatorItemsS);
}
writer.append(sb);
writer.close();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
public void LoadData(String filename) throws Exception {
File file = new File(filename);
if (!file.exists()) throw new Exception("Файл не существует");
try (BufferedReader fs = new BufferedReader(new FileReader(filename))) {
String s = fs.readLine();
if (s == null || s.isEmpty() || !s.startsWith(_collectionKey))
throw new Exception("В файле нет данных или данные неверные");
_storages.clear();
s = "";
while ((s = fs.readLine()) != null) {
String[] record = s.split(_separatorForKeyValue);
if (record.length != 4) {
continue;
}
ICollectionGenericObjects<T> collection = CreateCollection(record[1]);
if (collection == null)
{
throw new Exception("Не удалось создать коллекцию");
}
collection.SetMaxCount(Integer.parseInt(record[2]));
String[] set = record[3].split(_separatorItems);
for (String elem : set) {
try
{
DrawingShip ship = ExtentionDrawningShip.CreateDrawingShip(elem);
if (collection.Insert((T) ship) == -1)
{
throw new Exception("Объект не удалось добавить в коллекцию: " + record[3]);
}
}
catch (CollectionOverflowException ex)
{
throw new Exception("Коллекция переполнена", ex);
}
}
_storages.put(record[0], collection);
}
}
catch (IOException e) {
throw new RuntimeException(e);
}
}
public void LoadOneCollection(String filename) throws Exception {
File file = new File(filename);
if (!file.exists()) throw new Exception("Файл не существует");
try (BufferedReader fs = new BufferedReader(new FileReader(filename))) {
String s = fs.readLine();
if (s == null || s.isEmpty() || !s.startsWith(_collectionName))
throw new Exception("В файле нет данных или данные неверные");
if (_storages.containsKey(s)) {
_storages.get(s).ClearCollection();
}
s = fs.readLine();
String[] record = s.split(_separatorForKeyValue);
if (record.length != 4) {
throw new Exception("Неверные данные");
}
ICollectionGenericObjects<T> collection = CreateCollection(record[1]);
if (collection == null)
{
throw new Exception("Не удалось создать коллекцию");
}
collection.SetMaxCount(Integer.parseInt(record[2]));
String[] set = record[3].split(_separatorItems);
for (String elem : set) {
try
{
DrawingShip ship = ExtentionDrawningShip.CreateDrawingShip(elem);
if (collection.Insert((T) ship) == -1)
{
throw new Exception("Объект не удалось добавить в коллекцию: " + record[3]);
}
}
catch (CollectionOverflowException ex)
{
throw new Exception("Коллекция переполнена", ex);
}
}
_storages.put(record[0], collection);
}
catch (IOException e) {
throw new RuntimeException(e);
}
}
public ICollectionGenericObjects<T> CreateCollection(String s) {
switch (s) {
case "Massive":
return new MassiveGenericObjects<T>();
case "List":
return new ListGenericObjects<T>();
}
return null;
}
}

View File

@ -0,0 +1,28 @@
package DiffetentsDrawingDecks;
import java.awt.*;
public class DrawingDecksType1 implements IDifferentDecks {
private NumberOfDecks numberOfDecks;
@Override
public void setNumberOfDecks(int numberofdeck) {
for (NumberOfDecks numofenum : NumberOfDecks.values()) {
if (numofenum.getNumdecks() == numberofdeck) {
numberOfDecks = numofenum;
return;
}
}
}
@Override
public NumberOfDecks getNumberOfDecks() {
return numberOfDecks;
}
@Override
public void DrawDecks(Graphics2D g, int x, int y, int width, int height, Color bodyColor) {
g.setColor(bodyColor);
g.fillRect(x, y, width, height);
g.setColor(Color.BLACK);
g.drawRect(x, y, width, height);
g.setColor(bodyColor);
}
}

View File

@ -0,0 +1,34 @@
package DiffetentsDrawingDecks;
import java.awt.*;
public class DrawingDecksType2 implements IDifferentDecks {
private NumberOfDecks numberOfDecks;
@Override
public void setNumberOfDecks(int numberofdeck) {
for (NumberOfDecks numofenum : NumberOfDecks.values()) {
if (numofenum.getNumdecks() == numberofdeck) {
numberOfDecks = numofenum;
return;
}
}
}
@Override
public NumberOfDecks getNumberOfDecks() {
return numberOfDecks;
}
@Override
public void DrawDecks(Graphics2D g, int x, int y, int width, int height, Color bodyColor) {
g.setStroke(new BasicStroke(3.0F));
g.setColor(bodyColor);
//верхняя часть полубы
g.drawLine(x, y, x + width, y);
//опорные балки
int countBalks = 4;
int wayBetweenBalks = width / countBalks;
for (int i = 0; i <= countBalks; i++) {
int nowX = x + wayBetweenBalks * i;
g.drawLine(nowX, y, nowX, y + height);
}
}
}

View File

@ -0,0 +1,28 @@
package DiffetentsDrawingDecks;
import java.awt.*;
public class DrawingDecksType3 implements IDifferentDecks{
private NumberOfDecks numberOfDecks;
@Override
public void setNumberOfDecks(int numberofdeck) {
for (NumberOfDecks numofenum : NumberOfDecks.values()) {
if (numofenum.getNumdecks() == numberofdeck) {
numberOfDecks = numofenum;
return;
}
}
}
@Override
public NumberOfDecks getNumberOfDecks() {
return numberOfDecks;
}
@Override
public void DrawDecks(Graphics2D g, int x, int y, int width, int height, Color bodyColor) {
g.setColor(bodyColor);
g.fillRect(x, y, width, height);
g.setColor(Color.BLACK);
g.fillRect(x+ 10, y+5, width - 20, height-5);
g.setColor(bodyColor);
}
}

View File

@ -0,0 +1,9 @@
package DiffetentsDrawingDecks;
import java.awt.*;
public interface IDifferentDecks {
void setNumberOfDecks(int numberofdeck);
NumberOfDecks getNumberOfDecks();
void DrawDecks(Graphics2D g, int x, int y, int width, int height, Color bodyColor);
}

View File

@ -0,0 +1,12 @@
package DiffetentsDrawingDecks;
public enum NumberOfDecks {
OneDeck(1),
TwoDecks(2),
ThreeDecks(3);
private int numberofdecks;
NumberOfDecks(int numberofdecks) {
this.numberofdecks = numberofdecks;
}
public int getNumdecks() {return numberofdecks;}
}

View File

@ -0,0 +1,33 @@
package DrawingShip;
import CollectionGenericObjects.AbstractCompany;
import javax.swing.*;
import java.awt.*;
public class CanvasFormShipCollection<T> extends JComponent
{
public AbstractCompany company = null;
public void SetCollectionToCanvas(AbstractCompany company) {
this.company = company;
}
public CanvasFormShipCollection(){};
public void paintComponent(Graphics g) {
super.paintComponents(g);
if (company == null || company._collection == null) {
return;
}
company.DrawBackgound(g);
for (int i = 0; i < company._collection.getCount(); i++) {
try {
Graphics2D g2d = (Graphics2D) g;
T obj = (T) company._collection.Get(i);
if (obj instanceof DrawingShip) {
((DrawingShip) obj).DrawTransport(g2d);
}
}
catch (Exception ex) {}
}
super.repaint();
}
}

View File

@ -0,0 +1,19 @@
package DrawingShip;
import javax.swing.*;
import java.awt.*;
public class CanvasWarmlyShip extends JComponent {
public DrawingShip _drawingShip;
public CanvasWarmlyShip(){}
public void paintComponent(Graphics g) {
if (_drawingShip == null) {
return;
}
super.paintComponents(g);
Graphics2D g2d = (Graphics2D) g;
_drawingShip.DrawTransport(g2d);
super.repaint();
}
}

View File

@ -0,0 +1,9 @@
package DrawingShip;
public enum DirectionType {
Unknow,
Up,
Down,
Left,
Right
}

View File

@ -0,0 +1,149 @@
package DrawingShip;
import DiffetentsDrawingDecks.DrawingDecksType2;
import DiffetentsDrawingDecks.DrawingDecksType3;
import DiffetentsDrawingDecks.IDifferentDecks;
import Entities.EntityShip;
import DiffetentsDrawingDecks.DrawingDecksType1;
import javax.swing.*;
import java.awt.*;
public class DrawingShip extends JPanel {
public Entities.EntityShip EntityShip;
public IDifferentDecks drawingDecks;
private Integer picture_width;
private Integer picture_height;
public Integer _StartPosX;
public Integer _StartPosY;
private int drawingShipWidth = 150;
protected int drawingShipHeight = 50;
public Integer GetPosX() {return _StartPosX;}
public Integer GetPosY() {return _StartPosY;}
public Integer GetWidth() {return drawingShipWidth;}
public Integer GetHeight() {return drawingShipHeight;}
protected DrawingShip() {
picture_width = null;
picture_height = null;
_StartPosX = null;
_StartPosY = null;
}
public DrawingShip(int speed, double weight, Color bodycolor) {
super();
EntityShip = new EntityShip(speed, weight, bodycolor);
}
protected DrawingShip(int drawingShipWidth, int drawingShipHeight) {
super();
this.drawingShipWidth = drawingShipWidth;
this.drawingShipHeight = drawingShipHeight;
}
//добавил
public DrawingShip(EntityShip entity, IDifferentDecks decks) {
EntityShip = entity;
drawingDecks = decks;
}
public boolean SetPictureSize(int width, int height) {
if (width < drawingShipWidth || height < drawingShipHeight) return false;
picture_width = width;
picture_height = height;
if (_StartPosX != null || _StartPosY != null) {
if (_StartPosX + drawingShipWidth > picture_width)
{
_StartPosX = _StartPosX - (_StartPosX + drawingShipWidth - picture_width);
}
else if (_StartPosX < 0) _StartPosX = 0;
if (_StartPosY + drawingShipHeight > picture_height)
{
_StartPosY = _StartPosY - (_StartPosY + drawingShipHeight - picture_height);
}
else if (_StartPosY < 0) _StartPosY = 0;
}
return true;
}
public void SetPosition(int x, int y) {
if (!(picture_width != null && picture_height != null)) return;
if (x + drawingShipWidth > picture_width)
{
_StartPosX = x - (x + drawingShipWidth - picture_width);
}
else if (x < 0) _StartPosX = 0;
else _StartPosX = x;
if (y + drawingShipHeight > picture_height)
{
_StartPosY = y - (y + drawingShipHeight - picture_height);
}
else if (y < 0) _StartPosY = 0;
else _StartPosY = y;
}
public boolean MoveTransport(DirectionType direction) {
if (EntityShip == null || _StartPosX == null || _StartPosY == null) return false;
switch (direction) {
case DirectionType.Left:
if (_StartPosX - EntityShip.Step > 0) {
_StartPosX -= (int)EntityShip.Step;
}
return true;
case DirectionType.Up:
if (_StartPosY - EntityShip.Step > 0)
{
_StartPosY -= (int)EntityShip.Step;
}
return true;
case DirectionType.Right:
if (_StartPosX + drawingShipWidth + (int)EntityShip.Step < picture_width - EntityShip.Step)
{
_StartPosX += (int)EntityShip.Step;
}
return true;
case DirectionType.Down:
if (_StartPosY + drawingShipHeight + (int)EntityShip.Step < picture_height - EntityShip.Step)
{
_StartPosY += (int)EntityShip.Step;
}
return true;
default:
return false;
}
}
public void DrawTransport(Graphics2D g) {
if (EntityShip == null || _StartPosX == null || _StartPosY == null) return;
int y = _StartPosY;
g.setColor(EntityShip.getBodyColor());
if (drawingDecks != null && drawingDecks.getNumberOfDecks() != null) {
switch (drawingDecks.getNumberOfDecks()) {
case OneDeck:
drawingDecks.DrawDecks(g, _StartPosX + 30, y, 100, 15, EntityShip.getBodyColor());
y += 15;
break;
case TwoDecks:
drawingDecks.DrawDecks(g, _StartPosX + 30, y, 100, 15, EntityShip.getBodyColor());
drawingDecks.DrawDecks(g, _StartPosX + 30, y + 15, 100, 15, EntityShip.getBodyColor());
y += 30;
break;
case ThreeDecks:
drawingDecks.DrawDecks(g, _StartPosX + 30, y, 100, 15, EntityShip.getBodyColor());
drawingDecks.DrawDecks(g, _StartPosX + 30, y + 15, 100, 15, EntityShip.getBodyColor());
drawingDecks.DrawDecks(g, _StartPosX + 30, y + 30, 100, 15, EntityShip.getBodyColor());
y += 45;
break;
}
}
int[] arrayX = {_StartPosX, _StartPosX+150, _StartPosX+150, _StartPosX+120, _StartPosX+120, _StartPosX+30, _StartPosX+30, _StartPosX};
int[] arrayY = {y, y, y, y + 50, y + 50, y + 50, y + 50, y};
Polygon poly = new Polygon(arrayX, arrayY, 8);
g.fillPolygon(poly);
drawingShipHeight = y + 50 - _StartPosY;
}
public String[] GetStringRepresentationDecks() {
if (drawingDecks instanceof DrawingDecksType1) {
return new String[]{String.valueOf(drawingDecks.getNumberOfDecks().getNumdecks()), "DrawingDecksType1"};
}
else if (drawingDecks instanceof DrawingDecksType2) {
return new String[]{String.valueOf(drawingDecks.getNumberOfDecks().getNumdecks()), "DrawingDecksType2"};
}
else if (drawingDecks instanceof DrawingDecksType3) {
return new String[]{String.valueOf(drawingDecks.getNumberOfDecks().getNumdecks()), "DrawingDecksType3"};
}
return null;
}
}

View File

@ -0,0 +1,52 @@
package DrawingShip;
import DiffetentsDrawingDecks.IDifferentDecks;
import Entities.EntityWarmlyShip;
import java.awt.*;
public class DrawingWarmlyShip extends DrawingShip {
public DrawingWarmlyShip(int speed, double weight, Color bodycolor, Color additionalcolor, boolean sheeppipes, boolean fueltank) {
EntityShip = new EntityWarmlyShip(speed, weight, bodycolor, additionalcolor, sheeppipes, fueltank);
}
//добавил
public DrawingWarmlyShip(EntityWarmlyShip entity, IDifferentDecks decks) {
EntityShip = entity;
drawingDecks = decks;
}
@Override
public void DrawTransport(Graphics2D g) {
if (EntityShip == null || !(EntityShip instanceof EntityWarmlyShip warmlyship) || _StartPosX == null || _StartPosY == null)
return;
int y = _StartPosY;
if (warmlyship.ShipPipes) {
//трубы
g.setColor(warmlyship.getAdditionalColor());
g.fillRect(_StartPosX + 70, _StartPosY, 12, 30);
g.fillRect(_StartPosX + 90, _StartPosY, 12, 30);
_StartPosY += 30;
}
super.DrawTransport(g);
int count_decks = 0;
if (drawingDecks != null && drawingDecks.getNumberOfDecks() != null) {
switch (drawingDecks.getNumberOfDecks()) {
case OneDeck:
count_decks = 1;
break;
case TwoDecks:
count_decks = 2;
break;
case ThreeDecks:
count_decks = 3;
break;
}
}
if (warmlyship.getFuelTank()) {
g.setColor(warmlyship.getAdditionalColor());
g.fillRect(_StartPosX + 40, _StartPosY + count_decks * 15 + 30, 70, 10);
}
if (warmlyship.ShipPipes) {
_StartPosY -= 30;
drawingShipHeight += 30;
}
}
}

View File

@ -0,0 +1,74 @@
package DrawingShip;
import DiffetentsDrawingDecks.DrawingDecksType1;
import DiffetentsDrawingDecks.DrawingDecksType2;
import DiffetentsDrawingDecks.DrawingDecksType3;
import DiffetentsDrawingDecks.IDifferentDecks;
import Entities.EntityShip;
import Entities.EntityWarmlyShip;
import java.util.ArrayList;
import java.util.Collections;
public class ExtentionDrawningShip {
private static String _separatorForObjectS = ":";
private static String _separatorForObject = "\\:";
public static DrawingShip CreateDrawingShip(String info) {
String[] strs = info.split(_separatorForObject);
EntityShip ship;
IDifferentDecks decks = null;
if (strs.length == 8)
{
String s = strs[8];
switch (s) {
case "DrawingDecksType1":
decks = new DrawingDecksType1();
case "DrawingDecksType2":
decks = new DrawingDecksType2();
case "DrawingDecksType3":
decks = new DrawingDecksType3();
}
if (decks != null) decks.setNumberOfDecks(Integer.parseInt(strs[7]));
}
else if (strs.length == 6) {
String s = strs[5];
switch (s) {
case "DrawingDecksType1":
decks = new DrawingDecksType1();
case "DrawingDecksType2":
decks = new DrawingDecksType2();
case "DrawingDecksType3":
decks = new DrawingDecksType3();
}
if (decks != null) decks.setNumberOfDecks(Integer.parseInt(strs[4]));
}
ship = EntityWarmlyShip.CreateEntityWarmlyShip(strs);
if (ship != null)
{
return new DrawingWarmlyShip((EntityWarmlyShip)ship, decks);
}
ship = EntityShip.CreateEntityShip(strs);
if (ship != null)
{
return new DrawingShip(ship, decks);
}
return null;
}
public static String GetDataForSave(DrawingShip drawningShip)
{
if (drawningShip == null) return "";
String[] array1 = drawningShip.EntityShip.GetStringRepresentation();
String[] array2 = drawningShip.GetStringRepresentationDecks();
if (array1 == null)
{
return "";
}
ArrayList<String> list = new ArrayList<>();
Collections.addAll(list, array1);
if (array2 == null) {
Collections.addAll(list, "0", " ");
}
else Collections.addAll(list, array2);
return String.join(_separatorForObjectS, list);
}
}

View File

@ -0,0 +1,42 @@
package Entities;
import java.awt.*;
import java.util.Objects;
public class EntityShip {
private Integer Speed;
public void setSpeed(int speed) {Speed = speed;}
public Integer getSpeed() {return Speed;}
private Double Weight;
public void setWeight(double weight) {Weight = weight;}
public Double getWeight() {return Weight;}
private Color BodyColor;
public Color getBodyColor() {return BodyColor;}
public void setBodyColor(Color color) {BodyColor = color;}
public double Step;
public EntityShip(int speed, double weight, Color bodycolor)
{
Speed = speed;
Weight = weight;
BodyColor = bodycolor;
Step = Speed * 100 / Weight;
}
public String[] GetStringRepresentation()
{
return new String[]{"EntityShip", Speed.toString(), Weight.toString(), colorToHexString(BodyColor)};
}
public static EntityShip CreateEntityShip(String[] strs)
{
if (strs.length != 6 || !Objects.equals(strs[0], "EntityShip"))
{
return null;
}
return new EntityShip(Integer.parseInt(strs[1]), Double.parseDouble(strs[2]), hexStringToColor(strs[3]));
}
public static String colorToHexString(Color color) {
return String.format("#%02x%02x%02x", color.getRed(), color.getGreen(), color.getBlue());
}
public static Color hexStringToColor(String hexString) {
return Color.decode(hexString);
}
}

View File

@ -0,0 +1,38 @@
package Entities;
import java.awt.*;
import java.util.Objects;
public class EntityWarmlyShip extends EntityShip{
public Color AdditionalColor;
public Color getAdditionalColor() {return AdditionalColor;}
public void setAdditionalColor(Color color) {AdditionalColor = color;}
public boolean ShipPipes;
public void setShipPipes(boolean pipes) {ShipPipes = pipes;}
public boolean FuelTank;
public boolean getFuelTank() {return FuelTank;}
public void setFuelTank(boolean tank) {FuelTank = tank;}
public EntityWarmlyShip(int speed, double weight, Color bodyColor, Color additionalcolor, boolean sheeppipes, boolean fueltank)
{
super(speed, weight, bodyColor);
AdditionalColor = additionalcolor;
ShipPipes = sheeppipes;
FuelTank = fueltank;
}
@Override
public String[] GetStringRepresentation()
{
return new String[]{"EntityWarmlyShip", getSpeed().toString(), getWeight().toString(),
colorToHexString(getBodyColor()), colorToHexString(getAdditionalColor()),
String.valueOf(ShipPipes), String.valueOf(FuelTank)};
}
public static EntityWarmlyShip CreateEntityWarmlyShip(String[] strs)
{
if (strs.length != 9 || !Objects.equals(strs[0], "EntityWarmlyShip"))
{
return null;
}
return new EntityWarmlyShip(Integer.parseInt(strs[1]), Double.parseDouble(strs[2]), hexStringToColor(strs[3]),
hexStringToColor(strs[4]), Boolean.parseBoolean(strs[5]), Boolean.parseBoolean(strs[6]));
}
}

View File

@ -0,0 +1,8 @@
package Exceptions;
//неиспользованные методы
public class CollectionOverflowException extends Exception {
public CollectionOverflowException(int count) {super("В коллекции превышено допустимое количество: " + count); }
public CollectionOverflowException() { super(); }
public CollectionOverflowException(String message) { super(message); }
public CollectionOverflowException(String message, Exception exception) { super(message, exception); }
}

View File

@ -0,0 +1,8 @@
package Exceptions;
//неиспользованные методы
public class ObjectNotFoundException extends Exception{
public ObjectNotFoundException(int i) { super("Не найден объект по позиции " + i); }
public ObjectNotFoundException() { super(); }
public ObjectNotFoundException(String message) { super(message); }
public ObjectNotFoundException(String message, Throwable cause) {super(message, cause); }
}

View File

@ -0,0 +1,8 @@
package Exceptions;
//неиспользуемые методы
public class PositionOutOfCollectionException extends Exception{
public PositionOutOfCollectionException(int i) { super("Выход за границы коллекции. Позиция " + i); }
public PositionOutOfCollectionException() { super(); }
public PositionOutOfCollectionException(String message) { super(message); }
public PositionOutOfCollectionException(String message, Throwable cause) { super(message, cause); }
}

View File

@ -0,0 +1,153 @@
import CollectionAdditionalObjects.AdditionalCollections;
import CollectionGenericObjects.AbstractCompany;
import DiffetentsDrawingDecks.DrawingDecksType1;
import DiffetentsDrawingDecks.DrawingDecksType2;
import DiffetentsDrawingDecks.DrawingDecksType3;
import DiffetentsDrawingDecks.IDifferentDecks;
import DrawingShip.DrawingShip;
import DrawingShip.DrawingWarmlyShip;
import DrawingShip.CanvasWarmlyShip;
import Entities.EntityShip;
import Entities.EntityWarmlyShip;
import Exceptions.CollectionOverflowException;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Random;
import static DrawingShip.ExtentionDrawningShip.GetDataForSave;
public class FormAdditionalCollection extends JFrame {
public DrawingShip drawingShip = null;
private AbstractCompany company = null;
private CanvasWarmlyShip canvasship = new CanvasWarmlyShip();
private AdditionalCollections<EntityShip, IDifferentDecks> additionalCollection = null;
private Random random = new Random();
private JButton buttonGenerate = new JButton("Создать");
private JList<String> listEntity = new JList<String>();
private JList<String> listDecks = new JList<String>();
private org.apache.logging.log4j.Logger logger;
private org.apache.logging.log4j.Logger loggerErrow;
public FormAdditionalCollection(org.apache.logging.log4j.Logger logger,
org.apache.logging.log4j.Logger logger2) {
setTitle("Random ship");
setMinimumSize(new Dimension(650,310));
this.logger = logger;
this.loggerErrow = logger2;
additionalCollection = new AdditionalCollections<EntityShip, IDifferentDecks>(3,
(Class) EntityShip.class, (Class) IDifferentDecks.class);
AddEntities();
AddDecks();
buttonGenerate.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
try {
drawingShip = additionalCollection.CreateAdditionalCollectionShip();
drawingShip.SetPictureSize(getWidth(), getHeight());
drawingShip.SetPosition(50, 50);
canvasship._drawingShip = drawingShip;
canvasship.repaint();
DrawingShip copyShip;
if (drawingShip instanceof DrawingWarmlyShip)
copyShip = new DrawingWarmlyShip((EntityWarmlyShip) drawingShip.EntityShip, drawingShip.drawingDecks);
else
copyShip = new DrawingShip(drawingShip.EntityShip, drawingShip.drawingDecks);
company._collection.Insert(copyShip);
FormShipCollection.canvasShow();
logger.info("Добавлен объект: " + GetDataForSave(copyShip));
String[] data1 = new String[additionalCollection.CountEntities];
for (int i = 0; i < additionalCollection.CountEntities; i++) {
EntityShip entity = additionalCollection._collectionEntity[i];
data1[i] = ToString(entity);
}
String[] data2 = new String[additionalCollection.CountDecks];
for (int i = 0; i < additionalCollection.CountDecks; i++) {
IDifferentDecks decks = additionalCollection._collectionDecks[i];
data2[i] = ToString(decks);
}
listEntity.setListData(data1);
listDecks.setListData(data2);
}
catch (CollectionOverflowException ex) {
loggerErrow.warn(ex.toString());
}
catch (Exception ex) {
loggerErrow.fatal("Ошибка в выводу форме FormAdditionalCollection");
}
}
});
buttonGenerate.setBounds(450, 10, 100, 50);
add(buttonGenerate);
listEntity.setBounds(10,200,300,60);
listDecks.setBounds(320,200,300,60);
add(listEntity);
add(listDecks);
add(canvasship);
setVisible(true);
}
private String ToString(EntityShip entity) {
String str = "";
if (entity instanceof EntityWarmlyShip) str += "EntityWarmlyShip ";
else str += "EntityShip ";
str += entity.getBodyColor().toString();
return str;
}
private String ToString(IDifferentDecks decks) {
if (decks == null || decks.getNumberOfDecks() == null)
return "Dont have decks";
String str = "Deck ";
if (decks instanceof DrawingDecksType1) str += "Type 1 ";
else if (decks instanceof DrawingDecksType2) str += "Type 2 ";
else str += "Type 3 ";
str += decks.getNumberOfDecks().toString();
return str;
}
public void AddEntities() {
for (int i = 0; i < additionalCollection.CountEntities; i++) {
random = new Random();
int speed = random.nextInt(100, 300);
double weight = random.nextInt(1000, 3000);
Color bodycolor = new Color(random.nextInt(256), random.nextInt(256), random.nextInt(256));
EntityShip entity;
if (random.nextBoolean()) {
entity = new EntityShip(speed, weight, bodycolor);
}
else {
Color additionalcolor = new Color(random.nextInt(256), random.nextInt(256), random.nextInt(256));
boolean sheeppipes = random.nextBoolean();
boolean fueltaln = random.nextBoolean();
entity = new EntityWarmlyShip(speed, weight, bodycolor,
additionalcolor, sheeppipes, fueltaln);
}
additionalCollection.Insert(entity);
}
}
public void AddDecks() {
for (int i = 0; i < additionalCollection.CountDecks; i++) {
random = new Random();
Integer numberOfDecks = random.nextInt(0, 4);
IDifferentDecks drawingDecks = null;
switch (random.nextInt(0,4)) {
case 1:
drawingDecks = new DrawingDecksType1();
break;
case 2:
drawingDecks = new DrawingDecksType2();
break;
case 3:
drawingDecks = new DrawingDecksType3();
break;
default:
numberOfDecks = null;
break;
}
if (drawingDecks != null) drawingDecks.setNumberOfDecks(numberOfDecks);
additionalCollection.Insert(drawingDecks);
}
}
void setCompany(AbstractCompany company) {
this.company = company;
}
}

View File

@ -0,0 +1,433 @@
import CollectionGenericObjects.*;
import DrawingShip.CanvasFormShipCollection;
import DrawingShip.DrawingShip;
import Exceptions.ObjectNotFoundException;
import Exceptions.PositionOutOfCollectionException;
import javax.swing.*;
import javax.swing.text.MaskFormatter;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.text.ParseException;
import java.util.Stack;
import java.util.logging.Logger;
import static DrawingShip.ExtentionDrawningShip.GetDataForSave;
import static java.lang.Integer.parseInt;
public class FormShipCollection extends JFrame{
private String title;
private Dimension dimension;
public static CanvasFormShipCollection<DrawingShip> _canvasWarmlyShip = new CanvasFormShipCollection<DrawingShip>();
private static AbstractCompany _company = null;
private Stack<DrawingShip> _collectionRemoveObjects = new Stack<DrawingShip>();
private StorageCollection<DrawingShip> _storageCollection = new StorageCollection<DrawingShip>();
private JTextField textBoxCollection = new JTextField();
private JRadioButton radioButtonMassive = new JRadioButton("Massive");
private JRadioButton radioButtonList = new JRadioButton("List");
private JButton buttonAddCollection = new JButton("Add");
private JList listBoxCollection = new JList();
private JButton buttonRemoveCollection = new JButton("Remove");
private JButton buttonCreateCompany = new JButton("Create company");
private JButton CreateShipButton = new JButton("Create ship");
private JButton RemoveButton = new JButton("Remove");
private JButton GoToCheckButton = new JButton("Check");
private JButton RandomButton = new JButton("RandomShip");
private JButton RemoveObjectsButton = new JButton("Show remove");
private JButton RefreshButton = new JButton("Refresh");
private JComboBox ComboBoxCollections = new JComboBox(new String[]{"", "Хранилище"});
private JFormattedTextField MaskedTextField;
private JMenuBar menuBar = new JMenuBar();
private JMenu fileMenu = new JMenu("File");
private JMenuItem loadItem = new JMenuItem("Load");
private JMenuItem saveItem = new JMenuItem("Save");
private JMenuItem loadCollection = new JMenuItem("Load coll");
private JMenuItem saveCollection = new JMenuItem("Save coll");
private org.apache.logging.log4j.Logger logger;
private org.apache.logging.log4j.Logger loggerErrow;
public FormShipCollection(String title, Dimension dimension,
org.apache.logging.log4j.Logger logger1, org.apache.logging.log4j.Logger logger2) {
this.title = title;
this.dimension = dimension;
this.logger = logger1;
logger.info("Форма загрузилась");
this.loggerErrow = logger2;
}
public static void canvasShow() {
_company.SetPosition();
_canvasWarmlyShip.SetCollectionToCanvas(_company);
_canvasWarmlyShip.repaint();
}
public void Init() {
setTitle(title);
setMinimumSize(dimension);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
MaskFormatter mask = null;
try {
mask = new MaskFormatter("##");
mask.setPlaceholder("00");
} catch (ParseException e) {
throw new RuntimeException(e);
}
MaskedTextField = new JFormattedTextField(mask);
CreateShipButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
if (_company == null) return;
FormShipConfig form = new FormShipConfig("", new Dimension(700, 300),
logger, loggerErrow);
form.setCompany(_company);
form.Init();
}
});
RemoveButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
if (_company == null || MaskedTextField.getText() == null ||
listBoxCollection.getSelectedValue().toString() == null) {
return;
}
int pos = parseInt(MaskedTextField.getText());
int resultConfirmDialog = JOptionPane.showConfirmDialog(null,
"Удалить", "Удаление",
JOptionPane.YES_NO_OPTION);
if (resultConfirmDialog == JOptionPane.NO_OPTION) return;
try {
DrawingShip obj = _storageCollection.Get(
listBoxCollection.getSelectedValue().toString(), pos);
if (obj != null) {
JOptionPane.showMessageDialog(null, "Объект удален");
_collectionRemoveObjects.push(obj);
canvasShow();
logger.info("Объект удален по позиции " + pos);
}
}
catch (PositionOutOfCollectionException | ObjectNotFoundException ex) {
loggerErrow.warn(ex.toString());
}
catch (Exception ex) {
loggerErrow.fatal(ex.toString());
JOptionPane.showMessageDialog(null, "Объект не удалось удалить");
}
}
});
GoToCheckButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
if (_company == null)
{
return;
}
try {
DrawingShip ship = null;
int counter = 100;
while (ship == null) {
ship = _company.GetRandomObject();
counter--;
if (counter <= 0) {
break;
}
}
if (ship == null) {
return;
}
FormWarmlyShip form = new FormWarmlyShip("Теплоход", new Dimension(900, 565));
form.Init(ship);
}
catch (Exception ex) {}
}
});
RandomButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
if (_company == null)
{
return;
}
try {
FormAdditionalCollection form = new FormAdditionalCollection(logger, loggerErrow);
form.setCompany(_company);
}
catch (Exception ex) {
loggerErrow.warn(ex.toString());
}
}
});
RefreshButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
if (_company == null)
{
return;
}
canvasShow();
}
});
buttonAddCollection.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
if (textBoxCollection.getText().isEmpty() || (!radioButtonMassive.isSelected()
&& !radioButtonList.isSelected())) {
JOptionPane.showMessageDialog(null, "Не все данные заполнены");
return;
}
try {
CollectionType collectionType = CollectionType.None;
if (radioButtonMassive.isSelected()) {
collectionType = CollectionType.Massive;
} else if (radioButtonList.isSelected()) {
collectionType = CollectionType.List;
}
_storageCollection.AddCollection(textBoxCollection.getText(), collectionType);
RerfreshListBoxItems();
logger.info("Добавлена коллекция: " + textBoxCollection.getText());
}
catch (Exception ex) {
loggerErrow.error(ex.toString());
}
}
});
buttonRemoveCollection.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
if (listBoxCollection.getSelectedIndex() < 0 || listBoxCollection.getSelectedValue() == null) {
JOptionPane.showMessageDialog(null, "Коллекция не выбрана");
return;
}
int resultConfirmDialog = JOptionPane.showConfirmDialog(null,
"Удалить", "Удаление",
JOptionPane.YES_NO_OPTION);
if (resultConfirmDialog == JOptionPane.NO_OPTION) return;
try {
_storageCollection.DelCollection(listBoxCollection.getSelectedValue().toString());
RerfreshListBoxItems();
logger.info("Удалена коллекция: " + textBoxCollection.getText());
}
catch (Exception ex) {
loggerErrow.error(ex.toString());
}
}
});
buttonCreateCompany.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
if (listBoxCollection.getSelectedIndex() < 0 || listBoxCollection.getSelectedValue() == null) {
JOptionPane.showMessageDialog(null, "Коллекция не выбрана");
return;
}
ICollectionGenericObjects<DrawingShip> collection =
_storageCollection.getCollectionObject(listBoxCollection.getSelectedValue().toString());
if (collection == null) {
JOptionPane.showMessageDialog(null, "Коллекция не проинициализирована");
return;
}
switch (ComboBoxCollections.getSelectedItem().toString()) {
case "Хранилище":
_company = new ShipPortService(getWidth()-200, getHeight()-70,
collection);
break;
}
RerfreshListBoxItems();
}
});
RemoveObjectsButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
if (_collectionRemoveObjects.empty())
{
return;
}
DrawingShip ship = null;
ship = _collectionRemoveObjects.pop();
if (ship == null)
{
return;
}
FormWarmlyShip form = new FormWarmlyShip("Теплоход", new Dimension(900,565));
form.Init(ship);
}
});
saveItem.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
SaveFile();
}
});
loadItem.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
LoadFile();
}
});
saveCollection.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
System.out.println("Save coll");
SaveCollection();
}
});
loadCollection.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
System.out.println("Load coll");
LoadCollection();
}
});
JLabel labelCollectionName = new JLabel("Название коллекции");
ButtonGroup radiobuttonsGroup = new ButtonGroup();
radiobuttonsGroup.add(radioButtonMassive);
radiobuttonsGroup.add(radioButtonList);
fileMenu.add(loadItem);
fileMenu.add(saveItem);
fileMenu.add(loadCollection);
fileMenu.add(saveCollection);
fileMenu.addSeparator();
menuBar.add(fileMenu);
setJMenuBar(menuBar);
_canvasWarmlyShip.setBounds(0, 0, getWidth()-200, getHeight());
labelCollectionName.setBounds(getWidth()-190, 10, 150, 20);
textBoxCollection.setBounds(getWidth()-190, 32, 150, 25);
radioButtonMassive.setBounds(getWidth()-190, 60, 75, 20);
radioButtonList.setBounds(getWidth()-105, 60, 50, 20);
buttonAddCollection.setBounds(getWidth()-190, 85, 150, 20);
listBoxCollection.setBounds(getWidth()-190, 115, 150, 70);
buttonRemoveCollection.setBounds(getWidth()-190, 195, 150, 20);
ComboBoxCollections.setBounds(getWidth()-190, 235, 150, 20);
buttonCreateCompany.setBounds(getWidth()-190, 260, 150, 20);
CreateShipButton.setBounds(getWidth()-190, 295, 150, 30);
MaskedTextField.setBounds(getWidth()-190,365,150,30);
RemoveButton.setBounds(getWidth()-190, 400, 150, 30);
GoToCheckButton.setBounds(getWidth()-190, 435, 150, 30);
RandomButton.setBounds(getWidth()-190, 470, 150, 30);
RemoveObjectsButton.setBounds(getWidth()-190, 505, 150, 30);
RefreshButton.setBounds(getWidth()-190, getHeight()-100, 150, 30);
setSize(dimension.width,dimension.height);
setLayout(null);
add(_canvasWarmlyShip);
add(labelCollectionName);
add(textBoxCollection);
add(radioButtonMassive);
add(radioButtonList);
add(buttonAddCollection);
add(listBoxCollection);
add(buttonRemoveCollection);
add(ComboBoxCollections);
add(buttonCreateCompany);
add(CreateShipButton);
add(MaskedTextField);
add(RemoveButton);
add(GoToCheckButton);
add(RandomButton);
add(RemoveObjectsButton);
add(RefreshButton);
setVisible(true);
}
private String SaveWindow() {
FileDialog fileDialog = new FileDialog(this, "Save File", FileDialog.SAVE);
fileDialog.setVisible(true);
String directory = fileDialog.getDirectory();
String file = fileDialog.getFile();
if (directory == null || file == null) return null;
return directory + file;
}
private void SaveFile() {
String filename = SaveWindow();
try {
_storageCollection.SaveData(filename);
JOptionPane.showMessageDialog(null, "Сохранено");
logger.info("Сохранение в файл: " + filename);
}
catch (Exception ex) {
JOptionPane.showMessageDialog(null, "Ошибка сохранения");
loggerErrow.error(ex.toString());
}
}
private void SaveCollection() {
String filename = SaveWindow();
if (filename == null) {
JOptionPane.showMessageDialog(null, "Файл не выбран");
return;
}
if (listBoxCollection.getSelectedIndex() < 0 || listBoxCollection.getSelectedValue() == null) {
JOptionPane.showMessageDialog(null, "Коллекция не выбрана");
}
try {
_storageCollection.SaveOneCollection(filename, listBoxCollection.getSelectedValue().toString());
JOptionPane.showMessageDialog(null, "Коллекция сохранена");
logger.info("Сохранение коллекции:" +
listBoxCollection.getSelectedValue().toString() + " в файл: " + filename);
}
catch (Exception ex) {
JOptionPane.showMessageDialog(null, "Ошибка сохранения");
loggerErrow.error(ex.toString());
}
}
private String LoadWindow() {
FileDialog fileDialog = new FileDialog(this, "Save File", FileDialog.LOAD);
fileDialog.setVisible(true);
String directory = fileDialog.getDirectory();
String file = fileDialog.getFile();
if (directory == null || file == null) return null;
return directory + file;
}
private void LoadFile() {
String filename = LoadWindow();
try {
_storageCollection.LoadData(filename);
JOptionPane.showMessageDialog(null, "Загрузка прошла успешно");
RerfreshListBoxItems();
logger.info("Загрузка файла: " + filename);
}
catch (Exception ex) {
JOptionPane.showMessageDialog(null, "Не загрузилось");
loggerErrow.error(ex.toString());
}
}
private void LoadCollection() {
String filename = LoadWindow();
try {
_storageCollection.LoadOneCollection(filename);
JOptionPane.showMessageDialog(null, "Коллекция загружена");
RerfreshListBoxItems();
logger.info("Загрузка коллекции: ");
}
catch (Exception ex) {
JOptionPane.showMessageDialog(null, "Не загрузилось");
loggerErrow.error(ex.toString());
}
}
private void RerfreshListBoxItems()
{
DefaultListModel<String> list = new DefaultListModel<String>();
for (String name : _storageCollection.Keys()) {
if (name != "")
{
list.addElement(name);
}
}
listBoxCollection.setModel(list);
}
}

View File

@ -0,0 +1,466 @@
import CollectionGenericObjects.AbstractCompany;
import DiffetentsDrawingDecks.DrawingDecksType1;
import DiffetentsDrawingDecks.DrawingDecksType2;
import DiffetentsDrawingDecks.DrawingDecksType3;
import DiffetentsDrawingDecks.IDifferentDecks;
import DrawingShip.DrawingShip;
import DrawingShip.DrawingWarmlyShip;
import Entities.EntityWarmlyShip;
import Exceptions.CollectionOverflowException;
import org.apache.logging.log4j.Logger;
import javax.swing.*;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import java.awt.*;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.StringSelection;
import java.awt.datatransfer.Transferable;
import java.awt.datatransfer.UnsupportedFlavorException;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.io.IOException;
import static DrawingShip.ExtentionDrawningShip.GetDataForSave;
public class FormShipConfig extends JFrame {
private String title;
private Dimension dimension;
private DrawingShip _ship;
private AbstractCompany company = null;
private JLabel labelSpeed = new JLabel("Speed");
private JLabel labelWeight = new JLabel("Weight");
private JLabel labelShip = new JLabel("Ship", SwingConstants.CENTER);
private JLabel labelWarmlyShip = new JLabel("WarmlyShip", SwingConstants.CENTER);
private JLabel labelColor = new JLabel("Color");
private JLabel labelBodyColor = new JLabel("BodyColor", SwingConstants.CENTER);
private JLabel labelSolidDeck = new JLabel("Solid Deck",SwingConstants.CENTER);
private JLabel labelBeamsDeck = new JLabel("Beams Deck", SwingConstants.CENTER);
private JLabel labelWindowDeck = new JLabel("Window Deck", SwingConstants.CENTER);
private JLabel labelAdditionalColor = new JLabel("Additi Color", SwingConstants.CENTER);
private JLabel labelNumberOfDecks = new JLabel("Numb Of decks");
private JSpinner spinnerSpeed = new JSpinner();
private JSpinner spinnerWeight = new JSpinner();
private JSpinner spinnerNumberOfDecks = new JSpinner();
private JCheckBox checkBoxPipes = new JCheckBox("Have a Ship Pipes");
private JCheckBox checkBoxFuelTank = new JCheckBox("Have a Fuel Tank");
private JComponent panelObject = new JPanel();
private JPanel panelColorRed = new JPanel();
private JPanel panelColorGreen = new JPanel();
private JPanel panelColorBlue = new JPanel();
private JPanel panelColorYellow = new JPanel();
private JPanel panelColorBlack = new JPanel();
private JPanel panelColorWhite = new JPanel();
private JPanel panelColorGray = new JPanel();
private JPanel panelColorCyan = new JPanel();
private JButton buttonAdd = new JButton("Add");
private JButton buttonCansel = new JButton("Cancel");
private org.apache.logging.log4j.Logger logger;
private org.apache.logging.log4j.Logger loggerErrow;
public FormShipConfig(String title, Dimension dimension, org.apache.logging.log4j.Logger logger,
org.apache.logging.log4j.Logger logger2) {
this.title = title;
this.dimension = dimension;
this.logger = logger;
this.loggerErrow = logger2;
}
public void Init() {
SpinnerModel numSpeed = new SpinnerNumberModel(100, 100, 1000, 1);
SpinnerModel numWeight = new SpinnerNumberModel(100, 100, 1000, 1);
spinnerSpeed.setModel(numSpeed);
spinnerWeight.setModel(numWeight);
SpinnerModel numDecks = new SpinnerNumberModel(0, 0, 3, 1);
spinnerNumberOfDecks.setModel(numDecks);
panelObject = new Canvas();
panelObject.setBorder(BorderFactory.createLineBorder(Color.BLACK, 2));
spinnerSpeed.addChangeListener(new ChangeListener() {
@Override
public void stateChanged(ChangeEvent e) {
if (_ship == null) return;
_ship.EntityShip.setSpeed((int)spinnerSpeed.getValue());
}
});
spinnerWeight.addChangeListener(new ChangeListener() {
@Override
public void stateChanged(ChangeEvent e) {
if (_ship == null) return;
_ship.EntityShip.setWeight((int)spinnerWeight.getValue());
}
});
checkBoxPipes.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
if (_ship == null) return;
if (_ship.EntityShip instanceof EntityWarmlyShip warmlyShip) {
warmlyShip.setShipPipes(checkBoxPipes.isSelected());
panelObject.repaint();
}
}
});
checkBoxFuelTank.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
if (_ship == null) return;
if (_ship.EntityShip instanceof EntityWarmlyShip warmlyShip) {
warmlyShip.setFuelTank(checkBoxFuelTank.isSelected());
panelObject.repaint();
}
}
});
labelShip.setBackground(Color.WHITE);
labelShip.setBorder(BorderFactory.createLineBorder(Color.BLACK, 2));
labelWarmlyShip.setBackground(Color.WHITE);
labelWarmlyShip.setBorder(BorderFactory.createLineBorder(Color.BLACK, 2));
labelBodyColor.setBorder(BorderFactory.createLineBorder(Color.BLACK, 2));
labelAdditionalColor.setBorder(BorderFactory.createLineBorder(Color.BLACK, 2));
labelSolidDeck.setBorder(BorderFactory.createLineBorder(Color.BLACK, 2));
labelBeamsDeck.setBorder(BorderFactory.createLineBorder(Color.BLACK, 2));
labelWindowDeck.setBorder(BorderFactory.createLineBorder(Color.BLACK, 2));
MouseAdapter labelObjectsMouseDown = new MouseAdapter() {
@Override
public void mousePressed(MouseEvent e) {
((JLabel) e.getComponent()).getTransferHandler().exportAsDrag(((JLabel) e.getComponent()), e, TransferHandler.COPY);
}
};
TransferHandler labelObjectsTransferHandler = new TransferHandler() {
@Override
public int getSourceActions(JComponent c) {
return TransferHandler.COPY;
}
@Override
protected Transferable createTransferable(JComponent c) {
return new StringSelection(((JLabel) c).getText());
}
};
labelShip.addMouseListener(labelObjectsMouseDown);
labelShip.setTransferHandler(labelObjectsTransferHandler);
labelWarmlyShip.addMouseListener(labelObjectsMouseDown);
labelWarmlyShip.setTransferHandler(labelObjectsTransferHandler);
MouseAdapter labelDecksMouseDown = new MouseAdapter() {
@Override
public void mousePressed(MouseEvent e) {
((JLabel) e.getComponent()).getTransferHandler().exportAsDrag(((JLabel) e.getComponent()), e, TransferHandler.COPY);
}
};
labelSolidDeck.addMouseListener(labelDecksMouseDown);
labelBeamsDeck.addMouseListener(labelDecksMouseDown);
labelWindowDeck.addMouseListener(labelDecksMouseDown);
labelSolidDeck.setTransferHandler(new TransferHandler() {
@Override
public int getSourceActions(JComponent c) {return TransferHandler.COPY;}
@Override
protected Transferable createTransferable(JComponent c) {
return new DecksTransferable(new DrawingDecksType1());
}
});
labelBeamsDeck.setTransferHandler(new TransferHandler() {
@Override
public int getSourceActions(JComponent c) {return TransferHandler.COPY;}
@Override
protected Transferable createTransferable(JComponent c) {
return new DecksTransferable(new DrawingDecksType2());
}
});
labelWindowDeck.setTransferHandler(new TransferHandler() {
@Override
public int getSourceActions(JComponent c) {return TransferHandler.COPY;}
@Override
protected Transferable createTransferable(JComponent c) {
return new DecksTransferable(new DrawingDecksType3());
}
});
panelObject.setTransferHandler(new TransferHandler() {
@Override
public boolean canImport(TransferHandler.TransferSupport support) {
return support.isDataFlavorSupported(DataFlavor.stringFlavor)
|| support.isDataFlavorSupported(DecksTransferable.decksDataFlavor);
}
@Override
public boolean importData(TransferHandler.TransferSupport support) {
if (canImport(support)) {
try {
String data = (String) support.getTransferable().getTransferData(DataFlavor.stringFlavor);
switch (data) {
case "Ship":
_ship = new DrawingShip((int) spinnerSpeed.getValue(), (int) spinnerWeight.getValue(),
Color.WHITE);
break;
case "WarmlyShip":
_ship = new DrawingWarmlyShip((int) spinnerSpeed.getValue(), (int) spinnerWeight.getValue(),
Color.WHITE, Color.BLACK, checkBoxPipes.isSelected(), checkBoxFuelTank.isSelected());
break;
}
if (_ship != null) {
_ship.SetPictureSize(155,155);
_ship.SetPosition(5,10);
}
else return false;
}
catch (UnsupportedFlavorException | IOException e) {}
try {
IDifferentDecks decks =
(IDifferentDecks) support.getTransferable().getTransferData(DecksTransferable.decksDataFlavor);
_ship.drawingDecks = decks;
_ship.drawingDecks.setNumberOfDecks((int) spinnerNumberOfDecks.getValue());
}catch (UnsupportedFlavorException | IOException e) {}
panelObject.repaint();
return true;
}
return false;
}
});
JPanel[] colorPanels = {
panelColorRed,
panelColorGreen,
panelColorBlue,
panelColorYellow,
panelColorWhite,
panelColorBlack,
panelColorGray,
panelColorCyan,
};
panelColorRed.setBackground(Color.RED);
panelColorGreen.setBackground(Color.GREEN);
panelColorBlue.setBackground(Color.BLUE);
panelColorYellow.setBackground(Color.YELLOW);
panelColorWhite.setBackground(Color.WHITE);
panelColorBlack.setBackground(Color.BLACK);
panelColorGray.setBackground(Color.GRAY);
panelColorCyan.setBackground(Color.CYAN);
MouseAdapter colorMouseDown = new MouseAdapter() {
@Override
public void mousePressed(MouseEvent e) {
((JPanel) e.getComponent()).getTransferHandler().exportAsDrag(((JPanel) e.getComponent()), e, TransferHandler.COPY);
}
};
for (var panelColor : colorPanels) {
panelColor.addMouseListener(colorMouseDown);
panelColor.setTransferHandler(new ColorTransferHandler());
}
labelBodyColor.setTransferHandler(new TransferHandler() {
@Override
public boolean canImport(TransferHandler.TransferSupport support) {
return support.isDataFlavorSupported(ColorTransferable.colorDataFlavor);
}
@Override
public boolean importData(TransferSupport support) {
try {
Color color = (Color) support.getTransferable().getTransferData(ColorTransferable.colorDataFlavor);
if (_ship == null) return false;
_ship.EntityShip.setBodyColor(color);
return true;
} catch (UnsupportedFlavorException | IOException e) {
e.printStackTrace();
}
return false;
}
});
labelAdditionalColor.setTransferHandler(new TransferHandler() {
@Override
public boolean canImport(TransferHandler.TransferSupport support) {
if (!(_ship instanceof DrawingWarmlyShip)) return false;
return support.isDataFlavorSupported(ColorTransferable.colorDataFlavor);
}
@Override
public boolean importData(TransferSupport support) {
try {
Color color = (Color) support.getTransferable().getTransferData(ColorTransferable.colorDataFlavor);
if (_ship == null) return false;
if (_ship.EntityShip instanceof EntityWarmlyShip warmlyShip) {
warmlyShip.setAdditionalColor(color);
labelColor.setBackground(color);
return true;
}
return false;
} catch (UnsupportedFlavorException | IOException e) {
e.printStackTrace();
}
return false;
}
});
buttonAdd.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
if (_ship == null) return;
DrawingShip copyShip;
if (_ship instanceof DrawingWarmlyShip)
copyShip = new DrawingWarmlyShip((EntityWarmlyShip) _ship.EntityShip, _ship.drawingDecks);
else
copyShip = new DrawingShip(_ship.EntityShip, _ship.drawingDecks);
try {
company._collection.Insert(copyShip);
FormShipCollection.canvasShow();
logger.info("Добавлен объект: " + GetDataForSave(copyShip));
} catch (CollectionOverflowException ex) {
loggerErrow.warn(ex.toString());
JOptionPane.showMessageDialog(null, "Коллекция переполнена");
} catch (Exception ex) {
loggerErrow.fatal("Ошибка при добавлении объекта с формы config");
}
dispose();
}
});
buttonCansel.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
dispose();
}
});
labelSpeed.setBounds(10, 17, 50, 15);
labelWeight.setBounds(10,43, 50, 15);
labelNumberOfDecks.setBounds(10, 68, 50, 15);
labelShip.setBounds(10,150,70,30);
labelWarmlyShip.setBounds(10,190,70,30);
labelColor.setBounds(170,10,30,15);
labelBodyColor.setBounds(500,5,75, 40);
labelAdditionalColor.setBounds(580,5,75,40);
labelSolidDeck.setBounds(120, 210, 100, 40);
labelBeamsDeck.setBounds(230, 210, 100,40);
labelWindowDeck.setBounds(340,210,100,40);
spinnerSpeed.setBounds(60,15, 60,20);
spinnerWeight.setBounds(60,40, 60,20);
spinnerNumberOfDecks.setBounds(60, 65,60,20);
checkBoxPipes.setBounds(8,85,150,20);
checkBoxFuelTank.setBounds(8,105,150,20);
panelObject.setBounds(500,50,160,150);
panelColorRed.setBounds(170, 30, 40, 40);
panelColorGreen.setBounds(220, 30, 40,40);
panelColorBlue.setBounds(270,30,40,40);
panelColorYellow.setBounds(320,30,40,40);
panelColorWhite.setBounds(170, 80,40,40);
panelColorBlack.setBounds(220,80,40,40);
panelColorGray.setBounds(270,80,40,40);
panelColorCyan.setBounds(320,80,40,40);
buttonAdd.setBounds(500, 210, 70, 40);
buttonCansel.setBounds(585, 210, 70, 40);
setSize(dimension.width, dimension.height);
setLayout(null);
add(labelSpeed);
add(labelWeight);
add(labelNumberOfDecks);
add(labelShip);
add(labelWarmlyShip);
add(labelColor);
add(labelBodyColor);
add(labelAdditionalColor);
add(labelSolidDeck);
add(labelSolidDeck);
add(labelBeamsDeck);
add(labelWindowDeck);
add(spinnerSpeed);
add(spinnerWeight);
add(spinnerNumberOfDecks);
add(checkBoxPipes);
add(checkBoxFuelTank);
add(panelObject);
add(panelColorRed);
add(panelColorGreen);
add(panelColorBlue);
add(panelColorYellow);
add(panelColorWhite);
add(panelColorBlack);
add(panelColorGray);
add(panelColorCyan);
add(buttonAdd);
add(buttonCansel);
setVisible(true);
}
public void setCompany(AbstractCompany company) {
this.company = company;
}
private class Canvas extends JComponent {
public Canvas() {
}
public void paintComponent(Graphics g) {
if (_ship == null) {
return;
}
super.paintComponents(g);
Graphics2D g2d = (Graphics2D) g;
_ship.DrawTransport(g2d);
super.repaint();
}
}
private class ColorTransferable implements Transferable {
private Color color;
private static final DataFlavor colorDataFlavor = new DataFlavor(Color.class, "Color");
public ColorTransferable(Color color) {
this.color = color;
}
@Override
public DataFlavor[] getTransferDataFlavors() {
return new DataFlavor[]{colorDataFlavor};
}
@Override
public boolean isDataFlavorSupported(DataFlavor flavor) {
return colorDataFlavor.equals(flavor);
}
@Override
public Object getTransferData(DataFlavor flavor) throws UnsupportedFlavorException {
if (isDataFlavorSupported(flavor)) {
return color;
} else {
throw new UnsupportedFlavorException(flavor);
}
}
}
private class ColorTransferHandler extends TransferHandler {
@Override
public int getSourceActions(JComponent c) {
return TransferHandler.COPY;
}
@Override
protected Transferable createTransferable(JComponent c) {
return new ColorTransferable(c.getBackground());
}
}
private class DecksTransferable implements Transferable {
private IDifferentDecks decks;
private static final DataFlavor decksDataFlavor = new DataFlavor(IDifferentDecks.class, "Decks");
public DecksTransferable(IDifferentDecks decks) {
this.decks = decks;
}
@Override
public DataFlavor[] getTransferDataFlavors() {
return new DataFlavor[]{decksDataFlavor};
}
@Override
public boolean isDataFlavorSupported(DataFlavor flavor) {
return flavor.equals(decksDataFlavor);
}
@Override
public Object getTransferData(DataFlavor flavor) throws UnsupportedFlavorException {
if (isDataFlavorSupported(flavor)) {
return decks;
} else {
throw new UnsupportedFlavorException(flavor);
}
}
}
}

View File

@ -0,0 +1,154 @@
import DrawingShip.CanvasWarmlyShip;
import DrawingShip.DirectionType;
import DrawingShip.DrawingShip;
import MovementStrategy.*;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ComponentAdapter;
import java.awt.event.ComponentEvent;
public class FormWarmlyShip extends JFrame {
private String title;
private Dimension dimension;
private int Width, Height;
public CanvasWarmlyShip canvasWarmlyShip = new CanvasWarmlyShip();
private JButton UpButton = new JButton();
private JButton DownButton = new JButton();;
private JButton LeftButton = new JButton();;
private JButton RightButton = new JButton();
private AbstractStrategy _strategy;
private JComboBox ComboBoxStrategy = new JComboBox(new String[]{"К центру", "К краю"});
private JButton ButtonStrategy = new JButton("Шаг");
public FormWarmlyShip(String title, Dimension dimension) {
this.title = title;
this.dimension = dimension;
}
public void Init(DrawingShip ship) {
setTitle(title);
setMinimumSize(dimension);
Width = getWidth() - 10;
Height = getHeight() - 34;
ComboBoxStrategy.setEnabled(true);
_strategy = null;
canvasWarmlyShip._drawingShip = ship;
Icon iconUp = new ImageIcon("src\\images\\up.jpg");
UpButton.setIcon(iconUp);
UpButton.setName("UP");
DownButton.setName("DOWN");
Icon iconDown = new ImageIcon("src\\images\\down.jpg");
DownButton.setIcon(iconDown);
LeftButton.setName("LEFT");
Icon iconLeft = new ImageIcon("src\\images\\left.jpg");
LeftButton.setIcon(iconLeft);
RightButton.setName("RIGHT");
Icon iconRight = new ImageIcon("src\\images\\right.jpg");
RightButton.setIcon(iconRight);
ButtonStrategy.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
if (canvasWarmlyShip._drawingShip == null) return;
if (ComboBoxStrategy.isEnabled())
{
int index = ComboBoxStrategy.getSelectedIndex();
switch(index)
{
case 0:
_strategy = new MoveToCenter();
break;
case 1:
_strategy = new MoveToBorder();
break;
default:
_strategy = null;
break;
};
if (_strategy == null)
{
return;
}
_strategy.SetData(new MoveableShip(canvasWarmlyShip._drawingShip), Width, Height);
}
if (_strategy == null)
{
return;
}
ComboBoxStrategy.setEnabled(false);
_strategy.MakeStep();
if (_strategy.GetStatus() == StrategyStatus.Finish)
{
ComboBoxStrategy.setEnabled(true);
_strategy = null;
}
}
});
ActionListener actionListener = new ActionListener() {
@Override
public void actionPerformed(ActionEvent event) {
if (canvasWarmlyShip._drawingShip == null) return;
boolean result = false;
switch ((((JButton)(event.getSource())).getName())) {
case "UP":
result = canvasWarmlyShip._drawingShip.MoveTransport(DirectionType.Up);
break;
case "DOWN":
result = canvasWarmlyShip._drawingShip.MoveTransport(DirectionType.Down);
break;
case "LEFT":
result = canvasWarmlyShip._drawingShip.MoveTransport(DirectionType.Left);
break;
case "RIGHT":
result = canvasWarmlyShip._drawingShip.MoveTransport(DirectionType.Right);
break;
}
if (result) {
canvasWarmlyShip.repaint();
}
}
};
UpButton.addActionListener(actionListener);
DownButton.addActionListener(actionListener);
LeftButton.addActionListener(actionListener);
RightButton.addActionListener(actionListener);
setSize(dimension.width,dimension.height);
setLayout(null);
canvasWarmlyShip.setBounds(0,0, getWidth(), getHeight());
UpButton.setBounds(getWidth() - 140, getHeight() - 160, 50, 50);
DownButton.setBounds(getWidth() - 140, getHeight() - 100, 50, 50);
RightButton.setBounds(getWidth() - 80, getHeight() - 100, 50, 50);
LeftButton.setBounds(getWidth() - 200, getHeight() - 100, 50, 50);
ComboBoxStrategy.setBounds(getWidth() - 170, 10, 140, 35);
ButtonStrategy.setBounds(getWidth() - 130, 55, 100, 25);
add(UpButton);
add(DownButton);
add(RightButton);
add(LeftButton);
add(ComboBoxStrategy);
add(ButtonStrategy);
add(canvasWarmlyShip);
setVisible(true);
//обработка события изменения размеров окна
addComponentListener(new ComponentAdapter() {
public void componentResized(ComponentEvent e) {
Width = getWidth() - 10;
Height = getHeight() - 34;
if (canvasWarmlyShip._drawingShip != null)
canvasWarmlyShip._drawingShip.SetPictureSize(Width, Height);
canvasWarmlyShip.setBounds(0,0, getWidth(), getHeight());
UpButton.setBounds(getWidth() - 140, getHeight() - 160, 50, 50);
DownButton.setBounds(getWidth() - 140, getHeight() - 100, 50, 50);
RightButton.setBounds(getWidth() - 80, getHeight() - 100, 50, 50);
LeftButton.setBounds(getWidth() - 200, getHeight() - 100, 50, 50);
ComboBoxStrategy.setBounds(getWidth() - 170, 10, 140, 35);
ButtonStrategy.setBounds(getWidth() - 130, 55, 100, 25);
}
});
}
}

View File

@ -1,5 +1,13 @@
import org.apache.logging.log4j.LogManager;
import java.awt.*;
public class Main { public class Main {
public static void main(String[] args) { public static void main(String[] args) {
System.out.println("Hello world!"); org.apache.logging.log4j.Logger logger1 = LogManager.getLogger("logging.file1");
org.apache.logging.log4j.Logger logger2 = LogManager.getLogger("logging.file2");
FormShipCollection form = new FormShipCollection("Коллекция судов",
new Dimension(1100, 648), logger1, logger2);
form.Init();
} }
} }

View File

@ -0,0 +1,56 @@
package MovementStrategy;
public abstract class AbstractStrategy {
private IMoveableObjects _moveableObject;
private StrategyStatus _state = StrategyStatus.NotInit;
public int FieldWidth;
public int FieldHeight;
public StrategyStatus GetStatus() {return _state;}
public void SetData(IMoveableObjects moveableObjects, int width, int height)
{
if (moveableObjects == null)
{
_state = StrategyStatus.NotInit;
return;
}
_state = StrategyStatus.InProgress;
_moveableObject = moveableObjects;
FieldWidth = width;
FieldHeight = height;
}
public void MakeStep()
{
if (_state != StrategyStatus.InProgress) return;
if (IsTargetDestinaion())
{
_state = StrategyStatus.Finish;
return;
}
MoveToTarget();
}
protected boolean MoveLeft() {return MoveTo(MovementDirection.Left);};
protected boolean MoveRight() {return MoveTo(MovementDirection.Right);};
protected boolean MoveUp() {return MoveTo(MovementDirection.Up);};
protected boolean MoveDown() {return MoveTo(MovementDirection.Down);};
protected ObjectParameters GetObjectParameters() {return _moveableObject.GetObjectPosition();};
protected Integer GetStep()
{
if (_state != StrategyStatus.InProgress)
{
return null;
}
return _moveableObject.GetStep();
}
protected abstract void MoveToTarget();
protected abstract boolean IsTargetDestinaion();
private boolean MoveTo(MovementDirection movementDirection)
{
if (_state != StrategyStatus.InProgress)
{
return false;
}
boolean stateTryMoveObject = _moveableObject.TryMoveObject(movementDirection);
if (stateTryMoveObject) return stateTryMoveObject;
return false;
}
}

View File

@ -0,0 +1,7 @@
package MovementStrategy;
public interface IMoveableObjects {
ObjectParameters GetObjectPosition();
int GetStep();
boolean TryMoveObject(MovementDirection direction);
}

View File

@ -0,0 +1,27 @@
package MovementStrategy;
public class MoveToBorder extends AbstractStrategy{
@Override
protected boolean IsTargetDestinaion() {
ObjectParameters objParams = GetObjectParameters();
if (objParams == null)
{
return false;
}
return objParams.RightBorder + GetStep() >= FieldWidth-GetStep() &&
objParams.DownBorder + GetStep() >= FieldHeight-GetStep();
}
@Override
protected void MoveToTarget() {
ObjectParameters objParams = GetObjectParameters();
if (objParams == null)
{
return;
}
//реализация в правый нижний угол
int x = objParams.RightBorder;
if (x + GetStep() < FieldWidth) MoveRight();
int y = objParams.DownBorder;
if (y + GetStep() < FieldHeight) MoveDown();
}
}

View File

@ -0,0 +1,48 @@
package MovementStrategy;
public class MoveToCenter extends AbstractStrategy{
@Override
protected boolean IsTargetDestinaion() {
ObjectParameters objParams = GetObjectParameters();
if (objParams == null)
{
return false;
}
return objParams.ObjectMiddleHorizontal - GetStep() <= FieldWidth / 2 &&
objParams.ObjectMiddleHorizontal + GetStep() >= FieldWidth / 2 &&
objParams.ObjectMiddleVertical - GetStep() <= FieldHeight / 2 &&
objParams.ObjectMiddleVertical + GetStep() >= FieldHeight /2;
}
@Override
protected void MoveToTarget() {
ObjectParameters objParams = GetObjectParameters();
if (objParams == null)
{
return;
}
int diffX = objParams.ObjectMiddleHorizontal - FieldWidth / 2;
if (Math.abs(diffX) > GetStep())
{
if (diffX > 0)
{
MoveLeft();
}
else
{
MoveRight();
}
}
int diffY = objParams.ObjectMiddleVertical - FieldHeight / 2;
if (Math.abs(diffY) > GetStep())
{
if (diffY > 0)
{
MoveUp();
}
else
{
MoveDown();
}
}
}
}

View File

@ -0,0 +1,46 @@
package MovementStrategy;
import DrawingShip.CanvasFormShipCollection;
import DrawingShip.DirectionType;
import DrawingShip.DrawingShip;
import DrawingShip.CanvasWarmlyShip;
public class MoveableShip implements IMoveableObjects{
private CanvasWarmlyShip canvas = new CanvasWarmlyShip();
public MoveableShip(DrawingShip drawningship)
{
canvas._drawingShip = drawningship;
}
@Override
public ObjectParameters GetObjectPosition() {
if (canvas._drawingShip == null || canvas._drawingShip.EntityShip == null ||
canvas._drawingShip.GetPosX() == null || canvas._drawingShip.GetPosY() == null)
{
return null;
}
return new ObjectParameters(canvas._drawingShip.GetPosX(), canvas._drawingShip.GetPosY(),
canvas._drawingShip.GetWidth(), canvas._drawingShip.GetHeight());
}
@Override
public int GetStep() {
return (int)(canvas._drawingShip.EntityShip.Step);
}
@Override
public boolean TryMoveObject(MovementDirection direction) {
if (canvas._drawingShip == null || canvas._drawingShip.EntityShip == null)
{
return false;
}
return canvas._drawingShip.MoveTransport(GetDirectionType(direction));
}
private static DirectionType GetDirectionType(MovementDirection direction)
{
switch (direction) {
case MovementDirection.Left: return DirectionType.Left;
case MovementDirection.Right: return DirectionType.Right;
case MovementDirection.Up: return DirectionType.Up;
case MovementDirection.Down: return DirectionType.Down;
default: return DirectionType.Unknow;
}
}
}

View File

@ -0,0 +1,9 @@
package MovementStrategy;
public enum MovementDirection {
Up,
Down,
Left,
Right
}

View File

@ -0,0 +1,27 @@
package MovementStrategy;
public class ObjectParameters {
private int _x;
private int _y;
private int _width;
private int _height;
public int LeftBorder = _x;
public int TopBorder = _y;
public int RightBorder = _x + _width;
public int DownBorder = _y + _height;
public int ObjectMiddleHorizontal = _x + _width / 2;
public int ObjectMiddleVertical = _y + _height / 2;
public ObjectParameters(int x, int y, int width, int height)
{
_x = x;
_y = y;
_width = width;
_height = height;
LeftBorder = _x;
TopBorder = _y;
RightBorder = _x + _width;
DownBorder = _y + _height;
ObjectMiddleHorizontal = _x + _width / 2;
ObjectMiddleVertical = _y + _height / 2;
}
}

View File

@ -0,0 +1,7 @@
package MovementStrategy;
public enum StrategyStatus {
NotInit,
InProgress,
Finish
}

Binary file not shown.

After

Width:  |  Height:  |  Size: 141 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 139 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.8 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 141 KiB

26
WarmlyShip/src/log4j2.xml Normal file
View File

@ -0,0 +1,26 @@
<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="WARN">
<Appenders>
<Console name="Console" target="SYSTEM_OUT">
<PatternLayout pattern="%-5level %msg (дата - %d{HH:mm:ss})%n"/>
</Console>
<File name="file1" fileName="log1.log">
<PatternLayout pattern="%d{HH:mm:ss} %-5level %msg%n"/>
</File>
<File name="file2" fileName="log2.log">
<PatternLayout pattern="%-5level %msg (дата - %d{HH:mm:ss})%n"/>
</File>
</Appenders>
<Loggers>
<Root level="Debug">
<AppenderRef ref="Console"/>
</Root>
<Logger name="logging.file1" level="info" additivity="true">
<AppenderRef ref="file1" level="INFO"/>
</Logger>
<Logger name="logging.file2" level="info" additivity="true">
<AppenderRef ref="file2" level="INFO"/>
</Logger>
</Loggers>
</Configuration>