Добавлены исключения и их обработка, немного изменена отрисовка объектов в хранилище и логика их хранения

This commit is contained in:
Данила Мочалов 2022-12-02 18:34:48 +04:00
parent 29ba58c11a
commit 02ac7e5533
6 changed files with 201 additions and 128 deletions

View File

@ -6,6 +6,55 @@ import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;
import java.text.ParseException;
import java.util.HashMap;
// Остановился на первом коммите и этом файле. Проблема в том, что в СиШарпе при throw не нужно кусок кода
// обматывать в try catch, а в жабе это необходимо.
public class FormMapWithSetLocomotives extends JComponent {
private BufferedImage bufferImg = null;
@ -120,6 +169,7 @@ public class FormMapWithSetLocomotives extends JComponent {
return;
}
if (locomotive!=null) {
try {
DrawningObjectLocomotive objectLocomotive = new DrawningObjectLocomotive(locomotive);
if (_mapsCollection.Get(listBoxMaps.getSelectedValue().toString()).Plus(objectLocomotive)!= -1){
JOptionPane.showMessageDialog(formFrame, "Object added", "Success", JOptionPane.OK_CANCEL_OPTION);
@ -130,6 +180,13 @@ public class FormMapWithSetLocomotives extends JComponent {
JOptionPane.showMessageDialog(formFrame, "Object cannot be added", "Error", JOptionPane.OK_CANCEL_OPTION);
}
}
catch (StorageOverflowException ex) {
JOptionPane.showMessageDialog(formFrame, "Storage overflow error: "+ ex.getMessage());
}
catch (Exception ex) {
JOptionPane.showMessageDialog(formFrame, "Unknown error: "+ ex.getMessage());
}
}
});
});
statusPanel.add(addLocomotiveButton);
@ -149,6 +206,7 @@ public class FormMapWithSetLocomotives extends JComponent {
JFormattedTextField finalMaskedTextFieldPosition = maskedTextFieldPosition;
deleteLocomotiveButton.addActionListener(e -> {
// логика удаления
try{
if ((String)mapSelectComboBox.getSelectedItem() == null) {
return;
}
@ -163,6 +221,12 @@ public class FormMapWithSetLocomotives extends JComponent {
}
else{
JOptionPane.showMessageDialog(formFrame, "Object cannot be removed", "Error", JOptionPane.OK_CANCEL_OPTION);
}}
catch (LocomotiveNotFoundException ex) {
JOptionPane.showMessageDialog(formFrame, "Locomotive not found error: " + ex.getMessage());
}
catch (Exception ex) {
JOptionPane.showMessageDialog(formFrame, "Unknown error: "+ ex.getMessage());
}
});
statusPanel.add(deleteLocomotiveButton);
@ -186,8 +250,13 @@ public class FormMapWithSetLocomotives extends JComponent {
{
return;
}
try {
bufferImg = _mapsCollection.Get(listBoxMaps.getSelectedValue().toString()).ShowOnMap();
repaint();
}
catch (Exception ex) {
JOptionPane.showMessageDialog(null, "Unknown error: "+ ex.getMessage());
}
});
statusPanel.add(showOnMapButton);
@ -271,10 +340,13 @@ public class FormMapWithSetLocomotives extends JComponent {
fileChooser.setDialogTitle("Saving");
int result = fileChooser.showSaveDialog(FormMapWithSetLocomotives.this);
if (result == JFileChooser.APPROVE_OPTION ) {
if (_mapsCollection.SaveData(fileChooser.getSelectedFile().getAbsolutePath())) {
try {
_mapsCollection.SaveData(fileChooser.getSelectedFile().getAbsolutePath());
JOptionPane.showMessageDialog(null, "Save success");
}
else JOptionPane.showMessageDialog(null, "Save failed");
catch (Exception ex) {
JOptionPane.showMessageDialog(null, "Save error: " + ex.getMessage());
}
}
});
@ -285,13 +357,16 @@ public class FormMapWithSetLocomotives extends JComponent {
fileChooser.setDialogTitle("Loading");
int result = fileChooser.showSaveDialog(FormMapWithSetLocomotives.this);
if (result == JFileChooser.APPROVE_OPTION ) {
if (_mapsCollection.LoadData(fileChooser.getSelectedFile().getAbsolutePath())) {
try {
_mapsCollection.LoadData(fileChooser.getSelectedFile().getAbsolutePath());
JOptionPane.showMessageDialog(null, "Load success");
}
else JOptionPane.showMessageDialog(null, "Load failed");
}
ReloadMaps();
repaint();
}
catch (Exception ex) {
JOptionPane.showMessageDialog(null, "Load error: " + ex.getMessage());
}
}
});
statusPanel.add(loadButton);
@ -306,12 +381,15 @@ public class FormMapWithSetLocomotives extends JComponent {
return;
}
if(listBoxMaps.getSelectedValue().toString() == null) return;
if (_mapsCollection.SaveMap(listBoxMaps.getSelectedValue().toString(), fileChooser.getSelectedFile().getAbsolutePath())) {
try {
_mapsCollection.SaveMap(listBoxMaps.getSelectedValue().toString(), fileChooser.getSelectedFile().getAbsolutePath());
JOptionPane.showMessageDialog(null, "Map saving success");
}
else JOptionPane.showMessageDialog(null, "Map saving fail");
repaint();
}
catch (Exception ex) {
JOptionPane.showMessageDialog(null, "Map saving error: " + ex.getMessage());
}
}
});
statusPanel.add(saveMapButton);
@ -321,13 +399,16 @@ public class FormMapWithSetLocomotives extends JComponent {
fileChooser.setDialogTitle("Loading");
int result = fileChooser.showSaveDialog(FormMapWithSetLocomotives.this);
if (result == JFileChooser.APPROVE_OPTION ) {
if (_mapsCollection.LoadMap(fileChooser.getSelectedFile().getAbsolutePath())) {
try {
_mapsCollection.LoadMap(fileChooser.getSelectedFile().getAbsolutePath());
JOptionPane.showMessageDialog(null, "Load Map success");
}
else JOptionPane.showMessageDialog(null, "Load Map failed");
}
ReloadMaps();
repaint();
}
catch (Exception ex) {
JOptionPane.showMessageDialog(null, "Load Map error: " + ex.getMessage());
}
}
});
statusPanel.add(loadMapButton);

View File

@ -0,0 +1,5 @@
public class LocomotiveNotFoundException extends Exception{
public LocomotiveNotFoundException(int i) {
super("Не найден объект по позиции " + i);
}
}

View File

@ -13,9 +13,9 @@ public class MapWithSetLocomotivesGeneric
/// Высота окна отрисовки
private final int _pictureHeight;
/// Размер занимаемого объектом места (ширина)
private final int _placeSizeWidth = 210;
private final int _placeSizeWidth = 150;
/// Размер занимаемого объектом места (высота)
private final int _placeSizeHeight = 90;
private final int _placeSizeHeight = 150;
public final SetLocomotivesGeneric<T> _setLocomotives;
// Список удаленных объектов
@ -39,12 +39,12 @@ public class MapWithSetLocomotivesGeneric
}
/// Добавление
public int Plus(T locomotive)
public int Plus(T locomotive) throws StorageOverflowException
{
return this._setLocomotives.Insert(locomotive);
}
/// Удаление
public T Minus(int position)
public T Minus(int position) throws LocomotiveNotFoundException
{
T temp = this._setLocomotives.Remove(position);
if (temp == null) return null;
@ -62,7 +62,7 @@ public class MapWithSetLocomotivesGeneric
}
/// Просмотр объекта на карте
public BufferedImage ShowOnMap()
public BufferedImage ShowOnMap() throws LocomotiveNotFoundException, StorageOverflowException
{
Shaking();
for (var locomotive : _setLocomotives.GetLocomotives())
@ -86,7 +86,7 @@ public class MapWithSetLocomotivesGeneric
}
/// "Взбалтываем" набор, чтобы все элементы оказались в начале
private void Shaking()
private void Shaking() throws LocomotiveNotFoundException, StorageOverflowException
{
int j = _setLocomotives.Count() - 1;
for (int i = 0; i < _setLocomotives.Count(); i++)
@ -157,8 +157,8 @@ public class MapWithSetLocomotivesGeneric
/// Метод прорисовки объектов
private void DrawLocomotives(Graphics2D g)
{
int width = _pictureWidth / _placeSizeWidth;
int height = _pictureHeight / _placeSizeHeight;
int width = _pictureWidth / _placeSizeWidth - 1;
int height = _pictureHeight / _placeSizeHeight - 1;
int curWidth = 0;
int curHeight = 0;
@ -166,7 +166,7 @@ public class MapWithSetLocomotivesGeneric
for (var locomotive : _setLocomotives.GetLocomotives())
{
// установка позиции
if (locomotive != null) locomotive.SetObject(curWidth * _placeSizeWidth + 10, curHeight * _placeSizeHeight + 18, _pictureWidth, _pictureHeight);
if (locomotive != null) locomotive.SetObject(curWidth * _placeSizeWidth + 10, curHeight * _placeSizeHeight + 80, _pictureWidth, _pictureHeight);
if (locomotive != null) locomotive.DrawningObject(g);
if (curWidth < width) curWidth++;
else
@ -189,7 +189,7 @@ public class MapWithSetLocomotivesGeneric
}
/// Загрузка списка из массива строк
public void LoadData(String[] records)
public void LoadData(String[] records) throws StorageOverflowException
{
Collections.reverse(Arrays.asList(records));
for (var rec : records)

View File

@ -2,6 +2,7 @@ import java.io.*;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.zip.DataFormatException;
public class MapsCollection {
/// Словарь (хранилище) с картами
@ -51,59 +52,49 @@ public class MapsCollection {
}
/// Сохранение информации по локомотивам в хранилище в файл
public boolean SaveData(String filename)
public void SaveData(String filename) throws IOException
{
File file = new File(filename);
if (file.exists())
{
file.delete();
}
try(BufferedWriter bw = new BufferedWriter(new FileWriter(filename))) {
BufferedWriter bw = new BufferedWriter(new FileWriter(filename));
bw.write("MapsCollection\n");
for (var storage : _mapStorages.entrySet()) {
bw.write("" + storage.getKey() + separatorDict + storage.getValue().GetData(separatorDict.charAt(0), separatorData) + "\n");
}
}
catch (IOException ex) {
System.out.println(ex.getMessage());
}
return true;
}
// Сохранение одной выбранной карты
public boolean SaveMap(String map_name, String filename) {
public void SaveMap(String map_name, String filename) throws IOException{
File file = new File(filename);
MapWithSetLocomotivesGeneric<IDrawningObject, AbstractMap> map = Get(map_name);
if (file.exists())
{
file.delete();
}
try(BufferedWriter bw = new BufferedWriter(new FileWriter(filename))) {
BufferedWriter bw = new BufferedWriter(new FileWriter(filename));
bw.write("SingleMap\n");
bw.write("" + map_name + "\n");
bw.write("" + map.getClass() + "\n");
for (var locomotive : map._setLocomotives.GetLocomotives()) {
bw.write("" + locomotive.getInfo() + "\n");
}
}
catch (IOException ex) {
System.out.println(ex.getMessage());
}
return true;
}
// Загрузка одной карты
public boolean LoadMap(String filename){
public void LoadMap(String filename) throws StorageOverflowException, IOException, DataFormatException{
File file = new File(filename);
if (!file.exists())
{
return false;
throw new FileNotFoundException("Файл не найден");
}
try {
BufferedReader br = new BufferedReader(new FileReader(filename));
String curLine = br.readLine();
if (!curLine.contains("SingleMap")) {
return false;
throw new DataFormatException("Неверный формат данных");
}
String mapName = br.readLine();
String mapClass = br.readLine();
@ -113,7 +104,6 @@ public class MapsCollection {
_mapStorages.get(mapName)._setLocomotives.Insert(DrawningObjectLocomotive.Create(curLine));
}
_mapStorages.get(mapName)._setLocomotives.ReversePlaces();
return true;
}
AbstractMap map = null;
switch (mapClass)
@ -133,33 +123,27 @@ public class MapsCollection {
_mapStorages.get(mapName)._setLocomotives.Insert(DrawningObjectLocomotive.Create(curLine));
}
_mapStorages.get(mapName)._setLocomotives.ReversePlaces();
} catch (IOException ex) {
System.out.println(ex.getMessage());
}
return true;
}
/// Загрузка информации по локомотивам в депо из файла
public boolean LoadData(String filename)
public void LoadData(String filename) throws DataFormatException, IOException, StorageOverflowException
{
File file = new File(filename);
if (!file.exists())
{
return false;
throw new FileNotFoundException("Файл не найден");
}
try {
BufferedReader br = new BufferedReader(new FileReader(filename));
String curLine = br.readLine();
if (!curLine.contains("MapsCollection")) {
return false;
throw new DataFormatException("Неверный формат данных");
}
_mapStorages.clear();
while ((curLine = br.readLine()) != null) {
var elems = curLine.split(separatorDict);
AbstractMap map = null;
switch (elems[1])
{
case "class SimpleMap":
@ -176,10 +160,6 @@ public class MapsCollection {
_mapStorages.put(elems[0], new MapWithSetLocomotivesGeneric<IDrawningObject, AbstractMap>(_pictureWidth, _pictureHeight, map));
_mapStorages.get(elems[0]).LoadData(elems[2].split(Character.toString(separatorData)));
}
} catch (IOException ex) {
System.out.println(ex.getMessage());
}
return true;
}

View File

@ -18,20 +18,22 @@ public class SetLocomotivesGeneric <T>
_places = new ArrayList<>();
}
public int Insert (T locomotive) {
public int Insert (T locomotive) throws StorageOverflowException{
return Insert(locomotive, 0);
}
public int Insert (T locomotive, int position) {
if (position >= _maxCount|| position < 0) return -1;
public int Insert (T locomotive, int position) throws StorageOverflowException{
if (position < 0) return -1;
if (Count() >= _maxCount) throw new StorageOverflowException(_maxCount);
_places.add(position, locomotive);
return position;
}
public T Remove (int position) {
public T Remove (int position) throws LocomotiveNotFoundException {
if (position >= _maxCount || position < 0) return null;
if (_places.get(position) == null) throw new LocomotiveNotFoundException(position);
T result = _places.get(position);
_places.remove(position);
_places.set(position, null);
return result;
}

View File

@ -0,0 +1,5 @@
public class StorageOverflowException extends Exception{
public StorageOverflowException(int count) {
super("В наборе превышено допустимое количество: " + count);
}
}