Седьмая лабораторная работа.

This commit is contained in:
abazov73 2022-12-15 01:25:45 +04:00
parent 11be96c351
commit cd966ac794
7 changed files with 190 additions and 40 deletions

View File

@ -0,0 +1,15 @@
/*
* Click nbfs://nbhost/SystemFileSystem/Templates/Licenses/license-default.txt to change this license
* Click nbfs://nbhost/SystemFileSystem/Templates/Classes/Class.java to edit this template
*/
package AirBomberPackage;
/**
*
* @author Андрей
*/
public class AirBomberNotFoundException extends Exception {
public AirBomberNotFoundException(int i){
super("Не найден объект по позиции " + i);
}
}

View File

@ -8,6 +8,9 @@ import javax.swing.DefaultListModel;
import java.util.HashMap; import java.util.HashMap;
import java.util.LinkedList; import java.util.LinkedList;
import javax.swing.*; import javax.swing.*;
import org.apache.logging.log4j.*;
import java.io.*;
import java.nio.file.FileSystemException;
/** /**
* *
@ -20,6 +23,8 @@ public class JFrameMapWithSetAirBombers extends javax.swing.JFrame {
*/ */
public JFrameMapWithSetAirBombers() { public JFrameMapWithSetAirBombers() {
initComponents(); initComponents();
System.setProperty("log4j.configurationFile","C:\\Users\\Андрей\\Documents\\loggerSettings.xml");
logger = LogManager.getLogger("logger");
_mapsDict.put("Простая карта", new SimpleMap()); _mapsDict.put("Простая карта", new SimpleMap());
_mapsDict.put("Городская карта", new CityMap()); _mapsDict.put("Городская карта", new CityMap());
_mapsDict.put("Линейная карта", new LineMap()); _mapsDict.put("Линейная карта", new LineMap());
@ -37,6 +42,8 @@ public class JFrameMapWithSetAirBombers extends javax.swing.JFrame {
private LinkedList<DrawingObjectAirBomber> deletedAirBombers = new LinkedList<>(); private LinkedList<DrawingObjectAirBomber> deletedAirBombers = new LinkedList<>();
private Logger logger;
/** /**
* This method is called from within the constructor to initialize the form. * This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always * WARNING: Do NOT modify this code. The content of this method is always
@ -334,8 +341,25 @@ public class JFrameMapWithSetAirBombers extends javax.swing.JFrame {
return; return;
} }
JFrameAirBomberConfig airBomberConfig = new JFrameAirBomberConfig(); JFrameAirBomberConfig airBomberConfig = new JFrameAirBomberConfig();
airBomberConfig.addEvent(airBomber -> {_mapsCollection.Get(listBoxMaps.getSelectedValue()).add(new DrawingObjectAirBomber(airBomber)); airBomberConfig.addEvent(airBomber -> {
airBomberCanvas.getGraphics().drawImage(_mapsCollection.Get(listBoxMaps.getSelectedValue()).ShowSet(), 0, 0, null);}); try{
_mapsCollection.Get(listBoxMaps.getSelectedValue()).add(new DrawingObjectAirBomber(airBomber));
airBomberCanvas.getGraphics().drawImage(_mapsCollection.Get(listBoxMaps.getSelectedValue()).ShowSet(), 0, 0, null);
logger.log(Level.INFO, "Добавлен объект " + airBomber);
}
catch (AirBomberNotFoundException ex){
JOptionPane.showMessageDialog(null, ex);
logger.log(Level.WARN, "Ошибка: " + ex.getMessage());
}
catch (StorageOverflowException ex){
JOptionPane.showMessageDialog(null, ex);
logger.log(Level.WARN, "Ошибка: " + ex.getMessage());
}
catch (Exception ex){
JOptionPane.showMessageDialog(null, ex);
logger.log(Level.FATAL, "Ошибка: " + ex.getMessage());
}
});
airBomberConfig.setVisible(true); airBomberConfig.setVisible(true);
}//GEN-LAST:event_buttonAddAirBomberActionPerformed }//GEN-LAST:event_buttonAddAirBomberActionPerformed
@ -353,16 +377,20 @@ public class JFrameMapWithSetAirBombers extends javax.swing.JFrame {
return; return;
} }
int pos = Integer.parseInt(maskedTextBoxPosition.getText()); int pos = Integer.parseInt(maskedTextBoxPosition.getText());
DrawingObjectAirBomber deletedAirBomber = (DrawingObjectAirBomber) _mapsCollection.Get(listBoxMaps.getSelectedValue()).remove(pos); try{
if (deletedAirBomber != null) DrawingObjectAirBomber deletedAirBomber = (DrawingObjectAirBomber) _mapsCollection.Get(listBoxMaps.getSelectedValue()).remove(pos);
{
deletedAirBombers.add(deletedAirBomber); deletedAirBombers.add(deletedAirBomber);
JOptionPane.showMessageDialog(null,"Объект удален"); JOptionPane.showMessageDialog(null,"Объект удален");
airBomberCanvas.getGraphics().drawImage(_mapsCollection.Get(listBoxMaps.getSelectedValue()).ShowSet(), 0, 0, null); airBomberCanvas.getGraphics().drawImage(_mapsCollection.Get(listBoxMaps.getSelectedValue()).ShowSet(), 0, 0, null);
logger.log(Level.INFO, "Удалён объект " + deletedAirBomber);
} }
else catch (AirBomberNotFoundException ex){
{ JOptionPane.showMessageDialog(null, ex);
JOptionPane.showMessageDialog(null,"Не удалось удалить объект!"); logger.log(Level.WARN, "Ошибка: " + ex.getMessage());
}
catch (Exception ex){
JOptionPane.showMessageDialog(null, ex);
logger.log(Level.FATAL, "Ошибка: " + ex.getMessage());
} }
}//GEN-LAST:event_buttonRemoveAirBomberActionPerformed }//GEN-LAST:event_buttonRemoveAirBomberActionPerformed
@ -377,7 +405,21 @@ public class JFrameMapWithSetAirBombers extends javax.swing.JFrame {
if (listBoxMaps.getSelectedIndex() == -1){ if (listBoxMaps.getSelectedIndex() == -1){
return; return;
} }
airBomberCanvas.getGraphics().drawImage(_mapsCollection.Get(listBoxMaps.getSelectedValue()).ShowOnMap(), 0, 0, null); try{
airBomberCanvas.getGraphics().drawImage(_mapsCollection.Get(listBoxMaps.getSelectedValue()).ShowOnMap(), 0, 0, null);
}
catch (AirBomberNotFoundException ex){
JOptionPane.showMessageDialog(null, ex);
logger.log(Level.WARN, "Ошибка: " + ex.getMessage());
}
catch (StorageOverflowException ex){
JOptionPane.showMessageDialog(null, ex);
logger.log(Level.WARN, "Ошибка: " + ex.getMessage());
}
catch (Exception ex){
JOptionPane.showMessageDialog(null, ex);
logger.log(Level.FATAL, "Ошибка: " + ex.getMessage());
}
}//GEN-LAST:event_buttonShowOnMapActionPerformed }//GEN-LAST:event_buttonShowOnMapActionPerformed
private void buttonAddMapActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_buttonAddMapActionPerformed private void buttonAddMapActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_buttonAddMapActionPerformed
@ -391,15 +433,18 @@ public class JFrameMapWithSetAirBombers extends javax.swing.JFrame {
} }
_mapsCollection.AddMap(textBoxNewMapName.getText(), _mapsDict.get((String) comboBoxSelectorMap.getSelectedItem())); _mapsCollection.AddMap(textBoxNewMapName.getText(), _mapsDict.get((String) comboBoxSelectorMap.getSelectedItem()));
ReloadMaps(); ReloadMaps();
logger.log(Level.INFO, "Добавлна карта " + textBoxNewMapName.getText());
}//GEN-LAST:event_buttonAddMapActionPerformed }//GEN-LAST:event_buttonAddMapActionPerformed
private void buttonDeleteMapActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_buttonDeleteMapActionPerformed private void buttonDeleteMapActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_buttonDeleteMapActionPerformed
if (listBoxMaps.getSelectedIndex() == -1){ if (listBoxMaps.getSelectedIndex() == -1){
return; return;
} }
String name = listBoxMaps.getSelectedValue();
if (JOptionPane.showConfirmDialog(this, (Object) ("Удалить карту " + listBoxMaps.getSelectedValue() + "?") , "Удаление", JOptionPane.OK_CANCEL_OPTION) == JOptionPane.OK_OPTION){ if (JOptionPane.showConfirmDialog(this, (Object) ("Удалить карту " + listBoxMaps.getSelectedValue() + "?") , "Удаление", JOptionPane.OK_CANCEL_OPTION) == JOptionPane.OK_OPTION){
_mapsCollection.DelMap(listBoxMaps.getSelectedValue()); _mapsCollection.DelMap(listBoxMaps.getSelectedValue());
ReloadMaps(); ReloadMaps();
logger.log(Level.INFO, "Удалена карта " + name);
} }
}//GEN-LAST:event_buttonDeleteMapActionPerformed }//GEN-LAST:event_buttonDeleteMapActionPerformed
@ -416,12 +461,14 @@ public class JFrameMapWithSetAirBombers extends javax.swing.JFrame {
return; return;
} }
airBomberCanvas.getGraphics().drawImage(_mapsCollection.Get(listBoxMaps.getSelectedValue()).ShowSet(), 0, 0, null); airBomberCanvas.getGraphics().drawImage(_mapsCollection.Get(listBoxMaps.getSelectedValue()).ShowSet(), 0, 0, null);
logger.log(Level.INFO, "Переход на карту " + listBoxMaps.getSelectedValue());
}//GEN-LAST:event_listBoxMapsValueChanged }//GEN-LAST:event_listBoxMapsValueChanged
private void jMenuItemSaveActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItemSaveActionPerformed private void jMenuItemSaveActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItemSaveActionPerformed
if (jFileChooser1.showDialog(this, "Сохранить") == JFileChooser.APPROVE_OPTION){ if (jFileChooser1.showDialog(this, "Сохранить") == JFileChooser.APPROVE_OPTION){
if (_mapsCollection.SaveData(jFileChooser1.getSelectedFile().getPath())){ if (_mapsCollection.SaveData(jFileChooser1.getSelectedFile().getPath())){
JOptionPane.showMessageDialog(this, "Cохранено"); JOptionPane.showMessageDialog(this, "Cохранено");
logger.log(Level.INFO, "Сохранение");
} }
else{ else{
JOptionPane.showMessageDialog(this, "Не сохранилось"); JOptionPane.showMessageDialog(this, "Не сохранилось");
@ -430,15 +477,38 @@ public class JFrameMapWithSetAirBombers extends javax.swing.JFrame {
}//GEN-LAST:event_jMenuItemSaveActionPerformed }//GEN-LAST:event_jMenuItemSaveActionPerformed
private void jMenuItemLoadActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItemLoadActionPerformed private void jMenuItemLoadActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItemLoadActionPerformed
if (jFileChooser1.showDialog(this, "Загрузить") == JFileChooser.APPROVE_OPTION){ try{
if (_mapsCollection.LoadData(jFileChooser1.getSelectedFile().getPath())){ if (jFileChooser1.showDialog(this, "Загрузить") == JFileChooser.APPROVE_OPTION){
JOptionPane.showMessageDialog(this, "Загрузилось"); if (_mapsCollection.LoadData(jFileChooser1.getSelectedFile().getPath())){
ReloadMaps(); JOptionPane.showMessageDialog(this, "Загрузилось");
} ReloadMaps();
else{ logger.log(Level.INFO, "Загрузка");
JOptionPane.showMessageDialog(this, "Не загрузилось"); }
else{
JOptionPane.showMessageDialog(this, "Не загрузилось");
}
} }
} }
catch (AirBomberNotFoundException ex){
JOptionPane.showMessageDialog(null, ex);
logger.log(Level.WARN, "Ошибка: " + ex.getMessage());
}
catch (StorageOverflowException ex){
JOptionPane.showMessageDialog(null, ex);
logger.log(Level.WARN, "Ошибка: " + ex.getMessage());
}
catch (FileNotFoundException ex){
JOptionPane.showMessageDialog(null, ex);
logger.log(Level.ERROR, "Ошибка: " + ex.getMessage());
}
catch (FileSystemException ex){
JOptionPane.showMessageDialog(null, ex);
logger.log(Level.ERROR, "Ошибка: " + ex.getMessage());
}
catch (Exception ex){
JOptionPane.showMessageDialog(null, ex);
logger.log(Level.FATAL, "Ошибка: " + ex.getMessage());
}
}//GEN-LAST:event_jMenuItemLoadActionPerformed }//GEN-LAST:event_jMenuItemLoadActionPerformed
private void jMenuItemSaveStorageActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItemSaveStorageActionPerformed private void jMenuItemSaveStorageActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItemSaveStorageActionPerformed
@ -453,15 +523,29 @@ public class JFrameMapWithSetAirBombers extends javax.swing.JFrame {
}//GEN-LAST:event_jMenuItemSaveStorageActionPerformed }//GEN-LAST:event_jMenuItemSaveStorageActionPerformed
private void jMenuItemLoadStorageActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItemLoadStorageActionPerformed private void jMenuItemLoadStorageActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItemLoadStorageActionPerformed
if (jFileChooser1.showDialog(this, "Загрузить") == JFileChooser.APPROVE_OPTION){ try{
if (_mapsCollection.LoadStorage(jFileChooser1.getSelectedFile().getPath())){ if (jFileChooser1.showDialog(this, "Загрузить") == JFileChooser.APPROVE_OPTION){
JOptionPane.showMessageDialog(this, "Загрузилось"); if (_mapsCollection.LoadStorage(jFileChooser1.getSelectedFile().getPath())){
ReloadMaps(); JOptionPane.showMessageDialog(this, "Загрузилось");
} ReloadMaps();
else{ }
JOptionPane.showMessageDialog(this, "Не загрузилось"); else{
JOptionPane.showMessageDialog(this, "Не загрузилось");
}
} }
} }
catch (AirBomberNotFoundException ex){
JOptionPane.showMessageDialog(null, ex);
logger.log(Level.WARN, "Ошибка: " + ex.getMessage());
}
catch (StorageOverflowException ex){
JOptionPane.showMessageDialog(null, ex);
logger.log(Level.WARN, "Ошибка: " + ex.getMessage());
}
catch (Exception ex){
JOptionPane.showMessageDialog(null, ex);
logger.log(Level.FATAL, "Ошибка: " + ex.getMessage());
}
}//GEN-LAST:event_jMenuItemLoadStorageActionPerformed }//GEN-LAST:event_jMenuItemLoadStorageActionPerformed
private void ReloadMaps() private void ReloadMaps()

View File

@ -30,11 +30,11 @@ public class MapWithSetAirBombersGeneric <T extends IDrawingObject, U extends Ab
return _setAirBombers; return _setAirBombers;
} }
public int add(T airBomber){ public int add(T airBomber)throws AirBomberNotFoundException, StorageOverflowException, Exception{
return _setAirBombers.Insert(airBomber); return _setAirBombers.Insert(airBomber);
} }
public T remove(int position){ public T remove(int position)throws AirBomberNotFoundException, Exception{
return _setAirBombers.Remove(position); return _setAirBombers.Remove(position);
} }
@ -47,7 +47,7 @@ public class MapWithSetAirBombersGeneric <T extends IDrawingObject, U extends Ab
return bmp; return bmp;
} }
public BufferedImage ShowOnMap() public BufferedImage ShowOnMap() throws AirBomberNotFoundException, StorageOverflowException, Exception
{ {
Shaking(); Shaking();
for (int i = 0; i < _setAirBombers.getCount(); i++) for (int i = 0; i < _setAirBombers.getCount(); i++)
@ -84,7 +84,7 @@ public class MapWithSetAirBombersGeneric <T extends IDrawingObject, U extends Ab
} }
return data; return data;
} }
public void LoadData(String[] records) public void LoadData(String[] records) throws AirBomberNotFoundException, StorageOverflowException, Exception
{ {
for (var rec : records) for (var rec : records)
{ {
@ -96,7 +96,7 @@ public class MapWithSetAirBombersGeneric <T extends IDrawingObject, U extends Ab
_setAirBombers.clear(); _setAirBombers.clear();
} }
private void Shaking() private void Shaking() throws AirBomberNotFoundException, StorageOverflowException, Exception
{ {
int j = _setAirBombers.getCount() - 1; int j = _setAirBombers.getCount() - 1;
for (int i = 0; i < _setAirBombers.getCount(); i++) for (int i = 0; i < _setAirBombers.getCount(); i++)

View File

@ -6,6 +6,7 @@ package AirBomberPackage;
import java.util.HashMap; import java.util.HashMap;
import java.util.ArrayList; import java.util.ArrayList;
import java.io.*; import java.io.*;
import java.nio.file.FileSystemException;
import javax.swing.*; import javax.swing.*;
/** /**
* *
@ -105,7 +106,7 @@ public class MapsCollection {
/// </summary> /// </summary>
/// <param name="filename"></param> /// <param name="filename"></param>
/// <returns></returns> /// <returns></returns>
public boolean LoadData(String filename) public boolean LoadData(String filename) throws AirBomberNotFoundException, StorageOverflowException, Exception
{ {
File loadFile = new File(filename); File loadFile = new File(filename);
if (!loadFile.exists()) if (!loadFile.exists())
@ -174,11 +175,11 @@ public class MapsCollection {
return true; return true;
} }
public boolean LoadStorage(String filename){ public boolean LoadStorage(String filename) throws AirBomberNotFoundException, StorageOverflowException, FileNotFoundException, FileSystemException, Exception{
File loadFile = new File(filename); File loadFile = new File(filename);
if (!loadFile.exists()) if (!loadFile.exists())
{ {
return false; throw new FileNotFoundException(filename);
} }
try{ try{
@ -186,7 +187,7 @@ public class MapsCollection {
String line; String line;
line = br.readLine(); line = br.readLine();
line.trim(); line.trim();
if (!line.equals("Storage")) return false; if (!line.equals("Storage")) throw new FileSystemException("Неверный формат файла!");
String key = br.readLine(); String key = br.readLine();
String mapType = br.readLine(); String mapType = br.readLine();

View File

@ -37,7 +37,7 @@ public class SetAirBombersGeneric<T> {
/// </summary> /// </summary>
/// <param name="airBomber">Добавляемый автомобиль</param> /// <param name="airBomber">Добавляемый автомобиль</param>
/// <returns></returns> /// <returns></returns>
public int Insert(T airBomber) public int Insert(T airBomber)throws AirBomberNotFoundException, StorageOverflowException, Exception
{ {
return Insert(airBomber, 0); return Insert(airBomber, 0);
} }
@ -47,11 +47,14 @@ public class SetAirBombersGeneric<T> {
/// <param name="airBomber">Добавляемый автомобиль</param> /// <param name="airBomber">Добавляемый автомобиль</param>
/// <param name="position">Позиция</param> /// <param name="position">Позиция</param>
/// <returns></returns> /// <returns></returns>
public int Insert(T airBomber, int position) public int Insert(T airBomber, int position) throws AirBomberNotFoundException, StorageOverflowException, Exception
{ {
if (position < 0 || position >= _maxCount) if (position < 0 || position > _maxCount)
{ {
return -1; throw new AirBomberNotFoundException(position);
}
if (_places.size() + 1 > _maxCount){
throw new StorageOverflowException(_maxCount);
} }
_places.add(position, airBomber); _places.add(position, airBomber);
return position; return position;
@ -61,11 +64,11 @@ public class SetAirBombersGeneric<T> {
/// </summary> /// </summary>
/// <param name="position"></param> /// <param name="position"></param>
/// <returns></returns> /// <returns></returns>
public T Remove(int position) public T Remove(int position) throws AirBomberNotFoundException, Exception
{ {
if (position <0 || position >= _maxCount) if (position <0 || position > _maxCount)
{ {
return null; throw new AirBomberNotFoundException(position);
} }
T removedObject = _places.get(position); T removedObject = _places.get(position);
_places.remove(position); _places.remove(position);

View File

@ -0,0 +1,15 @@
/*
* Click nbfs://nbhost/SystemFileSystem/Templates/Licenses/license-default.txt to change this license
* Click nbfs://nbhost/SystemFileSystem/Templates/Classes/Class.java to edit this template
*/
package AirBomberPackage;
/**
*
* @author Андрей
*/
public class StorageOverflowException extends Exception {
public StorageOverflowException(int count){
super("В наборе превышено допустимое количество: " + count);
}
}

View File

@ -0,0 +1,32 @@
<?xml version="1.0" encoding="UTF-8"?>
<Configuration>
<!-- Секция аппендеров -->
<Appenders>
<!-- Файловый аппендер -->
<File name="fileWarnings" fileName="logWarnings.log">
<PatternLayout>
<Pattern> %m(дата-%d{d.M.y}) %ex%n</Pattern>
</PatternLayout>
</File>
<File name="fileInfo" fileName="logInfo.log">
<PatternLayout>
<Pattern> %m(дата-%d{d.M.y}) %ex%n</Pattern>
</PatternLayout>
<Filters>
<!-- Now deny warn, error and fatal messages -->
<ThresholdFilter level="warn" onMatch="DENY" onMismatch="NEUTRAL"/>
<!-- This filter accepts info, warn, error, fatal and denies debug/trace -->
<ThresholdFilter level="info" onMatch="ACCEPT" onMismatch="DENY"/>
</Filters>
</File>
</Appenders>
<!-- Секция логгеров -->
<Loggers>
<Logger name="logger" level="info" additivity="false">
<AppenderRef ref="fileInfo" level="INFO"/>
<AppenderRef ref="fileWarnings" level="WARN"/>
</Logger>
</Loggers>
</Configuration>