six commit

This commit is contained in:
Salikh 2023-12-30 09:55:26 +04:00
parent ea3315b4a9
commit 11444f958e
6 changed files with 340 additions and 5 deletions

View File

@ -1,6 +1,11 @@
import java.awt.*;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
public class BomberGenericCollection<T extends DrawingAir, U extends IMoveableObject> {
public static char _separatorRecords = ';';
public static char _separatorForObject = ':';
/// <summary>
/// Ширина окна прорисовки
/// </summary>
@ -21,6 +26,37 @@ public class BomberGenericCollection<T extends DrawingAir, U extends IMoveableOb
/// Набор объектов
/// </summary>
private SetGeneric<T> collection;
public ArrayList<T> GetPlanes(){
return collection.getPlanes(collection.getCount());
}
public boolean SaveData(File f, String name) throws IOException {
if(f.exists()) {
f.delete();
}
f.createNewFile();
StringBuilder data = new StringBuilder();
data.append("PlaneCollection\n");
data.append(String.format("%s\n", name));
StringBuilder records = new StringBuilder();
for(DrawingAir elem : GetPlanes())
{
records.append(String.format("%s%c", ExtentionDrawingBomber.GetDataForSave(elem, _separatorForObject),
_separatorRecords));
}
data.append(records);
if(data.length() == 0)
return false;
FileWriter writer = new FileWriter(f);
writer.write(data.toString());
writer.flush();
writer.close();
return true;
}
public void Clear(){
collection = new SetGeneric<>(pictureWidth * _pictureHeight);
}
/// <summary>
/// Конструктор
/// </summary>

View File

@ -1,10 +1,118 @@
import java.util.ArrayList;
import java.util.HashMap;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Map;
import java.util.Scanner;
public class BomberGenericStorage {
final HashMap<String, BomberGenericCollection<DrawingAir, DrawingObjectPlane>> planeStorages;
public HashMap<String, BomberGenericCollection<DrawingAir, DrawingObjectPlane>> planeStorages;
private final int _pictureWidth;
private final int _pictureHeight;
private static final char _separatorForKeyValue = '|';
private final char _separatorRecords = ';';
private static final char _separatorForObject = ':';
public void SaveData(File f) throws IOException {
if(f.exists()) {
f.delete();
}
f.createNewFile();
StringBuilder data = new StringBuilder();
data.append("PlaneStorage\n");
for(Map.Entry<String, BomberGenericCollection<DrawingAir, DrawingObjectPlane>> record : planeStorages.entrySet()){
StringBuilder records = new StringBuilder();
for(DrawingAir elem : record.getValue().GetPlanes())
{
records.append(String.format("%s%c", ExtentionDrawingBomber.GetDataForSave(elem, _separatorForObject),
_separatorRecords));
}
data.append(String.format("%s%c%s\n", record.getKey(), _separatorForKeyValue, records.toString()));
}
if(data.length() == 0)
return;
FileWriter writer = new FileWriter(f);
writer.write(data.toString());
writer.flush();
writer.close();
}
public boolean LoadData(File f) throws FileNotFoundException {
if(!f.exists())
return false;
StringBuilder bufferTextFromFile = new StringBuilder();
Scanner s = new Scanner(f);
while(s.hasNext())
bufferTextFromFile.append(s.next() + "\n");
s.close();
var strs = bufferTextFromFile.toString().split("\n");
if(strs == null || strs.length == 0)
return false;
if (!strs[0].startsWith("PlaneStorage"))
return false;
planeStorages.clear();
for(String data : strs){
String st = new String("\\" + Character.toString( _separatorForKeyValue));
String[]record = data.split(st);
if (record.length != 2)
continue;
BomberGenericCollection<DrawingAir, DrawingObjectPlane> collection =
new BomberGenericCollection<>(_pictureWidth, _pictureHeight);
String[] set = record[1].split(Character.toString(_separatorRecords));
for(int i = set.length -1; i >=0; i--){
String elem = set[i];
DrawingAir plane = ExtentionDrawingBomber.CreateDrawingPlane(elem,
_separatorForObject, _pictureWidth, _pictureHeight);
if (plane != null)
{
if (!(collection.Insert(plane)))
{
return false;
}
}
}
planeStorages.put(record[0], collection);
}
return true;
}
public boolean LoadCollection(File f) throws FileNotFoundException {
if(!f.exists())
return false;
StringBuilder bufferTextFromFile = new StringBuilder();
Scanner s = new Scanner(f);
while(s.hasNext())
bufferTextFromFile.append(s.next() + "\n");
s.close();
var strs = bufferTextFromFile.toString().split("\n");
if(strs == null || strs.length == 0)
return false;
if (!strs[0].startsWith("PlaneCollection"))
return false;
String collectionName = strs[1];
BomberGenericCollection<DrawingAir, DrawingObjectPlane> collection = getCollection(collectionName);
if(collection == null)
collection = new BomberGenericCollection<>(_pictureWidth, _pictureHeight);
else
collection.Clear();
String[] planesInfo = strs[2].split(Character.toString(BomberGenericCollection._separatorRecords));
for(int i = planesInfo.length-1; i >= 0; i--){
String data = planesInfo[i];
DrawingAir plane = ExtentionDrawingBomber.CreateDrawingPlane(data,
BomberGenericCollection._separatorForObject, _pictureWidth, _pictureHeight);
if (plane != null)
{
if (!(collection.Insert(plane)))
{
return false;
}
}
}
AddSetFromFile(collectionName, collection);
return true;
}
public BomberGenericStorage(int pictureWidth, int pictureHeight){
planeStorages = new HashMap<>();
_pictureWidth = pictureWidth;
@ -19,12 +127,25 @@ public class BomberGenericStorage {
planeStorages.put(name, new BomberGenericCollection<>(_pictureWidth, _pictureHeight));
}
public void DelSet(String name){
public void AddSetFromFile(String name, BomberGenericCollection<DrawingAir, DrawingObjectPlane> toAdd){
if(planeStorages.containsKey(name)){
planeStorages.remove(name);
}
planeStorages.put(name, toAdd);
}
public void DelSet(String name, BomberTrashCollection<DrawingAir> trashBox){
if(!planeStorages.containsKey(name))
return;
BomberGenericCollection<DrawingAir, DrawingObjectPlane> cur = planeStorages.get(name);
for(int i = 0; i < cur.size(); i++)
trashBox.Push(cur.Get(i));
planeStorages.remove(name);
}
public BomberGenericCollection<DrawingAir, DrawingObjectPlane> GetCollection(String collectionName){
return planeStorages.get(collectionName);
}
public BomberGenericCollection<DrawingAir, DrawingObjectPlane> getCollection(String name){
if(!planeStorages.containsKey(name))
return null;

View File

@ -6,7 +6,7 @@ public class DrawingAir {
public EntityAir getEntityAir() {
return entityAir;
}
private IDrawEngines drawingEngines;
public IDrawEngines drawingEngines;
public int _pictureWidth;
public int _pictureHeight;
protected int _startPosX;

View File

@ -0,0 +1,75 @@
import java.awt.*;
public class ExtentionDrawingBomber {
private static String getName(Color col){
if(col.equals(Color.RED))
return "RED";
if(col.equals(Color.GREEN))
return "GREEN";
if(col.equals(Color.BLUE))
return "BLUE";
if(col.equals(Color.YELLOW))
return "YELLOW";
if(col.equals(Color.WHITE))
return "WHITE";
if(col.equals(Color.GRAY))
return "GRAY";
if(col.equals(Color.BLACK))
return "BLACK";
if(col.equals(Color.MAGENTA))
return "MAGENTA";
return null;
}
private static Color getColor(String col){
if(col.equals("RED"))
return Color.RED;
if(col.equals("GREEN"))
return Color.GREEN;
if(col.equals("BLUE"))
return Color.BLUE;
if(col.equals("YELLOW"))
return Color.YELLOW;
if(col.equals("WHITE"))
return Color.WHITE;
if(col.equals("GRAY"))
return Color.GRAY;
if(col.equals("BLACK"))
return Color.BLACK;
if(col.equals("MAGENTA"))
return Color.MAGENTA;
return null;
}
public static DrawingAir CreateDrawingPlane(String info, char separatorForObject,
int width, int height){
String[] strs = info.split(Character.toString(separatorForObject));
if(strs.length == 5){
return new DrawingAir(Integer.parseInt(strs[0]),
Integer.parseInt(strs[1]), getColor(strs[2]), width, height, Integer.parseInt(strs[3]), Integer.parseInt(strs[4]));
}
if(strs.length == 8){
return new DrawingAirBomber(Integer.parseInt(strs[0]),
Integer.parseInt(strs[1]), getColor(strs[2]),
getColor(strs[5]), Boolean.parseBoolean(strs[6]),
Boolean.parseBoolean(strs[7]), width, height,
Integer.parseInt(strs[3]), Integer.parseInt(strs[4]));
}
return null;
}
public static String GetDataForSave(DrawingAir drawingPlane, char separatorForObject){
var plane = drawingPlane;
var entity = plane.entityAir;
if(entity == null)
return null;
var str = String.format("%d%c%d%c%s%c%d%c%d", entity.getSpeed(), separatorForObject, (int)entity.getWeight(),
separatorForObject, getName(entity.bodyColor), separatorForObject, plane.drawingEngines.getType(), separatorForObject, plane.drawingEngines.getNumber());
if(!(entity instanceof EntityAirBomber)){
return str;
}
var nstr = String.format("%s%c%s%c%b%c%b", str, separatorForObject,
getName(((EntityAirBomber) entity).additionalColor), separatorForObject,
((EntityAirBomber) entity).getBombs(), separatorForObject,
((EntityAirBomber) entity).getFuel());
return nstr;
}
}

View File

@ -3,6 +3,7 @@ import javax.swing.border.StrokeBorder;
import java.awt.*;
import java.io.IOException;
import java.io.File;
import java.util.ArrayList;
import java.util.Objects;
@ -37,6 +38,22 @@ public class FramePlaneCollection extends JFrame {
super.repaint();
}
};
JMenuBar menuFile = new JMenuBar();
JMenu file = new JMenu("Файл");
menuFile.add(file);
JMenuItem saveFile = new JMenuItem("Сохранить");
saveFile.addActionListener(e -> saveFile_Click());
JMenuItem loadFile = new JMenuItem("Загрузить");
loadFile.addActionListener(e -> loadFile_Click());
JMenuItem saveCollection = new JMenuItem("Сохранить коллекцию");
saveCollection.addActionListener(e -> saveCollection_Click());
JMenuItem loadCollection = new JMenuItem("Загрузить коллекцию");
loadCollection.addActionListener(e -> loadCollection_Click());
file.add(saveCollection);
file.add(loadCollection);
file.add(saveFile);
file.add(loadFile);
super.setJMenuBar(menuFile);
pictureBoxCollection.setPreferredSize(new Dimension(700, 600));
JButton buttonAddPlane = new JButton("Добавить самолет");
textFieldNumber = new TextField();
@ -105,6 +122,74 @@ public class FramePlaneCollection extends JFrame {
add(panelTools, BorderLayout.EAST);
add(pictureBoxCollection, BorderLayout.CENTER);
}
private void saveFile_Click(){
JFileChooser fc = new JFileChooser("C:\\Users\\salih\\OneDrive\\Рабочий стол\\HardSave");
fc.addChoosableFileFilter(new TxtSaveFilter());
fc.addChoosableFileFilter(new TxtSaveFilter());
int retrieval = fc.showSaveDialog(null);
if (retrieval == JFileChooser.APPROVE_OPTION) {
File file = new File(fc.getSelectedFile() + "." + "txt");
try {
storage.SaveData(file);
} catch (IOException ex) {
throw new RuntimeException(ex);
}
}
}
private void loadFile_Click() {
JFileChooser fc = new JFileChooser("C:\\Users\\salih\\OneDrive\\Рабочий стол\\HardSave");
fc.addChoosableFileFilter(new TxtSaveFilter());
int ret = fc.showDialog(null, "Открыть файл");
if(ret == JFileChooser.APPROVE_OPTION){
File file = fc.getSelectedFile();
try {
storage.LoadData(file);
reloadObjects();
super.repaint();
} catch (IOException ex) {
throw new RuntimeException(ex);
}
}
}
private void saveCollection_Click() {
JFileChooser fc = new JFileChooser("C:\\Users\\salih\\OneDrive\\Рабочий стол\\HardSave");
fc.addChoosableFileFilter(new TxtSaveFilter());
int retrieval = fc.showSaveDialog(null);
if (retrieval == JFileChooser.APPROVE_OPTION) {
File file = new File(fc.getSelectedFile() + "." + "txt");
try {
if(listStorages.getSelectedIndex() == -1) {
return;
}
storage.planeStorages.get(listStorages.getSelectedValue()).SaveData(file, listStorages.getSelectedValue());
reloadObjects();
super.repaint();
} catch (IOException ex) {
throw new RuntimeException(ex);
}
}
}
private void loadCollection_Click() {
JFileChooser fc = new JFileChooser("C:\\Users\\salih\\OneDrive\\Рабочий стол\\HardSave");
fc.addChoosableFileFilter(new TxtSaveFilter());
int ret = fc.showDialog(null, "Открыть файл");
if(ret == JFileChooser.APPROVE_OPTION){
File file = fc.getSelectedFile();
try {
storage.LoadCollection(file);
reloadObjects();
super.repaint();
} catch (IOException ex) {
throw new RuntimeException(ex);
}
}
}
private void reloadObjects(){
int index = listStorages.getSelectedIndex();
listModel.clear();
@ -133,7 +218,7 @@ public class FramePlaneCollection extends JFrame {
public void buttonDeleteSet_Click() {
if (listStorages.getSelectedIndex() == -1)
return;
storage.DelSet(listStorages.getSelectedValue());
storage.DelSet(listStorages.getSelectedValue(), trashCollection);
reloadObjects();
}
public void buttonAddPlaneClick() {

18
src/TxtSaveFilter.java Normal file
View File

@ -0,0 +1,18 @@
import javax.swing.filechooser.FileFilter;
import java.io.File;
public class TxtSaveFilter extends FileFilter {
@Override
public boolean accept(File f) {
if (f.isDirectory()) {
return false;
}
String s = f.getName().toLowerCase();
return s.endsWith(".txt");
}
@Override
public String getDescription() {
return "*.txt";
}
}