Лабараторная работа №7 1

This commit is contained in:
IlyasValiulov 2024-05-10 12:11:23 +04:00
parent 1b17183c14
commit bc5cce4b55
16 changed files with 314 additions and 129 deletions

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

@ -1,6 +1,8 @@
package CollectionGenericObjects; package CollectionGenericObjects;
import DrawingShip.DrawingShip; import DrawingShip.DrawingShip;
import Exceptions.ObjectNotFoundException;
import Exceptions.PositionOutOfCollectionException;
import java.awt.*; import java.awt.*;
@ -21,8 +23,7 @@ public abstract class AbstractCompany {
_collection.SetMaxCount(GetMaxCount()); _collection.SetMaxCount(GetMaxCount());
} }
//перегрузка операторов в джаве не возможна //перегрузка операторов в джаве не возможна
public DrawingShip GetRandomObject() public DrawingShip GetRandomObject() throws PositionOutOfCollectionException, ObjectNotFoundException {
{
return _collection.Get((int)(Math.random()*GetMaxCount() + 0)); return _collection.Get((int)(Math.random()*GetMaxCount() + 0));
} }
public void SetPosition() public void SetPosition()

View File

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

View File

@ -1,5 +1,8 @@
package CollectionGenericObjects; package CollectionGenericObjects;
import Exceptions.CollectionOverflowException;
import Exceptions.PositionOutOfCollectionException;
import java.util.*; import java.util.*;
public class ListGenericObjects<T> implements ICollectionGenericObjects<T> { public class ListGenericObjects<T> implements ICollectionGenericObjects<T> {
@ -23,22 +26,19 @@ public class ListGenericObjects<T> implements ICollectionGenericObjects<T> {
return collectionType; return collectionType;
} }
@Override @Override
public T Get(int position) public T Get(int position) throws PositionOutOfCollectionException {
{ if (position >= getCount() || position < 0) throw new PositionOutOfCollectionException(position);
if (position >= getCount() || position < 0) return null;
return _collection.get(position); return _collection.get(position);
} }
@Override @Override
public int Insert(T obj) public int Insert(T obj) throws CollectionOverflowException {
{ if (getCount() == _maxCount) throw new CollectionOverflowException(getCount());
if (getCount() == _maxCount) return -1;
_collection.add(obj); _collection.add(obj);
return getCount(); return getCount();
} }
@Override @Override
public T Remove(int position) public T Remove(int position) throws PositionOutOfCollectionException {
{ if (position >= getCount() || position < 0) throw new PositionOutOfCollectionException(position);
if (position >= getCount() || position < 0) return null;
T obj = _collection.get(position); T obj = _collection.get(position);
_collection.remove(position); _collection.remove(position);
return obj; return obj;

View File

@ -1,6 +1,9 @@
package CollectionGenericObjects; package CollectionGenericObjects;
import DrawingShip.DrawingShip; import DrawingShip.DrawingShip;
import Exceptions.CollectionOverflowException;
import Exceptions.ObjectNotFoundException;
import Exceptions.PositionOutOfCollectionException;
import java.lang.reflect.Array; import java.lang.reflect.Array;
import java.util.*; import java.util.*;
@ -27,7 +30,7 @@ public class MassiveGenericObjects<T> implements ICollectionGenericObjects<T>{
return collectionType; return collectionType;
} }
@Override @Override
public int Insert(T obj) { public int Insert(T obj) throws CollectionOverflowException {
int index = 0; int index = 0;
while (index < getCount()) while (index < getCount())
{ {
@ -38,19 +41,21 @@ public class MassiveGenericObjects<T> implements ICollectionGenericObjects<T>{
} }
++index; ++index;
} }
return -1; throw new CollectionOverflowException(Count);
} }
@Override @Override
public T Remove(int position) { public T Remove(int position) throws PositionOutOfCollectionException, ObjectNotFoundException {
if (position >= getCount() || position < 0) if (position >= getCount() || position < 0)
return null; throw new PositionOutOfCollectionException(position);
if (_collection[position] == null) throw new ObjectNotFoundException(position);
T obj = (T) _collection[position]; T obj = (T) _collection[position];
_collection[position] = null; _collection[position] = null;
return obj; return obj;
} }
@Override @Override
public T Get(int position) { public T Get(int position) throws PositionOutOfCollectionException, ObjectNotFoundException {
if (position >= getCount() || position < 0) return null; if (position >= getCount() || position < 0) throw new PositionOutOfCollectionException(position);
if (_collection[position] == null) throw new ObjectNotFoundException(position);
return (T) _collection[position]; return (T) _collection[position];
} }
@Override @Override

View File

@ -31,10 +31,13 @@ public class ShipPortService extends AbstractCompany{
int curWidth = width - 1; int curWidth = width - 1;
int curHeight = 0; int curHeight = 0;
for (int i = 0; i < (_collection.getCount()); i++) { for (int i = 0; i < (_collection.getCount()); i++) {
if (_collection.Get(i) != null) { try {
_collection.Get(i).SetPictureSize(_pictureWidth, _pictureHeight); if (_collection.Get(i) != null) {
_collection.Get(i).SetPosition(_placeSizeWidth * curWidth + 20, curHeight * _placeSizeHeight + 4); _collection.Get(i).SetPictureSize(_pictureWidth, _pictureHeight);
_collection.Get(i).SetPosition(_placeSizeWidth * curWidth + 20, curHeight * _placeSizeHeight + 4);
}
} }
catch (Exception ex) {}
if (curWidth > 0) if (curWidth > 0)
curWidth--; curWidth--;
else { else {

View File

@ -2,6 +2,9 @@ package CollectionGenericObjects;
import DrawingShip.DrawingShip; import DrawingShip.DrawingShip;
import DrawingShip.ExtentionDrawningShip; import DrawingShip.ExtentionDrawningShip;
import Exceptions.CollectionOverflowException;
import Exceptions.ObjectNotFoundException;
import Exceptions.PositionOutOfCollectionException;
import java.io.*; import java.io.*;
import java.util.*; import java.util.*;
@ -37,7 +40,7 @@ public class StorageCollection<T extends DrawingShip> {
return null; return null;
} }
//дополнительное задание номер 1 //дополнительное задание номер 1
public T Get(String name, int position){ public T Get(String name, int position) throws ObjectNotFoundException, PositionOutOfCollectionException {
if(_storages.containsKey(name)) if(_storages.containsKey(name))
return _storages.get(name).Remove(position); return _storages.get(name).Remove(position);
return null; return null;
@ -48,8 +51,8 @@ public class StorageCollection<T extends DrawingShip> {
private String _separatorForKeyValue = "\\|"; private String _separatorForKeyValue = "\\|";
private String _separatorItemsS = ";"; private String _separatorItemsS = ";";
private String _separatorItems = "\\;"; private String _separatorItems = "\\;";
public boolean SaveData(String filename) { public void SaveData(String filename) throws Exception {
if (_storages.isEmpty()) return false; if (_storages.isEmpty()) throw new Exception("В хранилище отсутствуют коллекции для сохранения");
File file = new File(filename); File file = new File(filename);
if (file.exists()) file.delete(); if (file.exists()) file.delete();
try { try {
@ -78,10 +81,9 @@ public class StorageCollection<T extends DrawingShip> {
} catch (IOException e) { } catch (IOException e) {
throw new RuntimeException(e); throw new RuntimeException(e);
} }
return true;
} }
public boolean SaveOneCollection(String filename, String name) { public void SaveOneCollection(String filename, String name) throws Exception {
if (_storages.isEmpty()) return false; if (_storages.isEmpty()) throw new Exception("В хранилище отсутствуют коллекции для сохранения");
File file = new File(filename); File file = new File(filename);
if (file.exists()) file.delete(); if (file.exists()) file.delete();
try { try {
@ -108,15 +110,14 @@ public class StorageCollection<T extends DrawingShip> {
} catch (IOException e) { } catch (IOException e) {
throw new RuntimeException(e); throw new RuntimeException(e);
} }
return true;
} }
public boolean LoadData(String filename) { public void LoadData(String filename) throws Exception {
File file = new File(filename); File file = new File(filename);
if (!file.exists()) return false; if (!file.exists()) throw new Exception("Файл не существует");
try (BufferedReader fs = new BufferedReader(new FileReader(filename))) { try (BufferedReader fs = new BufferedReader(new FileReader(filename))) {
String s = fs.readLine(); String s = fs.readLine();
if (s == null || s.isEmpty() || !s.startsWith(_collectionKey)) if (s == null || s.isEmpty() || !s.startsWith(_collectionKey))
return false; throw new Exception("В файле нет данных или данные неверные");
_storages.clear(); _storages.clear();
s = ""; s = "";
while ((s = fs.readLine()) != null) { while ((s = fs.readLine()) != null) {
@ -127,56 +128,68 @@ public class StorageCollection<T extends DrawingShip> {
ICollectionGenericObjects<T> collection = CreateCollection(record[1]); ICollectionGenericObjects<T> collection = CreateCollection(record[1]);
if (collection == null) if (collection == null)
{ {
return false; throw new Exception("Не удалось создать коллекцию");
} }
collection.SetMaxCount(Integer.parseInt(record[2])); collection.SetMaxCount(Integer.parseInt(record[2]));
String[] set = record[3].split(_separatorItems); String[] set = record[3].split(_separatorItems);
for (String elem : set) { for (String elem : set) {
DrawingShip ship = ExtentionDrawningShip.CreateDrawingShip(elem); try
if (collection.Insert((T) ship) == -1)
{ {
return false; 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); _storages.put(record[0], collection);
} }
return true;
} }
catch (IOException e) { catch (IOException e) {
throw new RuntimeException(e); throw new RuntimeException(e);
} }
} }
public boolean LoadOneCollection(String filename) { public void LoadOneCollection(String filename) throws Exception {
File file = new File(filename); File file = new File(filename);
if (!file.exists()) return false; if (!file.exists()) throw new Exception("Файл не существует");
try (BufferedReader fs = new BufferedReader(new FileReader(filename))) { try (BufferedReader fs = new BufferedReader(new FileReader(filename))) {
String s = fs.readLine(); String s = fs.readLine();
if (s == null || s.isEmpty() || !s.startsWith(_collectionName)) if (s == null || s.isEmpty() || !s.startsWith(_collectionName))
return false; throw new Exception("В файле нет данных или данные неверные");
if (_storages.containsKey(s)) { if (_storages.containsKey(s)) {
_storages.get(s).ClearCollection(); _storages.get(s).ClearCollection();
} }
s = fs.readLine(); s = fs.readLine();
String[] record = s.split(_separatorForKeyValue); String[] record = s.split(_separatorForKeyValue);
if (record.length != 4) { if (record.length != 4) {
return false; throw new Exception("Неверные данные");
} }
ICollectionGenericObjects<T> collection = CreateCollection(record[1]); ICollectionGenericObjects<T> collection = CreateCollection(record[1]);
if (collection == null) if (collection == null)
{ {
return false; throw new Exception("Не удалось создать коллекцию");
} }
collection.SetMaxCount(Integer.parseInt(record[2])); collection.SetMaxCount(Integer.parseInt(record[2]));
String[] set = record[3].split(_separatorItems); String[] set = record[3].split(_separatorItems);
for (String elem : set) { for (String elem : set) {
DrawingShip ship = ExtentionDrawningShip.CreateDrawingShip(elem); try
if (collection.Insert((T) ship) == -1)
{ {
return false; 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); _storages.put(record[0], collection);
return true;
} }
catch (IOException e) { catch (IOException e) {
throw new RuntimeException(e); throw new RuntimeException(e);

View File

@ -19,12 +19,14 @@ public class CanvasFormShipCollection<T> extends JComponent
} }
company.DrawBackgound(g); company.DrawBackgound(g);
for (int i = 0; i < company._collection.getCount(); i++) { for (int i = 0; i < company._collection.getCount(); i++) {
try {
Graphics2D g2d = (Graphics2D) g; Graphics2D g2d = (Graphics2D) g;
T obj = (T)company._collection.Get(i); T obj = (T) company._collection.Get(i);
if (obj instanceof DrawingShip) { if (obj instanceof DrawingShip) {
((DrawingShip) obj).DrawTransport(g2d); ((DrawingShip) obj).DrawTransport(g2d);
}
} }
catch (Exception ex) {}
} }
super.repaint(); super.repaint();
} }

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

@ -9,6 +9,7 @@ import DrawingShip.DrawingWarmlyShip;
import DrawingShip.CanvasWarmlyShip; import DrawingShip.CanvasWarmlyShip;
import Entities.EntityShip; import Entities.EntityShip;
import Entities.EntityWarmlyShip; import Entities.EntityWarmlyShip;
import Exceptions.CollectionOverflowException;
import javax.swing.*; import javax.swing.*;
import java.awt.*; import java.awt.*;
@ -16,6 +17,8 @@ import java.awt.event.ActionEvent;
import java.awt.event.ActionListener; import java.awt.event.ActionListener;
import java.util.Random; import java.util.Random;
import static DrawingShip.ExtentionDrawningShip.GetDataForSave;
public class FormAdditionalCollection extends JFrame { public class FormAdditionalCollection extends JFrame {
public DrawingShip drawingShip = null; public DrawingShip drawingShip = null;
private AbstractCompany company = null; private AbstractCompany company = null;
@ -25,9 +28,14 @@ public class FormAdditionalCollection extends JFrame {
private JButton buttonGenerate = new JButton("Создать"); private JButton buttonGenerate = new JButton("Создать");
private JList<String> listEntity = new JList<String>(); private JList<String> listEntity = new JList<String>();
private JList<String> listDecks = new JList<String>(); private JList<String> listDecks = new JList<String>();
public FormAdditionalCollection() { 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"); setTitle("Random ship");
setMinimumSize(new Dimension(650,310)); setMinimumSize(new Dimension(650,310));
this.logger = logger;
this.loggerErrow = logger2;
additionalCollection = new AdditionalCollections<EntityShip, IDifferentDecks>(3, additionalCollection = new AdditionalCollections<EntityShip, IDifferentDecks>(3,
(Class) EntityShip.class, (Class) IDifferentDecks.class); (Class) EntityShip.class, (Class) IDifferentDecks.class);
AddEntities(); AddEntities();
@ -35,31 +43,39 @@ public class FormAdditionalCollection extends JFrame {
buttonGenerate.addActionListener(new ActionListener() { buttonGenerate.addActionListener(new ActionListener() {
@Override @Override
public void actionPerformed(ActionEvent e) { public void actionPerformed(ActionEvent e) {
drawingShip = additionalCollection.CreateAdditionalCollectionShip(); try {
drawingShip.SetPictureSize(getWidth(), getHeight()); drawingShip = additionalCollection.CreateAdditionalCollectionShip();
drawingShip.SetPosition(50,50); drawingShip.SetPictureSize(getWidth(), getHeight());
canvasship._drawingShip = drawingShip; drawingShip.SetPosition(50, 50);
canvasship.repaint(); canvasship._drawingShip = drawingShip;
DrawingShip copyShip; canvasship.repaint();
if (drawingShip instanceof DrawingWarmlyShip) DrawingShip copyShip;
copyShip = new DrawingWarmlyShip((EntityWarmlyShip) drawingShip.EntityShip, drawingShip.drawingDecks); if (drawingShip instanceof DrawingWarmlyShip)
else copyShip = new DrawingWarmlyShip((EntityWarmlyShip) drawingShip.EntityShip, drawingShip.drawingDecks);
copyShip = new DrawingShip(drawingShip.EntityShip, drawingShip.drawingDecks); else
company._collection.Insert(copyShip); copyShip = new DrawingShip(drawingShip.EntityShip, drawingShip.drawingDecks);
FormShipCollection.canvasShow(); company._collection.Insert(copyShip);
FormShipCollection.canvasShow();
String[] data1 = new String[additionalCollection.CountEntities]; logger.info("Добавлен объект: " + GetDataForSave(copyShip));
for (int i = 0; i < additionalCollection.CountEntities; i++) { String[] data1 = new String[additionalCollection.CountEntities];
EntityShip entity = additionalCollection._collectionEntity[i]; for (int i = 0; i < additionalCollection.CountEntities; i++) {
data1[i] = ToString(entity); 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);
} }
String[] data2 = new String[additionalCollection.CountDecks]; catch (CollectionOverflowException ex) {
for (int i = 0; i < additionalCollection.CountDecks; i++) { loggerErrow.warn(ex.toString());
IDifferentDecks decks = additionalCollection._collectionDecks[i]; }
data2[i] = ToString(decks); catch (Exception ex) {
loggerErrow.fatal("Ошибка в выводу форме FormAdditionalCollection");
} }
listEntity.setListData(data1);
listDecks.setListData(data2);
} }
}); });
buttonGenerate.setBounds(450, 10, 100, 50); buttonGenerate.setBounds(450, 10, 100, 50);

View File

@ -1,7 +1,8 @@
import CollectionGenericObjects.*; import CollectionGenericObjects.*;
import DrawingShip.CanvasFormShipCollection; import DrawingShip.CanvasFormShipCollection;
import DrawingShip.DrawingShip; import DrawingShip.DrawingShip;
import DrawingShip.DrawingWarmlyShip; import Exceptions.ObjectNotFoundException;
import Exceptions.PositionOutOfCollectionException;
import javax.swing.*; import javax.swing.*;
import javax.swing.text.MaskFormatter; import javax.swing.text.MaskFormatter;
@ -9,9 +10,10 @@ import java.awt.*;
import java.awt.event.ActionEvent; import java.awt.event.ActionEvent;
import java.awt.event.ActionListener; import java.awt.event.ActionListener;
import java.text.ParseException; import java.text.ParseException;
import java.util.Random;
import java.util.Stack; import java.util.Stack;
import java.util.logging.Logger;
import static DrawingShip.ExtentionDrawningShip.GetDataForSave;
import static java.lang.Integer.parseInt; import static java.lang.Integer.parseInt;
public class FormShipCollection extends JFrame{ public class FormShipCollection extends JFrame{
@ -42,10 +44,17 @@ public class FormShipCollection extends JFrame{
private JMenuItem saveItem = new JMenuItem("Save"); private JMenuItem saveItem = new JMenuItem("Save");
private JMenuItem loadCollection = new JMenuItem("Load coll"); private JMenuItem loadCollection = new JMenuItem("Load coll");
private JMenuItem saveCollection = new JMenuItem("Save coll"); private JMenuItem saveCollection = new JMenuItem("Save coll");
public FormShipCollection(String title, Dimension dimension) { 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.title = title;
this.dimension = dimension; this.dimension = dimension;
this.logger = logger1;
logger.info("Форма загрузилась");
this.loggerErrow = logger2;
} }
public static void canvasShow() { public static void canvasShow() {
_company.SetPosition(); _company.SetPosition();
_canvasWarmlyShip.SetCollectionToCanvas(_company); _canvasWarmlyShip.SetCollectionToCanvas(_company);
@ -70,7 +79,8 @@ public class FormShipCollection extends JFrame{
@Override @Override
public void actionPerformed(ActionEvent e) { public void actionPerformed(ActionEvent e) {
if (_company == null) return; if (_company == null) return;
FormShipConfig form = new FormShipConfig("", new Dimension(700, 300)); FormShipConfig form = new FormShipConfig("", new Dimension(700, 300),
logger, loggerErrow);
form.setCompany(_company); form.setCompany(_company);
form.Init(); form.Init();
} }
@ -88,14 +98,21 @@ public class FormShipCollection extends JFrame{
"Удалить", "Удаление", "Удалить", "Удаление",
JOptionPane.YES_NO_OPTION); JOptionPane.YES_NO_OPTION);
if (resultConfirmDialog == JOptionPane.NO_OPTION) return; if (resultConfirmDialog == JOptionPane.NO_OPTION) return;
DrawingShip obj = _storageCollection.Get( try {
listBoxCollection.getSelectedValue().toString(), pos); DrawingShip obj = _storageCollection.Get(
if (obj != null) { listBoxCollection.getSelectedValue().toString(), pos);
JOptionPane.showMessageDialog(null, "Объект удален"); if (obj != null) {
_collectionRemoveObjects.push(obj); JOptionPane.showMessageDialog(null, "Объект удален");
canvasShow(); _collectionRemoveObjects.push(obj);
canvasShow();
logger.info("Объект удален по позиции " + pos);
}
} }
else { catch (PositionOutOfCollectionException | ObjectNotFoundException ex) {
loggerErrow.warn(ex.toString());
}
catch (Exception ex) {
loggerErrow.fatal(ex.toString());
JOptionPane.showMessageDialog(null, "Объект не удалось удалить"); JOptionPane.showMessageDialog(null, "Объект не удалось удалить");
} }
} }
@ -108,23 +125,24 @@ public class FormShipCollection extends JFrame{
{ {
return; return;
} }
DrawingShip ship = null; try {
int counter = 100;
while (ship == null) DrawingShip ship = null;
{ int counter = 100;
ship = _company.GetRandomObject(); while (ship == null) {
counter--; ship = _company.GetRandomObject();
if (counter <= 0) counter--;
{ if (counter <= 0) {
break; break;
}
} }
if (ship == null) {
return;
}
FormWarmlyShip form = new FormWarmlyShip("Теплоход", new Dimension(900, 565));
form.Init(ship);
} }
if (ship == null) catch (Exception ex) {}
{
return;
}
FormWarmlyShip form = new FormWarmlyShip("Теплоход", new Dimension(900,565));
form.Init(ship);
} }
}); });
@ -135,8 +153,13 @@ public class FormShipCollection extends JFrame{
{ {
return; return;
} }
FormAdditionalCollection form = new FormAdditionalCollection(); try {
form.setCompany(_company); FormAdditionalCollection form = new FormAdditionalCollection(logger, loggerErrow);
form.setCompany(_company);
}
catch (Exception ex) {
loggerErrow.warn(ex.toString());
}
} }
}); });
@ -159,17 +182,20 @@ public class FormShipCollection extends JFrame{
JOptionPane.showMessageDialog(null, "Не все данные заполнены"); JOptionPane.showMessageDialog(null, "Не все данные заполнены");
return; return;
} }
CollectionType collectionType = CollectionType.None; try {
if (radioButtonMassive.isSelected()) CollectionType collectionType = CollectionType.None;
{ if (radioButtonMassive.isSelected()) {
collectionType = CollectionType.Massive; collectionType = CollectionType.Massive;
} else if (radioButtonList.isSelected()) {
collectionType = CollectionType.List;
}
_storageCollection.AddCollection(textBoxCollection.getText(), collectionType);
RerfreshListBoxItems();
logger.info("Добавлена коллекция: " + textBoxCollection.getText());
} }
else if (radioButtonList.isSelected()) catch (Exception ex) {
{ loggerErrow.error(ex.toString());
collectionType = CollectionType.List;
} }
_storageCollection.AddCollection(textBoxCollection.getText(), collectionType);
RerfreshListBoxItems();
} }
}); });
@ -184,8 +210,14 @@ public class FormShipCollection extends JFrame{
"Удалить", "Удаление", "Удалить", "Удаление",
JOptionPane.YES_NO_OPTION); JOptionPane.YES_NO_OPTION);
if (resultConfirmDialog == JOptionPane.NO_OPTION) return; if (resultConfirmDialog == JOptionPane.NO_OPTION) return;
_storageCollection.DelCollection(listBoxCollection.getSelectedValue().toString()); try {
RerfreshListBoxItems(); _storageCollection.DelCollection(listBoxCollection.getSelectedValue().toString());
RerfreshListBoxItems();
logger.info("Удалена коллекция: " + textBoxCollection.getText());
}
catch (Exception ex) {
loggerErrow.error(ex.toString());
}
} }
}); });
@ -323,10 +355,15 @@ public class FormShipCollection extends JFrame{
} }
private void SaveFile() { private void SaveFile() {
String filename = SaveWindow(); String filename = SaveWindow();
if (_storageCollection.SaveData(filename)) { try {
_storageCollection.SaveData(filename);
JOptionPane.showMessageDialog(null, "Сохранено"); JOptionPane.showMessageDialog(null, "Сохранено");
logger.info("Сохранение в файл: " + filename);
}
catch (Exception ex) {
JOptionPane.showMessageDialog(null, "Ошибка сохранения");
loggerErrow.error(ex.toString());
} }
else JOptionPane.showMessageDialog(null, "Ошибка сохранения");
} }
private void SaveCollection() { private void SaveCollection() {
String filename = SaveWindow(); String filename = SaveWindow();
@ -337,10 +374,16 @@ public class FormShipCollection extends JFrame{
if (listBoxCollection.getSelectedIndex() < 0 || listBoxCollection.getSelectedValue() == null) { if (listBoxCollection.getSelectedIndex() < 0 || listBoxCollection.getSelectedValue() == null) {
JOptionPane.showMessageDialog(null, "Коллекция не выбрана"); JOptionPane.showMessageDialog(null, "Коллекция не выбрана");
} }
if (_storageCollection.SaveOneCollection(filename, listBoxCollection.getSelectedValue().toString())) { try {
_storageCollection.SaveOneCollection(filename, listBoxCollection.getSelectedValue().toString());
JOptionPane.showMessageDialog(null, "Коллекция сохранена"); JOptionPane.showMessageDialog(null, "Коллекция сохранена");
logger.info("Сохранение коллекции:" +
listBoxCollection.getSelectedValue().toString() + " в файл: " + filename);
}
catch (Exception ex) {
JOptionPane.showMessageDialog(null, "Ошибка сохранения");
loggerErrow.error(ex.toString());
} }
else JOptionPane.showMessageDialog(null, "Ошибка сохранения");
} }
private String LoadWindow() { private String LoadWindow() {
FileDialog fileDialog = new FileDialog(this, "Save File", FileDialog.LOAD); FileDialog fileDialog = new FileDialog(this, "Save File", FileDialog.LOAD);
@ -352,20 +395,29 @@ public class FormShipCollection extends JFrame{
} }
private void LoadFile() { private void LoadFile() {
String filename = LoadWindow(); String filename = LoadWindow();
if (_storageCollection.LoadData(filename)) { try {
_storageCollection.LoadData(filename);
JOptionPane.showMessageDialog(null, "Загрузка прошла успешно"); JOptionPane.showMessageDialog(null, "Загрузка прошла успешно");
RerfreshListBoxItems(); RerfreshListBoxItems();
logger.info("Загрузка файла: " + filename);
}
catch (Exception ex) {
JOptionPane.showMessageDialog(null, "Не загрузилось");
loggerErrow.error(ex.toString());
} }
else JOptionPane.showMessageDialog(null, "Не загрузилось");
} }
private void LoadCollection() { private void LoadCollection() {
String filename = LoadWindow(); String filename = LoadWindow();
if (_storageCollection.LoadOneCollection(filename)) { try {
_storageCollection.LoadOneCollection(filename);
JOptionPane.showMessageDialog(null, "Коллекция загружена"); JOptionPane.showMessageDialog(null, "Коллекция загружена");
RerfreshListBoxItems(); RerfreshListBoxItems();
logger.info("Загрузка коллекции: ");
}
catch (Exception ex) {
JOptionPane.showMessageDialog(null, "Не загрузилось");
loggerErrow.error(ex.toString());
} }
else JOptionPane.showMessageDialog(null, "Не загрузилось");
} }
private void RerfreshListBoxItems() private void RerfreshListBoxItems()
{ {

View File

@ -6,6 +6,8 @@ import DiffetentsDrawingDecks.IDifferentDecks;
import DrawingShip.DrawingShip; import DrawingShip.DrawingShip;
import DrawingShip.DrawingWarmlyShip; import DrawingShip.DrawingWarmlyShip;
import Entities.EntityWarmlyShip; import Entities.EntityWarmlyShip;
import Exceptions.CollectionOverflowException;
import org.apache.logging.log4j.Logger;
import javax.swing.*; import javax.swing.*;
import javax.swing.event.ChangeEvent; import javax.swing.event.ChangeEvent;
@ -21,6 +23,8 @@ import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent; import java.awt.event.MouseEvent;
import java.io.IOException; import java.io.IOException;
import static DrawingShip.ExtentionDrawningShip.GetDataForSave;
public class FormShipConfig extends JFrame { public class FormShipConfig extends JFrame {
private String title; private String title;
private Dimension dimension; private Dimension dimension;
@ -53,10 +57,14 @@ public class FormShipConfig extends JFrame {
private JPanel panelColorCyan = new JPanel(); private JPanel panelColorCyan = new JPanel();
private JButton buttonAdd = new JButton("Add"); private JButton buttonAdd = new JButton("Add");
private JButton buttonCansel = new JButton("Cancel"); private JButton buttonCansel = new JButton("Cancel");
private org.apache.logging.log4j.Logger logger;
public FormShipConfig(String title, Dimension dimension) { 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.title = title;
this.dimension = dimension; this.dimension = dimension;
this.logger = logger;
this.loggerErrow = logger2;
} }
public void Init() { public void Init() {
SpinnerModel numSpeed = new SpinnerNumberModel(100, 100, 1000, 1); SpinnerModel numSpeed = new SpinnerNumberModel(100, 100, 1000, 1);
@ -301,8 +309,16 @@ public class FormShipConfig extends JFrame {
copyShip = new DrawingWarmlyShip((EntityWarmlyShip) _ship.EntityShip, _ship.drawingDecks); copyShip = new DrawingWarmlyShip((EntityWarmlyShip) _ship.EntityShip, _ship.drawingDecks);
else else
copyShip = new DrawingShip(_ship.EntityShip, _ship.drawingDecks); copyShip = new DrawingShip(_ship.EntityShip, _ship.drawingDecks);
company._collection.Insert(copyShip); try {
FormShipCollection.canvasShow(); 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(); dispose();
} }
}); });

View File

@ -1,8 +1,13 @@
import org.apache.logging.log4j.LogManager;
import java.awt.*; import java.awt.*;
public class Main { public class Main {
public static void main(String[] args) { public static void main(String[] args) {
FormShipCollection form = new FormShipCollection("Коллекция судов", new Dimension(1100, 648)); 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(); form.Init();
} }
} }

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>