сделанная работа

This commit is contained in:
pyzhov.egor 2024-05-20 01:33:55 +04:00
parent 09be0cd57d
commit b6884a45fb
12 changed files with 330 additions and 97 deletions

View File

@ -1,6 +1,9 @@
package CollectionGenericObjects;
import Drawnings.DrawningBoat;
import Exceptions.CollectionOverflowException;
import Exceptions.ObjectNotFoundException;
import Exceptions.PositionOutOfCollectionException;
import java.awt.*;
import java.util.Random;
@ -21,20 +24,20 @@ public abstract class AbstractCompany {
int maxCount = getMaxCount();
_collection.setMaxCount(maxCount);
}
public static int add(AbstractCompany company ,DrawningBoat boat) {
public static int add(AbstractCompany company ,DrawningBoat boat) throws PositionOutOfCollectionException, CollectionOverflowException {
if (company._collection == null) {
return -1;
}
return company._collection.insert(boat);
}
public static DrawningBoat remove(AbstractCompany company, int position) {
public static DrawningBoat remove(AbstractCompany company, int position) throws PositionOutOfCollectionException, ObjectNotFoundException {
if (company._collection == null) {
return null;
}
return company._collection.remove(position);
}
public DrawningBoat getRandomObject() {
public DrawningBoat getRandomObject() throws PositionOutOfCollectionException, ObjectNotFoundException {
if (_collection == null) {
return null;
}
@ -48,9 +51,15 @@ public abstract class AbstractCompany {
return;
}
for(int i = 0; i < _collection.getCount(); i++) {
if(_collection.get(i) != null) {
_collection.get(i).drawBoat(g);
try {
if(_collection.get(i) != null) {
_collection.get(i).drawBoat(g);
}
}
catch (Exception e) {
}
}
}
protected abstract void drawBackground(Graphics g);

View File

@ -48,16 +48,20 @@ public class BoatSharingService extends AbstractCompany {
}
int row = numRows - 1, col = numCols;
for (int i=0;i< _collection.getCount(); i++, col--) {
if (_collection.get(i) != null) {
_collection.get(i).setPictureSize(_pictureWidth, _pictureHeight);
_collection.get(i).setPosition((int)locCoord.get(row*numCols - col).getX() + 5,
(int)locCoord.get(row*numCols - col).getY() + 9);
if (col == 1) {
col = numCols + 1;
row--;
try {
if (_collection.get(i) != null) {
_collection.get(i).setPictureSize(_pictureWidth, _pictureHeight);
_collection.get(i).setPosition((int)locCoord.get(row*numCols - col).getX() + 5,
(int)locCoord.get(row*numCols - col).getY() + 9);
if (col == 1) {
col = numCols + 1;
row--;
}
}
}
catch (Exception e) {
}
}
}
}

View File

@ -1,6 +1,9 @@
package CollectionGenericObjects;
import Drawnings.DrawningBoat;
import Exceptions.CollectionOverflowException;
import Exceptions.ObjectNotFoundException;
import Exceptions.PositionOutOfCollectionException;
public interface ICollectionGenericObjects<T extends DrawningBoat> {
int getCount();
@ -8,13 +11,13 @@ public interface ICollectionGenericObjects<T extends DrawningBoat> {
void setMaxCount(int count);
int getMaxCount();
int insert(T obj);
int insert(T obj) throws CollectionOverflowException, PositionOutOfCollectionException;
int insert(T obj, int index);
int insert(T obj, int index) throws CollectionOverflowException, PositionOutOfCollectionException;
T remove(int index);
T remove(int index) throws PositionOutOfCollectionException, ObjectNotFoundException;
T get(int index);
T get(int index) throws PositionOutOfCollectionException, ObjectNotFoundException;
CollectionType GetCollectionType();
Iterable<T> GetItems();

View File

@ -1,6 +1,8 @@
package CollectionGenericObjects;
import Drawnings.DrawningBoat;
import Exceptions.CollectionOverflowException;
import Exceptions.PositionOutOfCollectionException;
import java.util.ArrayList;
import java.util.Iterator;
@ -27,14 +29,17 @@ public class ListGenericObjects<T extends DrawningBoat> implements ICollectionGe
return maxCount;
}
@Override
public int insert(T obj) {
public int insert(T obj) throws CollectionOverflowException, PositionOutOfCollectionException {
return insert(obj, count);
}
@Override
public int insert(T obj, int index) {
if (index > maxCount || index < 0 || index > count){
return -1;
public int insert(T obj, int index) throws CollectionOverflowException, PositionOutOfCollectionException {
if (index > maxCount){
throw new CollectionOverflowException(maxCount);
}
if (index < 0 || index > count) {
throw new PositionOutOfCollectionException(index);
}
if(index == count){
_collection.add(obj);
@ -47,9 +52,9 @@ public class ListGenericObjects<T extends DrawningBoat> implements ICollectionGe
}
@Override
public T remove(int index) {
public T remove(int index) throws PositionOutOfCollectionException {
if (index > maxCount || index < 0 || index >= count){
return null;
throw new PositionOutOfCollectionException(index);
}
count = _collection.size() - 1;
return _collection.remove(index);
@ -57,9 +62,9 @@ public class ListGenericObjects<T extends DrawningBoat> implements ICollectionGe
}
@Override
public T get(int index) {
public T get(int index) throws PositionOutOfCollectionException {
if (index >= count){
return null;
throw new PositionOutOfCollectionException(index);
}
return _collection.get(index);
}

View File

@ -1,6 +1,10 @@
package CollectionGenericObjects;
import Drawnings.DrawningBoat;
import Exceptions.CollectionOverflowException;
import Exceptions.ObjectNotFoundException;
import Exceptions.PositionOutOfCollectionException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.NoSuchElementException;
@ -23,14 +27,14 @@ public class MassiveGenericObjects<T extends DrawningBoat> implements ICollectio
return maxCount;
}
@Override
public int insert(T obj) {
public int insert(T obj) throws PositionOutOfCollectionException, CollectionOverflowException {
return insert(obj, 0);
}
@Override
public int insert(T obj, int position) {
public int insert(T obj, int position) throws PositionOutOfCollectionException, CollectionOverflowException {
if (position > maxCount|| position < 0) {
return -1;
throw new PositionOutOfCollectionException(position);
}
for (int i = position; i < maxCount; i++) {
@ -47,13 +51,13 @@ public class MassiveGenericObjects<T extends DrawningBoat> implements ICollectio
return i;
}
}
return -1;
throw new CollectionOverflowException(maxCount);
}
@Override
public T remove(int position) {
public T remove(int position) throws PositionOutOfCollectionException, ObjectNotFoundException {
if (position < 0 || position >= maxCount) {
return null;
throw new PositionOutOfCollectionException(position);
}
if (_collection.get(position) != null) {
T bf = _collection.get(position);
@ -61,16 +65,19 @@ public class MassiveGenericObjects<T extends DrawningBoat> implements ICollectio
--realSize;
return bf;
}
return null;
throw new ObjectNotFoundException(position);
}
@Override
public T get(int position) {
public T get(int position) throws PositionOutOfCollectionException, ObjectNotFoundException {
if (position >= 0 && position < _collection.size()) {
if (_collection.get(position) == null) {
throw new ObjectNotFoundException(position);
}
return _collection.get(position);
}
else {
return null;
throw new PositionOutOfCollectionException(position);
}
}

View File

@ -2,10 +2,14 @@ package CollectionGenericObjects;
import Drawnings.DrawningBoat;
import Drawnings.ExtentionDrawningBoat;
import Exceptions.CollectionOverflowException;
import Exceptions.ObjectNotFoundException;
import Exceptions.PositionOutOfCollectionException;
import javax.swing.*;
import java.io.*;
import java.nio.charset.StandardCharsets;
import java.security.InvalidParameterException;
import java.util.*;
public class StorageCollection<T extends DrawningBoat> {
@ -24,9 +28,9 @@ public class StorageCollection<T extends DrawningBoat> {
keys = new ArrayList<>();
}
public boolean SaveData(String filename){
public void SaveData(String filename) throws PositionOutOfCollectionException, ObjectNotFoundException {
if (_storages.isEmpty()) {
return false;
throw new InvalidParameterException("Коллекций в списке нет");
}
File file = new File(filename);
if (file.exists()){
@ -36,7 +40,7 @@ public class StorageCollection<T extends DrawningBoat> {
file.createNewFile();
}
catch (IOException e){
return false;
return;
}
FileWriter fw;
try {
@ -58,8 +62,11 @@ public class StorageCollection<T extends DrawningBoat> {
sb.append(_separatorForKeyValue);
for (int j = 0; j < _storages.get(keys.get(i)).getCount(); j++) {
String data = ExtentionDrawningBoat.GetDataForSave(this.getObjectFromChooseCollection(keys.get(i), j));
if (data==null) {
String data;
try {
data = ExtentionDrawningBoat.GetDataForSave(this.getObjectFromChooseCollection(keys.get(i), j));
}
catch (PositionOutOfCollectionException | ObjectNotFoundException exception) {
continue;
}
sb.append(data);
@ -70,14 +77,12 @@ public class StorageCollection<T extends DrawningBoat> {
fw.close();
}catch (IOException e){
e.getStackTrace();
return false;
}
return true;
}
public boolean SaveOneCollection(String filename, JList<String> stringJList){
public void SaveOneCollection(String filename, JList<String> stringJList) throws PositionOutOfCollectionException, ObjectNotFoundException {
if (_storages.isEmpty() || stringJList.getSelectedIndex() == -1) {
return false;
throw new InvalidParameterException("Коллекций в списке нет");
}
FileWriter fw;
File file = new File(filename);
@ -88,7 +93,7 @@ public class StorageCollection<T extends DrawningBoat> {
file.createNewFile();
}
catch (IOException e){
return false;
return;
}
try {
@ -101,7 +106,7 @@ public class StorageCollection<T extends DrawningBoat> {
sb.append('\n');
if (_storages.get(keys.get(i)) == null) {
fw.close();
return false;
throw new InvalidParameterException("Выбранная коллекция отсутствует");
}
sb.append(keys.get(i));
sb.append(_separatorForKeyValue);
@ -110,8 +115,11 @@ public class StorageCollection<T extends DrawningBoat> {
sb.append(_storages.get(keys.get(i)).getMaxCount());
sb.append(_separatorForKeyValue);
for (int j = 0; j < _storages.get(keys.get(i)).getCount(); j++) {
String data = ExtentionDrawningBoat.GetDataForSave(this.getObjectFromChooseCollection(keys.get(i), j));
if (data==null) {
String data;
try {
data = ExtentionDrawningBoat.GetDataForSave(this.getObjectFromChooseCollection(keys.get(i), j));
}
catch (PositionOutOfCollectionException | ObjectNotFoundException exception) {
continue;
}
sb.append(data);
@ -121,15 +129,13 @@ public class StorageCollection<T extends DrawningBoat> {
fw.close();
}catch (IOException e){
e.getStackTrace();
return false;
}
return true;
}
public boolean LoadData(String filename) {
public void LoadData(String filename) throws Exception {
File file = new File(filename);
if (!file.exists()) {
return false;
throw new FileNotFoundException("Файл не найден");
}
FileReader fr;
try {
@ -149,7 +155,7 @@ public class StorageCollection<T extends DrawningBoat> {
ICollectionGenericObjects<DrawningBoat> collection = StorageCollection.CreateCollection(collectionType);
if (collection == null) {
bufferedReader.close();
return false;
throw new Exception("Ошибка создания коллекции");
}
collection.setMaxCount(Integer.parseInt(record[2]));
String[] set = record[3].split(_separatorItems);
@ -157,10 +163,16 @@ public class StorageCollection<T extends DrawningBoat> {
for (int i = 0; i < set.length; i++) {
DrawningBoat boat;
if ((boat = ExtentionDrawningBoat.CreateDrawningBoat(set[i])) != null) {
if (collection.insert(boat) == -1) {
bufferedReader.close();
return false;
try {
collection.insert(boat);
}
catch (Exception e) {
bufferedReader.close();
throw e;
}
}
}
@ -170,28 +182,26 @@ public class StorageCollection<T extends DrawningBoat> {
}
}
else {
return false;
throw new InvalidParameterException("В файле не корректные данные");
}
bufferedReader.close();
}catch (IOException e){
e.getStackTrace();
return false;
}
return true;
}
public boolean LoadOneCollection(String filename) {
public void LoadOneCollection(String filename) throws Exception {
File file = new File(filename);
if (!file.exists()) return false;
if (!file.exists()) throw new InvalidParameterException("Файл не найден");
try (BufferedReader fs = new BufferedReader(new FileReader(filename))) {
String s = fs.readLine();
if (s == null || !s.startsWith(_collectionSingleKey))
return false;
throw new Exception("В файле не корректные данные");
ICollectionGenericObjects<DrawningBoat> collection;
s = fs.readLine();
String[] record = s.split(_separatorForKeyValue);
if (record.length != 4) {
return false;
throw new InvalidParameterException("В файле не корректные данные");
}
if (keys.contains(s)) {
@ -204,16 +214,22 @@ public class StorageCollection<T extends DrawningBoat> {
}
if (collection == null)
{
return false;
throw new Exception("Ошибка создания коллекции");
}
collection.setMaxCount(Integer.parseInt(record[2]));
String[] set = record[3].split(_separatorItems);
for (String elem : set) {
DrawningBoat boat = ExtentionDrawningBoat.CreateDrawningBoat(elem);
if (collection.insert((T) boat) == -1)
{
return false;
try {
DrawningBoat boat = ExtentionDrawningBoat.CreateDrawningBoat(elem);
if (collection.insert((T) boat) == -1)
{
throw new Exception("Не удалось добавить объект в коллекцию" + record[3]);
}
}
catch (CollectionOverflowException exception) {
throw new Exception("Коллекция переполнена", exception);
}
}
if (keys.contains(record[0])) {
keys.set(keys.indexOf(record[0]), record[0]);
@ -222,7 +238,6 @@ public class StorageCollection<T extends DrawningBoat> {
keys.add(record[0]);
}
_storages.put(record[0], (ICollectionGenericObjects<T>) collection);
return true;
}
catch (IOException e) {
throw new RuntimeException(e);
@ -264,7 +279,7 @@ public class StorageCollection<T extends DrawningBoat> {
return _storages.get(name);
}
public T getObjectFromChooseCollection(String name, int ind){
public T getObjectFromChooseCollection(String name, int ind) throws PositionOutOfCollectionException, ObjectNotFoundException{
return this.getCollection(name).get(ind);
}

View File

@ -3,6 +3,8 @@ package Drawnings;
import CollectionGenericObjects.*;
import CollectionGenericObjects.MassiveGenericObjects;
import Exceptions.CollectionOverflowException;
import Exceptions.PositionOutOfCollectionException;
import Forms.FormBoatConfig;
import Forms.FormCatamaran;
import Forms.FormConstructor;
@ -12,11 +14,22 @@ import java.awt.*;
import java.awt.event.WindowEvent;
import java.util.Random;
import java.util.Stack;
import java.util.logging.Logger;
import static Drawnings.ExtentionDrawningBoat.GetDataForSave;
import Exceptions.*;
public class DrawningAbstractCompany extends JComponent {
private AbstractCompany _company = null;
DrawningBoat _drawningBoat;
private final StorageCollection<DrawningBoat> storageCollection = new StorageCollection<>();
private final Logger userLogger;
private final Logger programLogger;
public DrawningAbstractCompany(Logger userLogger, Logger programLogger) {
this.userLogger = userLogger;
this.programLogger = programLogger;
}
public StorageCollection<DrawningBoat> getStorageCollection() {
return storageCollection;
}
@ -30,6 +43,7 @@ public class DrawningAbstractCompany extends JComponent {
return false;
}
_company = new BoatSharingService(width, height,storageCollection.getCollection(collectionList.getSelectedValue()));
userLogger.info("Компания создана на коллекции " + collectionList.getSelectedValue());
return true;
default:
return false;
@ -44,14 +58,24 @@ public class DrawningAbstractCompany extends JComponent {
formBoatConfig.getButtonAdd().addActionListener(e -> {
if (formBoatConfig.getDrawningConfig().boat != null) {
_drawningBoat = formBoatConfig.getDrawningConfig().boat;
if (AbstractCompany.add(_company, _drawningBoat) != -1) {
try {
AbstractCompany.add(_company, _drawningBoat);
JOptionPane.showMessageDialog(obj, "Объект добавлен");
obj.repaint();
userLogger.info("Объект добавлен " + GetDataForSave(_drawningBoat));
}
else {
catch (PositionOutOfCollectionException | CollectionOverflowException exception) {
JOptionPane.showMessageDialog(obj, "Не удалось добавить объект");
programLogger.warning("Объект не добавлен: " + exception.getMessage());
}
formBoatConfig.getjFrameBoatConfig().dispatchEvent(new WindowEvent(formBoatConfig.getjFrameBoatConfig(), WindowEvent.WINDOW_CLOSING));
catch (Exception ex) {
JOptionPane.showMessageDialog(obj, "Не удалось добавить объект");
programLogger.warning("Объект не добавлен: " + ex.getMessage());
}
finally {
formBoatConfig.getjFrameBoatConfig().dispatchEvent(new WindowEvent(formBoatConfig.getjFrameBoatConfig(), WindowEvent.WINDOW_CLOSING));
}
}
});
@ -67,12 +91,21 @@ public class DrawningAbstractCompany extends JComponent {
"Подтвердение",
JOptionPane.YES_NO_OPTION);
if (result == JOptionPane.YES_OPTION) {
DrawningBoat deletableBoat = AbstractCompany.remove(_company, val);
if (deletableBoat != null) {
DrawningBoat deletableBoat = null;
try {
deletableBoat = AbstractCompany.remove(_company, val);
rubbishBinStack.add(deletableBoat);
JOptionPane.showMessageDialog(obj, "Выполнено");
return true;
} else {
userLogger.info("Объект удален " + GetDataForSave(deletableBoat));
}
catch (PositionOutOfCollectionException | ObjectNotFoundException exception) {
programLogger.warning("Удаление не удалось: " + exception.getMessage());
JOptionPane.showMessageDialog(obj, "Удаление не удалось" + exception.getMessage());
return false;
}
catch (Exception ex) {
programLogger.severe("Удаление не удалось: " + ex.getMessage());
JOptionPane.showMessageDialog(obj, "Удаление не удалось");
return false;
}
@ -86,13 +119,19 @@ public class DrawningAbstractCompany extends JComponent {
DrawningBoat boat = null;
int counter = 100;
while (boat == null && counter > 0) {
boat = _company.getRandomObject();
--counter;
try {
boat = _company.getRandomObject();
--counter;
createFormCatamaran(boat);
userLogger.info("Объект отправлен на проверку" + GetDataForSave(boat));
}
catch (PositionOutOfCollectionException | ObjectNotFoundException exception) {
programLogger.warning("Не удалось отправить объект: " + exception.getMessage());
}
catch (Exception ex) {
programLogger.severe("Не удалось отправить объект: " + ex.getMessage());
}
}
if (boat == null) {
return;
}
createFormCatamaran(boat);
}
@ -121,14 +160,24 @@ public class DrawningAbstractCompany extends JComponent {
formConstructor.getAddButton().addActionListener(e -> {
createObject = formConstructor.getConstructor().getObj();
if (AbstractCompany.add(_company, createObject) != -1) {
try {
AbstractCompany.add(_company, createObject);
JOptionPane.showMessageDialog(obj, "Выполнено");
} else {
JOptionPane.showMessageDialog(obj, "Добавление не удалось");
userLogger.info("Объект из конструктора добавлен " + GetDataForSave(createObject));
}
catch (PositionOutOfCollectionException | CollectionOverflowException exception) {
JOptionPane.showMessageDialog(obj, "Добавление не удалось");
programLogger.warning("Добавление не удалось: " + exception.getMessage());
}
catch (Exception ex) {
JOptionPane.showMessageDialog(obj, "Добавление не удалось");
programLogger.severe("Добавление не удалось: " + ex.getMessage());
}
finally {
obj.repaint();
formConstructor.getjFrameConstructor().dispatchEvent(new WindowEvent(formConstructor.getjFrameConstructor(), WindowEvent.WINDOW_CLOSING));
}
obj.repaint();
formConstructor.getjFrameConstructor().dispatchEvent(new WindowEvent(formConstructor.getjFrameConstructor(), WindowEvent.WINDOW_CLOSING));
});
}
@ -137,6 +186,7 @@ public class DrawningAbstractCompany extends JComponent {
if (textFieldSetCollectionName.getText().isEmpty() || (!massiveRadioButton.isSelected() && !listRadioButton.isSelected())) {
JOptionPane.showMessageDialog(jFrameCollectionBoats, "Не все элементы заполнены", "ERROR", JOptionPane.ERROR_MESSAGE);
programLogger.warning("Не все элементы заполнены");
return null;
}
CollectionType collectionType = CollectionType.None;
@ -145,6 +195,7 @@ public class DrawningAbstractCompany extends JComponent {
else if (listRadioButton.isSelected())
collectionType = CollectionType.List;
storageCollection.addCollection(textFieldSetCollectionName.getText(), collectionType);
userLogger.info("Коллекция добавлена " + textFieldSetCollectionName.getText());
return storageCollection;
}
public StorageCollection<DrawningBoat> deleteCollectionButtonAction(JFrame jFrameCollectionLocomotive, JList<String> keysList) {
@ -152,6 +203,7 @@ public class DrawningAbstractCompany extends JComponent {
int result = JOptionPane.showConfirmDialog( jFrameCollectionLocomotive, "Удалить объект?",
"Подтверждение", JOptionPane.YES_NO_OPTION);
if (result == JOptionPane.YES_OPTION) {
userLogger.info("Коллекция удалена " + keysList.getSelectedValue());
storageCollection.delCollection(keysList.getSelectedValue());
return storageCollection;
}

View File

@ -0,0 +1,20 @@
package Exceptions;
import java.io.Serializable;
public class CollectionOverflowException extends Exception implements Serializable {
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,18 @@
package Exceptions;
import java.io.Serializable;
public class ObjectNotFoundException extends Exception implements Serializable {
public ObjectNotFoundException(int i) {
super("Не найден объект по позиции " + i);
}
public ObjectNotFoundException() {
super();
}
public ObjectNotFoundException(String message) {
super(message);
}
public ObjectNotFoundException(String message, Exception exception) {
super(message, exception);
}
}

View File

@ -0,0 +1,19 @@
package Exceptions;
import java.io.Serializable;
public class PositionOutOfCollectionException extends Exception implements Serializable {
public PositionOutOfCollectionException(int i) {
super("Выход за границы коллекции. Позиция " + i);
}
public PositionOutOfCollectionException() {
super();
}
public PositionOutOfCollectionException(String message) {
super(message);
}
public PositionOutOfCollectionException(String message, Exception exception) {
super(message, exception);
}
}

View File

@ -14,10 +14,13 @@ import java.io.FileFilter;
import java.text.NumberFormat;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.logging.Logger;
public class FormBoatCollection extends JFrame {
final private Logger userLogger;
final private Logger programLogger;
final private JFrame jFrameCollectionBoats = new JFrame();
final private DrawningAbstractCompany _company = new DrawningAbstractCompany();
final private DrawningAbstractCompany _company;
final private JButton refreshButton = new JButton("Обновить");
final private JPanel refreshPanel = new JPanel();
final private String[] listOfComboBox = {
@ -73,6 +76,12 @@ public class FormBoatCollection extends JFrame {
final private JMenuItem loadCollection = new JMenuItem("Загрузить коллекцию");
final private JMenuItem saveCollection = new JMenuItem("Сохранить коллекцию");
public FormBoatCollection(Logger userLogger, Logger programLogger) {
this.userLogger = userLogger;
this.programLogger = programLogger;
this._company = new DrawningAbstractCompany(userLogger, programLogger);
}
public void OpenFrame() {
fileMenu.add(loadItem);
@ -305,10 +314,15 @@ public class FormBoatCollection extends JFrame {
}
private void SaveFile() {
String filename = SaveWindow();
if (_company.getStorageCollection().SaveData(filename)) {
try {
_company.getStorageCollection().SaveData(filename);
JOptionPane.showMessageDialog(jFrameCollectionBoats, "Сохранено");
userLogger.info("Сохранение данных в файл " + filename);
}
catch (Exception ex) {
JOptionPane.showMessageDialog(jFrameCollectionBoats, "Ошибка сохранения");
programLogger.warning("Сохранение данных не удалось: " + ex.getMessage());
}
else JOptionPane.showMessageDialog(jFrameCollectionBoats, "Ошибка сохранения");
}
private void SaveCollection() {
String filename = SaveWindow();
@ -319,10 +333,16 @@ public class FormBoatCollection extends JFrame {
if (collectionsList.getSelectedIndex() < 0 || collectionsList.getSelectedValue() == null) {
JOptionPane.showMessageDialog(jFrameCollectionBoats, "Коллекция не выбрана");
}
if (_company.getStorageCollection().SaveOneCollection(filename, collectionsList)) {
try {
_company.getStorageCollection().SaveOneCollection(filename, collectionsList);
JOptionPane.showMessageDialog(jFrameCollectionBoats, "Коллекция сохранена");
userLogger.info("Сохранение коллекции" + collectionsList.getSelectedValue() + "в файл " + filename);
} catch (Exception ex) {
JOptionPane.showMessageDialog(jFrameCollectionBoats, "Ошибка сохранения");
programLogger.warning("Сохранение коллекции не удалось: " + ex.getMessage());
}
else JOptionPane.showMessageDialog(jFrameCollectionBoats, "Ошибка сохранения");
}
private String LoadWindow() {
FileDialog fileDialog = new FileDialog(this, "Save File", FileDialog.LOAD);
@ -334,20 +354,30 @@ public class FormBoatCollection extends JFrame {
}
private void LoadFile() {
String filename = LoadWindow();
if (_company.getStorageCollection().LoadData(filename)) {
try {
_company.getStorageCollection().LoadData(filename);
JOptionPane.showMessageDialog(jFrameCollectionBoats, "Загрузка прошла успешно");
updateCollectionsList(_company.getStorageCollection());
userLogger.info("Загрузка данных из файла " + filename);
}
catch (Exception ex) {
JOptionPane.showMessageDialog(jFrameCollectionBoats, "Не загрузилось");
programLogger.warning("Загрузка данных не удалась: " + ex.getMessage());
}
else JOptionPane.showMessageDialog(jFrameCollectionBoats, "Не загрузилось");
}
private void LoadCollection() {
String filename = LoadWindow();
if (_company.getStorageCollection().LoadOneCollection(filename)) {
try {
_company.getStorageCollection().LoadOneCollection(filename);
JOptionPane.showMessageDialog(jFrameCollectionBoats, "Коллекция загружена");
updateCollectionsList(_company.getStorageCollection());
userLogger.info("Загрузка коллекции " + collectionsList.getSelectedValue() + " из файла " + filename);
}
catch (Exception ex) {
JOptionPane.showMessageDialog(jFrameCollectionBoats, "Не загрузилось");
programLogger.warning("Загрузка коллекции не удалась: " + ex.getMessage());
}
else JOptionPane.showMessageDialog(jFrameCollectionBoats, "Не загрузилось");
}
private void updateCollectionsList(StorageCollection<DrawningBoat> storageCollection) {

View File

@ -1,9 +1,60 @@
import Forms.FormBoatCollection;
import Forms.FormBoatConfig;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.time.format.FormatStyle;
import java.util.Date;
import java.util.logging.*;
public class Main {
private static Logger userLogger = Logger.getLogger("userLogger");
private static Logger programLogger = Logger.getLogger("programLogger");
public static void main(String[] args) {
FormBoatCollection formBoatCollection = new FormBoatCollection();
try {
FileHandler fileHandlerUser = new FileHandler("userLog.log");
userLogger.setLevel(Level.INFO);
;
fileHandlerUser.setFormatter(new Formatter() {
@Override
public String format(LogRecord record) {
DateTimeFormatter formatter = DateTimeFormatter.ofLocalizedTime(FormatStyle.MEDIUM);
Date currentDate = new Date();
DateFormat dateFormat = new SimpleDateFormat("dd.MM.yyyy");
String formattedDate = dateFormat.format(currentDate);
LocalTime localTime = LocalTime.now();
return formattedDate + " | " + localTime.format(formatter) + " | " + record.getLevel() + " | " + record.getMessage()+ "\n";
}
});
userLogger.addHandler(fileHandlerUser);
}
catch (Exception e) {
userLogger.log(Level.SEVERE, "Ошибка при настройке логгера", e);
}
try {
FileHandler fileHandlerProgram = new FileHandler("programLog.log");
programLogger.setLevel(Level.WARNING);
fileHandlerProgram.setFormatter(new Formatter() {
@Override
public String format(LogRecord record) {
Date currentDate = new Date();
DateFormat dateFormat = new SimpleDateFormat("dd.MM.yyyy");
String formattedDate = dateFormat.format(currentDate);
return record.getLevel() + " | " + record.getMessage() + " | (" + formattedDate + ")" + "\n";
}
});
programLogger.addHandler(fileHandlerProgram);
}
catch (Exception e) {
userLogger.log(Level.SEVERE, "Ошибка при настройке логгера", e);
}
FormBoatCollection formBoatCollection = new FormBoatCollection(userLogger, programLogger);
formBoatCollection.OpenFrame();
}