3 Commits

Author SHA1 Message Date
IlyasValiulov
1b17183c14 Лабараторная работа №6 1 2024-04-25 21:27:57 +04:00
IlyasValiulov
aa2c3827ef Лабараторная работа №5 1 2024-04-25 21:09:03 +04:00
IlyasValiulov
b143d60656 Лабараторная работа №5 1 2024-04-25 21:08:12 +04:00
11 changed files with 917 additions and 69 deletions

View File

@@ -7,5 +7,8 @@ public interface ICollectionGenericObjects<T>
int Insert(T obj); int Insert(T obj);
T Remove(int position); T Remove(int position);
T Get(int position); T Get(int position);
CollectionType GetCollectionType();
Iterable<T> GetItems();
void ClearCollection();
} }

View File

@@ -1,9 +1,10 @@
package CollectionGenericObjects; package CollectionGenericObjects;
import java.util.ArrayList; import java.util.*;
import java.util.List;
public class ListGenericObjects<T> implements ICollectionGenericObjects<T> { public class ListGenericObjects<T> implements ICollectionGenericObjects<T> {
private List<T> _collection; private List<T> _collection;
private CollectionType collectionType = CollectionType.List;
private int _maxCount; private int _maxCount;
public int getCount() { public int getCount() {
return _collection.size(); return _collection.size();
@@ -18,6 +19,10 @@ public class ListGenericObjects<T> implements ICollectionGenericObjects<T> {
_collection = new ArrayList<T>(); _collection = new ArrayList<T>();
} }
@Override @Override
public CollectionType GetCollectionType() {
return collectionType;
}
@Override
public T Get(int position) public T Get(int position)
{ {
if (position >= getCount() || position < 0) return null; if (position >= getCount() || position < 0) return null;
@@ -38,4 +43,35 @@ public class ListGenericObjects<T> implements ICollectionGenericObjects<T> {
_collection.remove(position); _collection.remove(position);
return obj; return obj;
} }
@Override
public Iterable<T> GetItems() {
return new Iterable<T>() {
@Override
public Iterator<T> iterator() {
return new Iterator<T>() {
private int currentIndex = 0;
//нужен ли count
private int count = 0;
@Override
public boolean hasNext() {
return currentIndex < getCount();
}
@Override
public T next() {
if (hasNext()) {
count++;
return _collection.get(currentIndex++);
}
throw new NoSuchElementException();
}
};
}
};
}
@Override
public void ClearCollection() {
for (T ship : _collection) {
ship = null;
}
}
} }

View File

@@ -3,10 +3,12 @@ package CollectionGenericObjects;
import DrawingShip.DrawingShip; import DrawingShip.DrawingShip;
import java.lang.reflect.Array; import java.lang.reflect.Array;
import java.util.*;
public class MassiveGenericObjects<T> implements ICollectionGenericObjects<T>{ public class MassiveGenericObjects<T> implements ICollectionGenericObjects<T>{
private T[] _collection = null; private T[] _collection = null;
private int Count; private int Count;
private CollectionType collectionType = CollectionType.Massive;
@Override @Override
public void SetMaxCount(int size) { public void SetMaxCount(int size) {
if (size > 0) { if (size > 0) {
@@ -21,6 +23,10 @@ public class MassiveGenericObjects<T> implements ICollectionGenericObjects<T>{
return Count; return Count;
} }
@Override @Override
public CollectionType GetCollectionType() {
return collectionType;
}
@Override
public int Insert(T obj) { public int Insert(T obj) {
int index = 0; int index = 0;
while (index < getCount()) while (index < getCount())
@@ -47,4 +53,35 @@ public class MassiveGenericObjects<T> implements ICollectionGenericObjects<T>{
if (position >= getCount() || position < 0) return null; if (position >= getCount() || position < 0) return null;
return (T) _collection[position]; return (T) _collection[position];
} }
@Override
public Iterable<T> GetItems() {
return new Iterable<T>() {
@Override
public Iterator<T> iterator() {
return new Iterator<T>() {
private int currentIndex = 0;
//нужен ли count
private int count = 0;
@Override
public boolean hasNext() {
return currentIndex < getCount();
}
@Override
public T next() {
if (hasNext()) {
count++;
return _collection[currentIndex++];
}
throw new NoSuchElementException();
}
};
}
};
}
@Override
public void ClearCollection() {
for (T ship : _collection) {
ship = null;
}
}
} }

View File

@@ -1,10 +1,12 @@
package CollectionGenericObjects; package CollectionGenericObjects;
import DrawingShip.DrawingShip; import DrawingShip.DrawingShip;
import DrawingShip.ExtentionDrawningShip;
import java.io.*;
import java.util.*; import java.util.*;
public class StorageCollection<T> { public class StorageCollection<T extends DrawingShip> {
private Map<String, ICollectionGenericObjects<T>> _storages; private Map<String, ICollectionGenericObjects<T>> _storages;
public StorageCollection() public StorageCollection()
{ {
@@ -40,4 +42,153 @@ public class StorageCollection<T> {
return _storages.get(name).Remove(position); return _storages.get(name).Remove(position);
return null; return null;
} }
private String _collectionKey = "CollectionsStorage";
private String _collectionName = "StorageCollection";
private String _separatorForKeyValueS = "|";
private String _separatorForKeyValue = "\\|";
private String _separatorItemsS = ";";
private String _separatorItems = "\\;";
public boolean SaveData(String filename) {
if (_storages.isEmpty()) return false;
File file = new File(filename);
if (file.exists()) file.delete();
try {
file.createNewFile();
FileWriter writer = new FileWriter(file);
writer.write(_collectionKey);
writer.write("\n");
for (Map.Entry<String, ICollectionGenericObjects<T>> value : _storages.entrySet()) {
StringBuilder sb = new StringBuilder();
sb.append(value.getKey());
sb.append(_separatorForKeyValueS);
sb.append(value.getValue().GetCollectionType());
sb.append(_separatorForKeyValueS);
sb.append(value.getValue().getCount());
sb.append(_separatorForKeyValueS);
for (T ship : value.getValue().GetItems()) {
String data = ExtentionDrawningShip.GetDataForSave((DrawingShip) ship);
if (data.isEmpty()) continue;
sb.append(data);
sb.append(_separatorItemsS);
}
sb.append("\n");
writer.write(String.valueOf(sb));
}
writer.close();
} catch (IOException e) {
throw new RuntimeException(e);
}
return true;
}
public boolean SaveOneCollection(String filename, String name) {
if (_storages.isEmpty()) return false;
File file = new File(filename);
if (file.exists()) file.delete();
try {
file.createNewFile();
FileWriter writer = new FileWriter(file);
writer.write(_collectionName);
writer.write("\n");
ICollectionGenericObjects<T> value = _storages.get(name);
StringBuilder sb = new StringBuilder();
sb.append(name);
sb.append(_separatorForKeyValueS);
sb.append(value.GetCollectionType());
sb.append(_separatorForKeyValueS);
sb.append(value.getCount());
sb.append(_separatorForKeyValueS);
for (T ship : value.GetItems()) {
String data = ExtentionDrawningShip.GetDataForSave((DrawingShip) ship);
if (data.isEmpty()) continue;
sb.append(data);
sb.append(_separatorItemsS);
}
writer.append(sb);
writer.close();
} catch (IOException e) {
throw new RuntimeException(e);
}
return true;
}
public boolean LoadData(String filename) {
File file = new File(filename);
if (!file.exists()) return false;
try (BufferedReader fs = new BufferedReader(new FileReader(filename))) {
String s = fs.readLine();
if (s == null || s.isEmpty() || !s.startsWith(_collectionKey))
return false;
_storages.clear();
s = "";
while ((s = fs.readLine()) != null) {
String[] record = s.split(_separatorForKeyValue);
if (record.length != 4) {
continue;
}
ICollectionGenericObjects<T> collection = CreateCollection(record[1]);
if (collection == null)
{
return false;
}
collection.SetMaxCount(Integer.parseInt(record[2]));
String[] set = record[3].split(_separatorItems);
for (String elem : set) {
DrawingShip ship = ExtentionDrawningShip.CreateDrawingShip(elem);
if (collection.Insert((T) ship) == -1)
{
return false;
}
}
_storages.put(record[0], collection);
}
return true;
}
catch (IOException e) {
throw new RuntimeException(e);
}
}
public boolean LoadOneCollection(String filename) {
File file = new File(filename);
if (!file.exists()) return false;
try (BufferedReader fs = new BufferedReader(new FileReader(filename))) {
String s = fs.readLine();
if (s == null || s.isEmpty() || !s.startsWith(_collectionName))
return false;
if (_storages.containsKey(s)) {
_storages.get(s).ClearCollection();
}
s = fs.readLine();
String[] record = s.split(_separatorForKeyValue);
if (record.length != 4) {
return false;
}
ICollectionGenericObjects<T> collection = CreateCollection(record[1]);
if (collection == null)
{
return false;
}
collection.SetMaxCount(Integer.parseInt(record[2]));
String[] set = record[3].split(_separatorItems);
for (String elem : set) {
DrawingShip ship = ExtentionDrawningShip.CreateDrawingShip(elem);
if (collection.Insert((T) ship) == -1)
{
return false;
}
}
_storages.put(record[0], collection);
return true;
}
catch (IOException e) {
throw new RuntimeException(e);
}
}
public ICollectionGenericObjects<T> CreateCollection(String s) {
switch (s) {
case "Massive":
return new MassiveGenericObjects<T>();
case "List":
return new ListGenericObjects<T>();
}
return null;
}
} }

View File

@@ -28,28 +28,9 @@ public class DrawingShip extends JPanel {
_StartPosX = null; _StartPosX = null;
_StartPosY = null; _StartPosY = null;
} }
protected void SetAmountandTypeDecks() {
int numberOfDecks = (int)(Math.random() * 4 + 0);
switch ((int)(Math.random() * 3 + 1)) {
case 1:
drawingDecks = new DrawingDecksType1();
break;
case 2:
drawingDecks = new DrawingDecksType2();
break;
case 3:
drawingDecks = new DrawingDecksType3();
break;
default:
numberOfDecks = 0;
break;
}
drawingDecks.setNumberOfDecks(numberOfDecks);
}
public DrawingShip(int speed, double weight, Color bodycolor) { public DrawingShip(int speed, double weight, Color bodycolor) {
super(); super();
EntityShip = new EntityShip(speed, weight, bodycolor); EntityShip = new EntityShip(speed, weight, bodycolor);
SetAmountandTypeDecks();
} }
protected DrawingShip(int drawingShipWidth, int drawingShipHeight) { protected DrawingShip(int drawingShipWidth, int drawingShipHeight) {
super(); super();
@@ -153,4 +134,16 @@ public class DrawingShip extends JPanel {
g.fillPolygon(poly); g.fillPolygon(poly);
drawingShipHeight = y + 50 - _StartPosY; drawingShipHeight = y + 50 - _StartPosY;
} }
public String[] GetStringRepresentationDecks() {
if (drawingDecks instanceof DrawingDecksType1) {
return new String[]{String.valueOf(drawingDecks.getNumberOfDecks().getNumdecks()), "DrawingDecksType1"};
}
else if (drawingDecks instanceof DrawingDecksType2) {
return new String[]{String.valueOf(drawingDecks.getNumberOfDecks().getNumdecks()), "DrawingDecksType2"};
}
else if (drawingDecks instanceof DrawingDecksType3) {
return new String[]{String.valueOf(drawingDecks.getNumberOfDecks().getNumdecks()), "DrawingDecksType3"};
}
return null;
}
} }

View File

@@ -1,6 +1,5 @@
package DrawingShip; package DrawingShip;
import DiffetentsDrawingDecks.IDifferentDecks; import DiffetentsDrawingDecks.IDifferentDecks;
import Entities.EntityShip;
import Entities.EntityWarmlyShip; import Entities.EntityWarmlyShip;
import java.awt.*; import java.awt.*;
@@ -8,7 +7,6 @@ import java.awt.*;
public class DrawingWarmlyShip extends DrawingShip { public class DrawingWarmlyShip extends DrawingShip {
public DrawingWarmlyShip(int speed, double weight, Color bodycolor, Color additionalcolor, boolean sheeppipes, boolean fueltank) { public DrawingWarmlyShip(int speed, double weight, Color bodycolor, Color additionalcolor, boolean sheeppipes, boolean fueltank) {
EntityShip = new EntityWarmlyShip(speed, weight, bodycolor, additionalcolor, sheeppipes, fueltank); EntityShip = new EntityWarmlyShip(speed, weight, bodycolor, additionalcolor, sheeppipes, fueltank);
SetAmountandTypeDecks();
} }
//добавил //добавил
public DrawingWarmlyShip(EntityWarmlyShip entity, IDifferentDecks decks) { public DrawingWarmlyShip(EntityWarmlyShip entity, IDifferentDecks decks) {

View File

@@ -0,0 +1,74 @@
package DrawingShip;
import DiffetentsDrawingDecks.DrawingDecksType1;
import DiffetentsDrawingDecks.DrawingDecksType2;
import DiffetentsDrawingDecks.DrawingDecksType3;
import DiffetentsDrawingDecks.IDifferentDecks;
import Entities.EntityShip;
import Entities.EntityWarmlyShip;
import java.util.ArrayList;
import java.util.Collections;
public class ExtentionDrawningShip {
private static String _separatorForObjectS = ":";
private static String _separatorForObject = "\\:";
public static DrawingShip CreateDrawingShip(String info) {
String[] strs = info.split(_separatorForObject);
EntityShip ship;
IDifferentDecks decks = null;
if (strs.length == 8)
{
String s = strs[8];
switch (s) {
case "DrawingDecksType1":
decks = new DrawingDecksType1();
case "DrawingDecksType2":
decks = new DrawingDecksType2();
case "DrawingDecksType3":
decks = new DrawingDecksType3();
}
if (decks != null) decks.setNumberOfDecks(Integer.parseInt(strs[7]));
}
else if (strs.length == 6) {
String s = strs[5];
switch (s) {
case "DrawingDecksType1":
decks = new DrawingDecksType1();
case "DrawingDecksType2":
decks = new DrawingDecksType2();
case "DrawingDecksType3":
decks = new DrawingDecksType3();
}
if (decks != null) decks.setNumberOfDecks(Integer.parseInt(strs[4]));
}
ship = EntityWarmlyShip.CreateEntityWarmlyShip(strs);
if (ship != null)
{
return new DrawingWarmlyShip((EntityWarmlyShip)ship, decks);
}
ship = EntityShip.CreateEntityShip(strs);
if (ship != null)
{
return new DrawingShip(ship, decks);
}
return null;
}
public static String GetDataForSave(DrawingShip drawningShip)
{
if (drawningShip == null) return "";
String[] array1 = drawningShip.EntityShip.GetStringRepresentation();
String[] array2 = drawningShip.GetStringRepresentationDecks();
if (array1 == null)
{
return "";
}
ArrayList<String> list = new ArrayList<>();
Collections.addAll(list, array1);
if (array2 == null) {
Collections.addAll(list, "0", " ");
}
else Collections.addAll(list, array2);
return String.join(_separatorForObjectS, list);
}
}

View File

@@ -1,12 +1,18 @@
package Entities; package Entities;
import java.awt.*; import java.awt.*;
import java.util.Objects;
public class EntityShip { public class EntityShip {
private int Speed; private Integer Speed;
private double Weight; public void setSpeed(int speed) {Speed = speed;}
public Integer getSpeed() {return Speed;}
private Double Weight;
public void setWeight(double weight) {Weight = weight;}
public Double getWeight() {return Weight;}
private Color BodyColor; private Color BodyColor;
public Color getBodyColor() {return BodyColor;} public Color getBodyColor() {return BodyColor;}
public void setBodyColor(Color color) {BodyColor = color;}
public double Step; public double Step;
public EntityShip(int speed, double weight, Color bodycolor) public EntityShip(int speed, double weight, Color bodycolor)
{ {
@@ -15,4 +21,22 @@ public class EntityShip {
BodyColor = bodycolor; BodyColor = bodycolor;
Step = Speed * 100 / Weight; Step = Speed * 100 / Weight;
} }
public String[] GetStringRepresentation()
{
return new String[]{"EntityShip", Speed.toString(), Weight.toString(), colorToHexString(BodyColor)};
}
public static EntityShip CreateEntityShip(String[] strs)
{
if (strs.length != 6 || !Objects.equals(strs[0], "EntityShip"))
{
return null;
}
return new EntityShip(Integer.parseInt(strs[1]), Double.parseDouble(strs[2]), hexStringToColor(strs[3]));
}
public static String colorToHexString(Color color) {
return String.format("#%02x%02x%02x", color.getRed(), color.getGreen(), color.getBlue());
}
public static Color hexStringToColor(String hexString) {
return Color.decode(hexString);
}
} }

View File

@@ -1,12 +1,17 @@
package Entities; package Entities;
import java.awt.*; import java.awt.*;
import java.util.Objects;
public class EntityWarmlyShip extends EntityShip{ public class EntityWarmlyShip extends EntityShip{
public Color AdditionalColor; public Color AdditionalColor;
public Color getAdditionalColor() {return AdditionalColor;} public Color getAdditionalColor() {return AdditionalColor;}
public void setAdditionalColor(Color color) {AdditionalColor = color;}
public boolean ShipPipes; public boolean ShipPipes;
public void setShipPipes(boolean pipes) {ShipPipes = pipes;}
public boolean FuelTank; public boolean FuelTank;
public boolean getFuelTank() {return FuelTank;} public boolean getFuelTank() {return FuelTank;}
public void setFuelTank(boolean tank) {FuelTank = tank;}
public EntityWarmlyShip(int speed, double weight, Color bodyColor, Color additionalcolor, boolean sheeppipes, boolean fueltank) public EntityWarmlyShip(int speed, double weight, Color bodyColor, Color additionalcolor, boolean sheeppipes, boolean fueltank)
{ {
super(speed, weight, bodyColor); super(speed, weight, bodyColor);
@@ -14,4 +19,20 @@ public class EntityWarmlyShip extends EntityShip{
ShipPipes = sheeppipes; ShipPipes = sheeppipes;
FuelTank = fueltank; FuelTank = fueltank;
} }
@Override
public String[] GetStringRepresentation()
{
return new String[]{"EntityWarmlyShip", getSpeed().toString(), getWeight().toString(),
colorToHexString(getBodyColor()), colorToHexString(getAdditionalColor()),
String.valueOf(ShipPipes), String.valueOf(FuelTank)};
}
public static EntityWarmlyShip CreateEntityWarmlyShip(String[] strs)
{
if (strs.length != 9 || !Objects.equals(strs[0], "EntityWarmlyShip"))
{
return null;
}
return new EntityWarmlyShip(Integer.parseInt(strs[1]), Double.parseDouble(strs[2]), hexStringToColor(strs[3]),
hexStringToColor(strs[4]), Boolean.parseBoolean(strs[5]), Boolean.parseBoolean(strs[6]));
}
} }

View File

@@ -2,15 +2,12 @@ import CollectionGenericObjects.*;
import DrawingShip.CanvasFormShipCollection; import DrawingShip.CanvasFormShipCollection;
import DrawingShip.DrawingShip; import DrawingShip.DrawingShip;
import DrawingShip.DrawingWarmlyShip; import DrawingShip.DrawingWarmlyShip;
import Entities.EntityShip;
import javax.swing.*; import javax.swing.*;
import javax.swing.text.MaskFormatter; import javax.swing.text.MaskFormatter;
import java.awt.*; 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.awt.event.ComponentAdapter;
import java.awt.event.ComponentEvent;
import java.text.ParseException; import java.text.ParseException;
import java.util.Random; import java.util.Random;
import java.util.Stack; import java.util.Stack;
@@ -31,7 +28,6 @@ public class FormShipCollection extends JFrame{
private JList listBoxCollection = new JList(); private JList listBoxCollection = new JList();
private JButton buttonRemoveCollection = new JButton("Remove"); private JButton buttonRemoveCollection = new JButton("Remove");
private JButton buttonCreateCompany = new JButton("Create company"); private JButton buttonCreateCompany = new JButton("Create company");
private JButton CreateButton = new JButton("Create warmlyship");;
private JButton CreateShipButton = new JButton("Create ship"); private JButton CreateShipButton = new JButton("Create ship");
private JButton RemoveButton = new JButton("Remove"); private JButton RemoveButton = new JButton("Remove");
private JButton GoToCheckButton = new JButton("Check"); private JButton GoToCheckButton = new JButton("Check");
@@ -40,6 +36,12 @@ public class FormShipCollection extends JFrame{
private JButton RefreshButton = new JButton("Refresh"); private JButton RefreshButton = new JButton("Refresh");
private JComboBox ComboBoxCollections = new JComboBox(new String[]{"", "Хранилище"}); private JComboBox ComboBoxCollections = new JComboBox(new String[]{"", "Хранилище"});
private JFormattedTextField MaskedTextField; private JFormattedTextField MaskedTextField;
private JMenuBar menuBar = new JMenuBar();
private JMenu fileMenu = new JMenu("File");
private JMenuItem loadItem = new JMenuItem("Load");
private JMenuItem saveItem = new JMenuItem("Save");
private JMenuItem loadCollection = new JMenuItem("Load coll");
private JMenuItem saveCollection = new JMenuItem("Save coll");
public FormShipCollection(String title, Dimension dimension) { public FormShipCollection(String title, Dimension dimension) {
this.title = title; this.title = title;
this.dimension = dimension; this.dimension = dimension;
@@ -49,37 +51,6 @@ public class FormShipCollection extends JFrame{
_canvasWarmlyShip.SetCollectionToCanvas(_company); _canvasWarmlyShip.SetCollectionToCanvas(_company);
_canvasWarmlyShip.repaint(); _canvasWarmlyShip.repaint();
} }
private void CreateObject(String typeOfClass) {
if (_company == null) return;
int speed = (int)(Math.random() * 300 + 100);
double weight = (double)(Math.random() * 3000 + 1000);
Color bodyColor = getColor();
DrawingShip drawingShip;
switch (typeOfClass) {
case "DrawingShip":
drawingShip = new DrawingShip(speed, weight, bodyColor);
break;
case "DrawingWarmlyShip":
Color additionalColor = getColor();
boolean sheepPipes = new Random().nextBoolean();
boolean fuelTank = new Random().nextBoolean();;
drawingShip = new DrawingWarmlyShip(speed, weight, bodyColor, additionalColor, sheepPipes, fuelTank);
break;
default: return;
}
if (_company._collection.Insert(drawingShip) != -1) {
JOptionPane.showMessageDialog(null, "Объект добавлен");
canvasShow();
}
else {
JOptionPane.showMessageDialog(null, "Объект не удалось добавить");
}
}
public Color getColor() {
Color initializator = new Color((int)(Math.random() * 255 + 0),(int)(Math.random() * 255 + 0),(int)(Math.random() * 255 + 0));
Color color = JColorChooser.showDialog(this, "Select a color", initializator);
return color;
}
public void Init() { public void Init() {
setTitle(title); setTitle(title);
setMinimumSize(dimension); setMinimumSize(dimension);
@@ -96,13 +67,12 @@ public class FormShipCollection extends JFrame{
MaskedTextField = new JFormattedTextField(mask); MaskedTextField = new JFormattedTextField(mask);
CreateShipButton.addActionListener(new ActionListener() { CreateShipButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) { CreateObject("DrawingShip"); }
});
CreateButton.addActionListener(new ActionListener() {
@Override @Override
public void actionPerformed(ActionEvent e) { public void actionPerformed(ActionEvent e) {
CreateObject("DrawingWarmlyShip"); if (_company == null) return;
FormShipConfig form = new FormShipConfig("", new Dimension(700, 300));
form.setCompany(_company);
form.Init();
} }
}); });
@@ -260,11 +230,50 @@ public class FormShipCollection extends JFrame{
} }
}); });
saveItem.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
SaveFile();
}
});
loadItem.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
LoadFile();
}
});
saveCollection.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
System.out.println("Save coll");
SaveCollection();
}
});
loadCollection.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
System.out.println("Load coll");
LoadCollection();
}
});
JLabel labelCollectionName = new JLabel("Название коллекции"); JLabel labelCollectionName = new JLabel("Название коллекции");
ButtonGroup radiobuttonsGroup = new ButtonGroup(); ButtonGroup radiobuttonsGroup = new ButtonGroup();
radiobuttonsGroup.add(radioButtonMassive); radiobuttonsGroup.add(radioButtonMassive);
radiobuttonsGroup.add(radioButtonList); radiobuttonsGroup.add(radioButtonList);
fileMenu.add(loadItem);
fileMenu.add(saveItem);
fileMenu.add(loadCollection);
fileMenu.add(saveCollection);
fileMenu.addSeparator();
menuBar.add(fileMenu);
setJMenuBar(menuBar);
_canvasWarmlyShip.setBounds(0, 0, getWidth()-200, getHeight()); _canvasWarmlyShip.setBounds(0, 0, getWidth()-200, getHeight());
labelCollectionName.setBounds(getWidth()-190, 10, 150, 20); labelCollectionName.setBounds(getWidth()-190, 10, 150, 20);
textBoxCollection.setBounds(getWidth()-190, 32, 150, 25); textBoxCollection.setBounds(getWidth()-190, 32, 150, 25);
@@ -276,13 +285,12 @@ public class FormShipCollection extends JFrame{
ComboBoxCollections.setBounds(getWidth()-190, 235, 150, 20); ComboBoxCollections.setBounds(getWidth()-190, 235, 150, 20);
buttonCreateCompany.setBounds(getWidth()-190, 260, 150, 20); buttonCreateCompany.setBounds(getWidth()-190, 260, 150, 20);
CreateShipButton.setBounds(getWidth()-190, 295, 150, 30); CreateShipButton.setBounds(getWidth()-190, 295, 150, 30);
CreateButton.setBounds(getWidth()-190, 330, 150, 30);
MaskedTextField.setBounds(getWidth()-190,365,150,30); MaskedTextField.setBounds(getWidth()-190,365,150,30);
RemoveButton.setBounds(getWidth()-190, 400, 150, 30); RemoveButton.setBounds(getWidth()-190, 400, 150, 30);
GoToCheckButton.setBounds(getWidth()-190, 435, 150, 30); GoToCheckButton.setBounds(getWidth()-190, 435, 150, 30);
RandomButton.setBounds(getWidth()-190, 470, 150, 30); RandomButton.setBounds(getWidth()-190, 470, 150, 30);
RemoveObjectsButton.setBounds(getWidth()-190, 505, 150, 30); RemoveObjectsButton.setBounds(getWidth()-190, 505, 150, 30);
RefreshButton.setBounds(getWidth()-190, getHeight()-90, 150, 30); RefreshButton.setBounds(getWidth()-190, getHeight()-100, 150, 30);
setSize(dimension.width,dimension.height); setSize(dimension.width,dimension.height);
setLayout(null); setLayout(null);
@@ -297,7 +305,6 @@ public class FormShipCollection extends JFrame{
add(ComboBoxCollections); add(ComboBoxCollections);
add(buttonCreateCompany); add(buttonCreateCompany);
add(CreateShipButton); add(CreateShipButton);
add(CreateButton);
add(MaskedTextField); add(MaskedTextField);
add(RemoveButton); add(RemoveButton);
add(GoToCheckButton); add(GoToCheckButton);
@@ -306,6 +313,60 @@ public class FormShipCollection extends JFrame{
add(RefreshButton); add(RefreshButton);
setVisible(true); setVisible(true);
} }
private String SaveWindow() {
FileDialog fileDialog = new FileDialog(this, "Save File", FileDialog.SAVE);
fileDialog.setVisible(true);
String directory = fileDialog.getDirectory();
String file = fileDialog.getFile();
if (directory == null || file == null) return null;
return directory + file;
}
private void SaveFile() {
String filename = SaveWindow();
if (_storageCollection.SaveData(filename)) {
JOptionPane.showMessageDialog(null, "Сохранено");
}
else JOptionPane.showMessageDialog(null, "Ошибка сохранения");
}
private void SaveCollection() {
String filename = SaveWindow();
if (filename == null) {
JOptionPane.showMessageDialog(null, "Файл не выбран");
return;
}
if (listBoxCollection.getSelectedIndex() < 0 || listBoxCollection.getSelectedValue() == null) {
JOptionPane.showMessageDialog(null, "Коллекция не выбрана");
}
if (_storageCollection.SaveOneCollection(filename, listBoxCollection.getSelectedValue().toString())) {
JOptionPane.showMessageDialog(null, "Коллекция сохранена");
}
else JOptionPane.showMessageDialog(null, "Ошибка сохранения");
}
private String LoadWindow() {
FileDialog fileDialog = new FileDialog(this, "Save File", FileDialog.LOAD);
fileDialog.setVisible(true);
String directory = fileDialog.getDirectory();
String file = fileDialog.getFile();
if (directory == null || file == null) return null;
return directory + file;
}
private void LoadFile() {
String filename = LoadWindow();
if (_storageCollection.LoadData(filename)) {
JOptionPane.showMessageDialog(null, "Загрузка прошла успешно");
RerfreshListBoxItems();
}
else JOptionPane.showMessageDialog(null, "Не загрузилось");
}
private void LoadCollection() {
String filename = LoadWindow();
if (_storageCollection.LoadOneCollection(filename)) {
JOptionPane.showMessageDialog(null, "Коллекция загружена");
RerfreshListBoxItems();
}
else JOptionPane.showMessageDialog(null, "Не загрузилось");
}
private void RerfreshListBoxItems() private void RerfreshListBoxItems()
{ {
DefaultListModel<String> list = new DefaultListModel<String>(); DefaultListModel<String> list = new DefaultListModel<String>();

View File

@@ -0,0 +1,450 @@
import CollectionGenericObjects.AbstractCompany;
import DiffetentsDrawingDecks.DrawingDecksType1;
import DiffetentsDrawingDecks.DrawingDecksType2;
import DiffetentsDrawingDecks.DrawingDecksType3;
import DiffetentsDrawingDecks.IDifferentDecks;
import DrawingShip.DrawingShip;
import DrawingShip.DrawingWarmlyShip;
import Entities.EntityWarmlyShip;
import javax.swing.*;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import java.awt.*;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.StringSelection;
import java.awt.datatransfer.Transferable;
import java.awt.datatransfer.UnsupportedFlavorException;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.io.IOException;
public class FormShipConfig extends JFrame {
private String title;
private Dimension dimension;
private DrawingShip _ship;
private AbstractCompany company = null;
private JLabel labelSpeed = new JLabel("Speed");
private JLabel labelWeight = new JLabel("Weight");
private JLabel labelShip = new JLabel("Ship", SwingConstants.CENTER);
private JLabel labelWarmlyShip = new JLabel("WarmlyShip", SwingConstants.CENTER);
private JLabel labelColor = new JLabel("Color");
private JLabel labelBodyColor = new JLabel("BodyColor", SwingConstants.CENTER);
private JLabel labelSolidDeck = new JLabel("Solid Deck",SwingConstants.CENTER);
private JLabel labelBeamsDeck = new JLabel("Beams Deck", SwingConstants.CENTER);
private JLabel labelWindowDeck = new JLabel("Window Deck", SwingConstants.CENTER);
private JLabel labelAdditionalColor = new JLabel("Additi Color", SwingConstants.CENTER);
private JLabel labelNumberOfDecks = new JLabel("Numb Of decks");
private JSpinner spinnerSpeed = new JSpinner();
private JSpinner spinnerWeight = new JSpinner();
private JSpinner spinnerNumberOfDecks = new JSpinner();
private JCheckBox checkBoxPipes = new JCheckBox("Have a Ship Pipes");
private JCheckBox checkBoxFuelTank = new JCheckBox("Have a Fuel Tank");
private JComponent panelObject = new JPanel();
private JPanel panelColorRed = new JPanel();
private JPanel panelColorGreen = new JPanel();
private JPanel panelColorBlue = new JPanel();
private JPanel panelColorYellow = new JPanel();
private JPanel panelColorBlack = new JPanel();
private JPanel panelColorWhite = new JPanel();
private JPanel panelColorGray = new JPanel();
private JPanel panelColorCyan = new JPanel();
private JButton buttonAdd = new JButton("Add");
private JButton buttonCansel = new JButton("Cancel");
public FormShipConfig(String title, Dimension dimension) {
this.title = title;
this.dimension = dimension;
}
public void Init() {
SpinnerModel numSpeed = new SpinnerNumberModel(100, 100, 1000, 1);
SpinnerModel numWeight = new SpinnerNumberModel(100, 100, 1000, 1);
spinnerSpeed.setModel(numSpeed);
spinnerWeight.setModel(numWeight);
SpinnerModel numDecks = new SpinnerNumberModel(0, 0, 3, 1);
spinnerNumberOfDecks.setModel(numDecks);
panelObject = new Canvas();
panelObject.setBorder(BorderFactory.createLineBorder(Color.BLACK, 2));
spinnerSpeed.addChangeListener(new ChangeListener() {
@Override
public void stateChanged(ChangeEvent e) {
if (_ship == null) return;
_ship.EntityShip.setSpeed((int)spinnerSpeed.getValue());
}
});
spinnerWeight.addChangeListener(new ChangeListener() {
@Override
public void stateChanged(ChangeEvent e) {
if (_ship == null) return;
_ship.EntityShip.setWeight((int)spinnerWeight.getValue());
}
});
checkBoxPipes.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
if (_ship == null) return;
if (_ship.EntityShip instanceof EntityWarmlyShip warmlyShip) {
warmlyShip.setShipPipes(checkBoxPipes.isSelected());
panelObject.repaint();
}
}
});
checkBoxFuelTank.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
if (_ship == null) return;
if (_ship.EntityShip instanceof EntityWarmlyShip warmlyShip) {
warmlyShip.setFuelTank(checkBoxFuelTank.isSelected());
panelObject.repaint();
}
}
});
labelShip.setBackground(Color.WHITE);
labelShip.setBorder(BorderFactory.createLineBorder(Color.BLACK, 2));
labelWarmlyShip.setBackground(Color.WHITE);
labelWarmlyShip.setBorder(BorderFactory.createLineBorder(Color.BLACK, 2));
labelBodyColor.setBorder(BorderFactory.createLineBorder(Color.BLACK, 2));
labelAdditionalColor.setBorder(BorderFactory.createLineBorder(Color.BLACK, 2));
labelSolidDeck.setBorder(BorderFactory.createLineBorder(Color.BLACK, 2));
labelBeamsDeck.setBorder(BorderFactory.createLineBorder(Color.BLACK, 2));
labelWindowDeck.setBorder(BorderFactory.createLineBorder(Color.BLACK, 2));
MouseAdapter labelObjectsMouseDown = new MouseAdapter() {
@Override
public void mousePressed(MouseEvent e) {
((JLabel) e.getComponent()).getTransferHandler().exportAsDrag(((JLabel) e.getComponent()), e, TransferHandler.COPY);
}
};
TransferHandler labelObjectsTransferHandler = new TransferHandler() {
@Override
public int getSourceActions(JComponent c) {
return TransferHandler.COPY;
}
@Override
protected Transferable createTransferable(JComponent c) {
return new StringSelection(((JLabel) c).getText());
}
};
labelShip.addMouseListener(labelObjectsMouseDown);
labelShip.setTransferHandler(labelObjectsTransferHandler);
labelWarmlyShip.addMouseListener(labelObjectsMouseDown);
labelWarmlyShip.setTransferHandler(labelObjectsTransferHandler);
MouseAdapter labelDecksMouseDown = new MouseAdapter() {
@Override
public void mousePressed(MouseEvent e) {
((JLabel) e.getComponent()).getTransferHandler().exportAsDrag(((JLabel) e.getComponent()), e, TransferHandler.COPY);
}
};
labelSolidDeck.addMouseListener(labelDecksMouseDown);
labelBeamsDeck.addMouseListener(labelDecksMouseDown);
labelWindowDeck.addMouseListener(labelDecksMouseDown);
labelSolidDeck.setTransferHandler(new TransferHandler() {
@Override
public int getSourceActions(JComponent c) {return TransferHandler.COPY;}
@Override
protected Transferable createTransferable(JComponent c) {
return new DecksTransferable(new DrawingDecksType1());
}
});
labelBeamsDeck.setTransferHandler(new TransferHandler() {
@Override
public int getSourceActions(JComponent c) {return TransferHandler.COPY;}
@Override
protected Transferable createTransferable(JComponent c) {
return new DecksTransferable(new DrawingDecksType2());
}
});
labelWindowDeck.setTransferHandler(new TransferHandler() {
@Override
public int getSourceActions(JComponent c) {return TransferHandler.COPY;}
@Override
protected Transferable createTransferable(JComponent c) {
return new DecksTransferable(new DrawingDecksType3());
}
});
panelObject.setTransferHandler(new TransferHandler() {
@Override
public boolean canImport(TransferHandler.TransferSupport support) {
return support.isDataFlavorSupported(DataFlavor.stringFlavor)
|| support.isDataFlavorSupported(DecksTransferable.decksDataFlavor);
}
@Override
public boolean importData(TransferHandler.TransferSupport support) {
if (canImport(support)) {
try {
String data = (String) support.getTransferable().getTransferData(DataFlavor.stringFlavor);
switch (data) {
case "Ship":
_ship = new DrawingShip((int) spinnerSpeed.getValue(), (int) spinnerWeight.getValue(),
Color.WHITE);
break;
case "WarmlyShip":
_ship = new DrawingWarmlyShip((int) spinnerSpeed.getValue(), (int) spinnerWeight.getValue(),
Color.WHITE, Color.BLACK, checkBoxPipes.isSelected(), checkBoxFuelTank.isSelected());
break;
}
if (_ship != null) {
_ship.SetPictureSize(155,155);
_ship.SetPosition(5,10);
}
else return false;
}
catch (UnsupportedFlavorException | IOException e) {}
try {
IDifferentDecks decks =
(IDifferentDecks) support.getTransferable().getTransferData(DecksTransferable.decksDataFlavor);
_ship.drawingDecks = decks;
_ship.drawingDecks.setNumberOfDecks((int) spinnerNumberOfDecks.getValue());
}catch (UnsupportedFlavorException | IOException e) {}
panelObject.repaint();
return true;
}
return false;
}
});
JPanel[] colorPanels = {
panelColorRed,
panelColorGreen,
panelColorBlue,
panelColorYellow,
panelColorWhite,
panelColorBlack,
panelColorGray,
panelColorCyan,
};
panelColorRed.setBackground(Color.RED);
panelColorGreen.setBackground(Color.GREEN);
panelColorBlue.setBackground(Color.BLUE);
panelColorYellow.setBackground(Color.YELLOW);
panelColorWhite.setBackground(Color.WHITE);
panelColorBlack.setBackground(Color.BLACK);
panelColorGray.setBackground(Color.GRAY);
panelColorCyan.setBackground(Color.CYAN);
MouseAdapter colorMouseDown = new MouseAdapter() {
@Override
public void mousePressed(MouseEvent e) {
((JPanel) e.getComponent()).getTransferHandler().exportAsDrag(((JPanel) e.getComponent()), e, TransferHandler.COPY);
}
};
for (var panelColor : colorPanels) {
panelColor.addMouseListener(colorMouseDown);
panelColor.setTransferHandler(new ColorTransferHandler());
}
labelBodyColor.setTransferHandler(new TransferHandler() {
@Override
public boolean canImport(TransferHandler.TransferSupport support) {
return support.isDataFlavorSupported(ColorTransferable.colorDataFlavor);
}
@Override
public boolean importData(TransferSupport support) {
try {
Color color = (Color) support.getTransferable().getTransferData(ColorTransferable.colorDataFlavor);
if (_ship == null) return false;
_ship.EntityShip.setBodyColor(color);
return true;
} catch (UnsupportedFlavorException | IOException e) {
e.printStackTrace();
}
return false;
}
});
labelAdditionalColor.setTransferHandler(new TransferHandler() {
@Override
public boolean canImport(TransferHandler.TransferSupport support) {
if (!(_ship instanceof DrawingWarmlyShip)) return false;
return support.isDataFlavorSupported(ColorTransferable.colorDataFlavor);
}
@Override
public boolean importData(TransferSupport support) {
try {
Color color = (Color) support.getTransferable().getTransferData(ColorTransferable.colorDataFlavor);
if (_ship == null) return false;
if (_ship.EntityShip instanceof EntityWarmlyShip warmlyShip) {
warmlyShip.setAdditionalColor(color);
labelColor.setBackground(color);
return true;
}
return false;
} catch (UnsupportedFlavorException | IOException e) {
e.printStackTrace();
}
return false;
}
});
buttonAdd.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
if (_ship == null) return;
DrawingShip copyShip;
if (_ship instanceof DrawingWarmlyShip)
copyShip = new DrawingWarmlyShip((EntityWarmlyShip) _ship.EntityShip, _ship.drawingDecks);
else
copyShip = new DrawingShip(_ship.EntityShip, _ship.drawingDecks);
company._collection.Insert(copyShip);
FormShipCollection.canvasShow();
dispose();
}
});
buttonCansel.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
dispose();
}
});
labelSpeed.setBounds(10, 17, 50, 15);
labelWeight.setBounds(10,43, 50, 15);
labelNumberOfDecks.setBounds(10, 68, 50, 15);
labelShip.setBounds(10,150,70,30);
labelWarmlyShip.setBounds(10,190,70,30);
labelColor.setBounds(170,10,30,15);
labelBodyColor.setBounds(500,5,75, 40);
labelAdditionalColor.setBounds(580,5,75,40);
labelSolidDeck.setBounds(120, 210, 100, 40);
labelBeamsDeck.setBounds(230, 210, 100,40);
labelWindowDeck.setBounds(340,210,100,40);
spinnerSpeed.setBounds(60,15, 60,20);
spinnerWeight.setBounds(60,40, 60,20);
spinnerNumberOfDecks.setBounds(60, 65,60,20);
checkBoxPipes.setBounds(8,85,150,20);
checkBoxFuelTank.setBounds(8,105,150,20);
panelObject.setBounds(500,50,160,150);
panelColorRed.setBounds(170, 30, 40, 40);
panelColorGreen.setBounds(220, 30, 40,40);
panelColorBlue.setBounds(270,30,40,40);
panelColorYellow.setBounds(320,30,40,40);
panelColorWhite.setBounds(170, 80,40,40);
panelColorBlack.setBounds(220,80,40,40);
panelColorGray.setBounds(270,80,40,40);
panelColorCyan.setBounds(320,80,40,40);
buttonAdd.setBounds(500, 210, 70, 40);
buttonCansel.setBounds(585, 210, 70, 40);
setSize(dimension.width, dimension.height);
setLayout(null);
add(labelSpeed);
add(labelWeight);
add(labelNumberOfDecks);
add(labelShip);
add(labelWarmlyShip);
add(labelColor);
add(labelBodyColor);
add(labelAdditionalColor);
add(labelSolidDeck);
add(labelSolidDeck);
add(labelBeamsDeck);
add(labelWindowDeck);
add(spinnerSpeed);
add(spinnerWeight);
add(spinnerNumberOfDecks);
add(checkBoxPipes);
add(checkBoxFuelTank);
add(panelObject);
add(panelColorRed);
add(panelColorGreen);
add(panelColorBlue);
add(panelColorYellow);
add(panelColorWhite);
add(panelColorBlack);
add(panelColorGray);
add(panelColorCyan);
add(buttonAdd);
add(buttonCansel);
setVisible(true);
}
public void setCompany(AbstractCompany company) {
this.company = company;
}
private class Canvas extends JComponent {
public Canvas() {
}
public void paintComponent(Graphics g) {
if (_ship == null) {
return;
}
super.paintComponents(g);
Graphics2D g2d = (Graphics2D) g;
_ship.DrawTransport(g2d);
super.repaint();
}
}
private class ColorTransferable implements Transferable {
private Color color;
private static final DataFlavor colorDataFlavor = new DataFlavor(Color.class, "Color");
public ColorTransferable(Color color) {
this.color = color;
}
@Override
public DataFlavor[] getTransferDataFlavors() {
return new DataFlavor[]{colorDataFlavor};
}
@Override
public boolean isDataFlavorSupported(DataFlavor flavor) {
return colorDataFlavor.equals(flavor);
}
@Override
public Object getTransferData(DataFlavor flavor) throws UnsupportedFlavorException {
if (isDataFlavorSupported(flavor)) {
return color;
} else {
throw new UnsupportedFlavorException(flavor);
}
}
}
private class ColorTransferHandler extends TransferHandler {
@Override
public int getSourceActions(JComponent c) {
return TransferHandler.COPY;
}
@Override
protected Transferable createTransferable(JComponent c) {
return new ColorTransferable(c.getBackground());
}
}
private class DecksTransferable implements Transferable {
private IDifferentDecks decks;
private static final DataFlavor decksDataFlavor = new DataFlavor(IDifferentDecks.class, "Decks");
public DecksTransferable(IDifferentDecks decks) {
this.decks = decks;
}
@Override
public DataFlavor[] getTransferDataFlavors() {
return new DataFlavor[]{decksDataFlavor};
}
@Override
public boolean isDataFlavorSupported(DataFlavor flavor) {
return flavor.equals(decksDataFlavor);
}
@Override
public Object getTransferData(DataFlavor flavor) throws UnsupportedFlavorException {
if (isDataFlavorSupported(flavor)) {
return decks;
} else {
throw new UnsupportedFlavorException(flavor);
}
}
}
}