PIbd-23. Yunusov N.N. Lab work 06 Hard #6

Closed
Yunusov_Niyaz wants to merge 5 commits from Lab6 into Lab5
6 changed files with 398 additions and 59 deletions

View File

@ -1,10 +1,18 @@
import java.awt.*;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
public class BusesGenericCollection<T extends DrawingBus, U extends IMoveableObject> {
private int _pictureWidth;
private int _pictureHeight;
private final int _placeSizeWidth = 210;
private final int _placeSizeHeight = 135;
private SetGeneric<T> _collection;
public static char _separatorRecords = ';';
public static char _separatorForObject = ':';
public BusesGenericCollection(int picWidth, int picHeight) {
int width = picWidth / _placeSizeWidth;
int height = picHeight / _placeSizeHeight;
@ -12,36 +20,40 @@ public class BusesGenericCollection<T extends DrawingBus, U extends IMoveableObj
_pictureHeight = picHeight;
_collection = new SetGeneric<T>(width * height);
}
public void showBuses(Graphics2D g){
public void showBuses(Graphics2D g) {
drawBackground(g);
drawObjects(g);
}
public boolean insert(T obj)
{
public int getCount(){return _collection.getCount();}
public boolean insert(T obj) {
if (obj != null)
return _collection.insert(obj);
return false;
}
public boolean remove(int pos)
{
public boolean remove(int pos) {
return _collection.remove(pos);
}
public U GetU(int pos) {
if(_collection.Get(pos) == null)
if (_collection.Get(pos) == null)
return null;
return (U)_collection.Get(pos).GetMoveableObject();
return (U) _collection.Get(pos).GetMoveableObject();
}
public T Get(int position){
if(position < 0 || position >= _collection.getCount())
public T Get(int position) {
if (position < 0 || position >= _collection.getCount())
return null;
return _collection.Get(position);
}
private void drawBackground(Graphics2D g) {
BasicStroke pen = new BasicStroke(3);
g.setStroke(pen);
for (int i = 0; i < _pictureWidth / _placeSizeWidth; i++) {
for (int j = 0; j < _pictureHeight / _placeSizeHeight +
1; ++j) { g.drawLine(i * _placeSizeWidth, j *
1; ++j) {g.drawLine(i * _placeSizeWidth, j *
_placeSizeHeight, i * _placeSizeWidth + _placeSizeWidth / 2, j *
_placeSizeHeight);
}
@ -49,10 +61,10 @@ public class BusesGenericCollection<T extends DrawingBus, U extends IMoveableObj
_placeSizeWidth, _pictureHeight / _placeSizeHeight * _placeSizeHeight);
}
}
private void drawObjects(Graphics2D g) {
for(int i =0;i <_collection.getCount(); i++)
{
DrawingBus bus =_collection.Get(i);
for (int i = 0; i < _collection.getCount(); i++) {
DrawingBus bus = _collection.Get(i);
if (bus != null) {
int inRow = _pictureWidth / _placeSizeWidth;
bus.setPosition(_placeSizeWidth * (inRow - 1) - (i % inRow * _placeSizeWidth), i / inRow * _placeSizeHeight);
@ -60,5 +72,35 @@ public class BusesGenericCollection<T extends DrawingBus, U extends IMoveableObj
}
}
}
public ArrayList<T> GetBuses(){
return _collection.GetBuses(_collection.getCount());
}
public boolean SaveData(File f, String name) throws IOException {
if(f.exists()) {
f.delete();
}
f.createNewFile();
StringBuilder data = new StringBuilder();
data.append("BusCollection\n");
data.append(String.format("%s\n", name));
StringBuilder records = new StringBuilder();
for(DrawingBus elem : GetBuses())
{
records.append(String.format("%s%c", ExtentionDrawingBus.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);
}
}

View File

@ -1,8 +1,114 @@
import java.util.HashMap;
import java.util.List;
import java.util.stream.Collectors;
import javax.xml.crypto.dsig.keyinfo.KeyValue;
import java.io.*;
import java.util.*;
import java.util.Queue;
public class BusesGenericStorage {
final HashMap<String, BusesGenericCollection<DrawingBus, DrawingObjectBus>> _busStorages;
public HashMap<String, BusesGenericCollection<DrawingBus, DrawingObjectBus>> _busStorages;
private static final char _separatorForKeyValue = '|';
private final char _separatorRecords = ';';
private static final char _separatorForObject = ':';
public boolean SaveData(File f) throws IOException {
if(f.exists()) {
f.delete();
}
f.createNewFile();
StringBuilder data = new StringBuilder();
data.append("BusStorage\n");
for(Map.Entry<String, BusesGenericCollection<DrawingBus, DrawingObjectBus>> record : _busStorages.entrySet()){
StringBuilder records = new StringBuilder();
for(DrawingBus elem : record.getValue().GetBuses())
{
records.append(String.format("%s%c", ExtentionDrawingBus.GetDataForSave(elem, _separatorForObject),
_separatorRecords));
}
data.append(String.format("%s%c%s\n", record.getKey(), _separatorForKeyValue, records.toString()));
}
if(data.length() == 0)
return false;
FileWriter writer = new FileWriter(f);
writer.write(data.toString());
writer.flush();
writer.close();
return true;
}
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("BusStorage"))
return false;
_busStorages.clear();
for(String data : strs){
String st = new String("\\" + Character.toString( _separatorForKeyValue));
String[]record = data.split(st);
if (record.length != 2)
continue;
BusesGenericCollection<DrawingBus, DrawingObjectBus> collection =
new BusesGenericCollection<>(_pictureWidth, _pictureHeight);
String[] set = record[1].split(Character.toString(_separatorRecords));
for(int i = set.length -1; i >=0; i--){
String elem = set[i];
DrawingBus bus = ExtentionDrawingBus.CreateDrawingBus(elem,
_separatorForObject, _pictureWidth, _pictureHeight);
if (bus != null)
{
if (!(collection.insert(bus)))
{
return false;
}
}
}
_busStorages.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("BusCollection"))
return false;
String collectionName = strs[1];
BusesGenericCollection<DrawingBus, DrawingObjectBus> collection = getCollection(collectionName);
if(collection == null)
collection = new BusesGenericCollection<>(_pictureWidth, _pictureHeight);
else
collection.Clear();
String[] busesInfo = strs[2].split(Character.toString(BusesGenericCollection._separatorRecords));
for(int i = busesInfo.length-1; i >= 0; i--){
String data = busesInfo[i];
DrawingBus bus = ExtentionDrawingBus.CreateDrawingBus(data,
BusesGenericCollection._separatorForObject, _pictureWidth, _pictureHeight);
if (bus != null)
{
if (!(collection.insert(bus)))
{
return false;
}
}
}
AddSetFromFile(collectionName, collection);
return true;
}
public List<String> Keys(){
if(_busStorages == null)
return null;
@ -23,9 +129,12 @@ public class BusesGenericStorage {
_busStorages.put(name, new BusesGenericCollection<>(_pictureWidth, _pictureHeight));
}
public void delSet(String name){
public void delSet(String name, Queue<DrawingBus> trashBox){
if(!_busStorages.containsKey(name))
return;
BusesGenericCollection<DrawingBus, DrawingObjectBus> cur = _busStorages.get(name);
for(int i = 0; i < cur.getCount(); i++)
trashBox.add(cur.Get(i));
_busStorages.remove(name);
}
@ -38,4 +147,13 @@ public class BusesGenericStorage {
public DrawingBus Get(String collectionName, int position){
return _busStorages.get(collectionName).Get(position);
}
public void AddSetFromFile(String name, BusesGenericCollection<DrawingBus, DrawingObjectBus> toAdd){
if(_busStorages.containsKey(name)){
_busStorages.remove(name);
}
_busStorages.put(name, toAdd);
}
public BusesGenericCollection<DrawingBus, DrawingObjectBus> GetCollection(String collectionName){
return _busStorages.get(collectionName);
}
}

View File

@ -23,7 +23,7 @@ public class DrawingBus {
public int getHeight() {
return busHeight;
}
private IDrawDoors drawingDoors;
public IDrawDoors drawingDoors;
public DrawingBus(int speed, double weight, Color bodyColor, int width, int height, int doorsNumber, int doorsType) {
if (width < busWidth || height < busHeight)
return;

View File

@ -0,0 +1,75 @@
import java.awt.*;
public class ExtentionDrawingBus {
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 DrawingBus CreateDrawingBus(String info, char separatorForObject, int width, int height){
String[] strs = info.split(Character.toString(separatorForObject));
if(strs.length == 5){
return new DrawingBus(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 DrawingTrolleybus(Integer.parseInt(strs[0]),
Integer.parseInt(strs[1]), getColor(strs[2]),
getColor(strs[7]),Boolean.parseBoolean(strs[5]),
Boolean.parseBoolean(strs[6]), width, height,
Integer.parseInt(strs[3]), Integer.parseInt(strs[4]));
}
return null;
}
public static String GetDataForSave(DrawingBus DrawingBus, char separatorForObject){
var bus = DrawingBus.getEntityBus();
if(bus == null)
return null;
var str = String.format("%d%c%d%c%s%c%d%c%d", bus.getSpeed(),
separatorForObject, (int)bus.getWeight(),
separatorForObject, getName(bus.getBodyColor()),
separatorForObject, DrawingBus.drawingDoors.getType(),
separatorForObject, DrawingBus.drawingDoors.getNumber());
if(!(bus instanceof EntityTrolleybus)){
return str;
}
return String.format("%s%c%b%c%b%c%s", str, separatorForObject,
((EntityTrolleybus) bus).getRoga(), separatorForObject,
((EntityTrolleybus) bus).getBattery(), separatorForObject,
getName(((EntityTrolleybus) bus).getAdditionalColor()));
}
}

View File

@ -1,13 +1,12 @@
import javax.swing.*;
import javax.swing.border.StrokeBorder;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;
import java.util.List;
import java.util.Objects;
import java.util.ArrayDeque;
import java.util.Queue;
import java.io.File;
public class FrameBusCollection extends JFrame {
private BusesGenericStorage storage;
@ -16,18 +15,20 @@ public class FrameBusCollection extends JFrame {
JComponent pictureBoxCollection;
TextField textFieldNumber;
TextField textFieldStorageName;
Queue <DrawingBus> queue = new ArrayDeque<>();
public FrameBusCollection(){
Queue<DrawingBus> trashCollection = new ArrayDeque<>();
public FrameBusCollection() {
super("Набор автобусов");
setSize(new Dimension(1000,500));
setSize(new Dimension(1000, 500));
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
createGui();
storage = new BusesGenericStorage(pictureBoxCollection.getWidth(),pictureBoxCollection.getHeight());
storage = new BusesGenericStorage(pictureBoxCollection.getWidth(), pictureBoxCollection.getHeight());
setVisible(true);
}
private void createGui(){
pictureBoxCollection = new JComponent(){
public void paintComponent(Graphics graphics){
private void createGui() {
pictureBoxCollection = new JComponent() {
public void paintComponent(Graphics graphics) {
super.paintComponent(graphics);
Graphics2D graphics2D = (Graphics2D) graphics;
if (listBoxStorages == null || storage == null)
@ -39,7 +40,19 @@ public class FrameBusCollection extends JFrame {
super.repaint();
}
};
pictureBoxCollection.setSize(new Dimension(700,450));
JMenuBar menuFile = new JMenuBar();
JMenu file = new JMenu("Файл");
menuFile.add(file);
JMenuItem saveFile = new JMenuItem("Сохранить");
JMenuItem loadFile = new JMenuItem("Загрузить");
JMenuItem saveCollection = new JMenuItem("Сохранить коллекцию");
JMenuItem loadCollection = new JMenuItem("Загрузить коллекцию");
file.add(saveCollection);
file.add(loadCollection);
file.add(saveFile);
file.add(loadFile);
setJMenuBar(menuFile);
pictureBoxCollection.setSize(new Dimension(700, 450));
JButton buttonAddBus = new JButton("Добавить автобус");
textFieldNumber = new TextField();
textFieldStorageName = new TextField();
@ -48,7 +61,7 @@ public class FrameBusCollection extends JFrame {
JButton buttonRefreshCollection = new JButton("Обновить коллекцию");
JButton buttonAddCollection = new JButton("Добавить набор");
listBoxModel = new DefaultListModel<>();
listBoxStorages= new JList<>(listBoxModel);
listBoxStorages = new JList<>(listBoxModel);
scrollPane.setViewportView(listBoxStorages);
JButton buttonDeleteCollection = new JButton("Удалить набор");
JButton buttonTrash = new JButton("Корзина");
@ -58,13 +71,17 @@ public class FrameBusCollection extends JFrame {
buttonAddCollection.addActionListener(e -> buttonAddCollectionClick());
buttonDeleteCollection.addActionListener(e -> buttonDeleteCollectionClick());
buttonTrash.addActionListener(e -> buttonTrashClick());
saveFile.addActionListener(e -> saveFile());
saveCollection.addActionListener(e -> saveCollection());
loadFile.addActionListener(e -> loadFile());
loadCollection.addActionListener(e -> loadCollection());
JPanel panelTools = new JPanel(new GridBagLayout());
panelTools.setBorder(new StrokeBorder(new BasicStroke(3)));
JPanel panelCollection = new JPanel(new GridBagLayout());
panelCollection.setBorder(new StrokeBorder(new BasicStroke(3)));
GridBagConstraints constraints = new GridBagConstraints();
constraints.insets.left = constraints.insets.right = 5;
constraints.insets.top = constraints.insets.bottom = 5;
constraints.insets.left = constraints.insets.right = 5;
constraints.insets.top = constraints.insets.bottom = 4;
constraints.fill = GridBagConstraints.BOTH;
constraints.gridx = 0;
constraints.gridy = 0;
@ -96,33 +113,31 @@ public class FrameBusCollection extends JFrame {
constraints.gridx = 0;
constraints.gridy = 5;
panelTools.add(buttonTrash, constraints);
setLayout(new BorderLayout());
add(panelTools, BorderLayout.EAST);
add(pictureBoxCollection,BorderLayout.CENTER);
add(pictureBoxCollection, BorderLayout.CENTER);
}
private void buttonAddBusClick(){
if(listBoxStorages.getSelectedIndex() == -1) {
private void buttonAddBusClick() {
if (listBoxStorages.getSelectedIndex() == -1) {
return;
}
BusesGenericCollection<DrawingBus, DrawingObjectBus> drawingBuses = storage.getCollection(listBoxStorages.getSelectedValue());
FrameBusConfig frameBusConfig = new FrameBusConfig();
frameBusConfig.addButton.addActionListener(e -> {
if (drawingBuses.insert(frameBusConfig.drawingBus))
{
if (drawingBuses.insert(frameBusConfig.drawingBus)) {
frameBusConfig.dispose();
frameBusConfig.drawingBus.pictureWidth = pictureBoxCollection.getWidth();
frameBusConfig.drawingBus.pictureHeight = pictureBoxCollection.getHeight();
JOptionPane.showMessageDialog(null, "Объект добавлен", "Информация", JOptionPane.INFORMATION_MESSAGE);
pictureBoxCollection.repaint();
}
else
{
} else {
JOptionPane.showMessageDialog(null, "Не удалось добавить объект", "Информация", JOptionPane.INFORMATION_MESSAGE);
}
});
frameBusConfig.cancelButton.addActionListener(e -> frameBusConfig.dispose());
}
private void buttonRemoveBusClick() {
if (listBoxStorages.getSelectedIndex() == -1)
return;
@ -130,34 +145,34 @@ public class FrameBusCollection extends JFrame {
if (obj == null)
return;
int pos = Integer.parseInt(textFieldNumber.getText());
queue.add(obj.Get(pos));
if (obj.remove(pos))
{
JOptionPane.showMessageDialog(this,"Объект удалён");
trashCollection.add(obj.Get(pos));
if (obj.remove(pos)) {
JOptionPane.showMessageDialog(this, "Объект удалён");
pictureBoxCollection.repaint();
}
else
{
JOptionPane.showMessageDialog(this,"Не удалось удалить объект");
} else {
JOptionPane.showMessageDialog(this, "Не удалось удалить объект");
}
}
private void buttonRefreshBusClick(){
private void buttonRefreshBusClick() {
pictureBoxCollection.repaint();
}
private void reloadObjects(){
private void reloadObjects() {
int index = listBoxStorages.getSelectedIndex();
listBoxModel.clear();
List<String> keys = storage.Keys();
for (String key : keys) {
listBoxModel.addElement(key);
}
if(listBoxModel.size() > 0 && (index == -1 || index >= listBoxModel.size()))
if (listBoxModel.size() > 0 && (index == -1 || index >= listBoxModel.size()))
listBoxStorages.setSelectedIndex(0);
else if(listBoxModel.size() > 0)
else if (listBoxModel.size() > 0)
listBoxStorages.setSelectedIndex(index);
}
private void buttonAddCollectionClick() {
if(textFieldStorageName.getText() == null ) {
if (textFieldStorageName.getText() == null) {
JOptionPane.showMessageDialog(this, "Не все данные заполнены");
return;
}
@ -169,23 +184,92 @@ public class FrameBusCollection extends JFrame {
storage.addSet(name);
reloadObjects();
}
private void buttonDeleteCollectionClick() {
if (listBoxStorages.getSelectedIndex() == -1)
return;
storage.delSet(listBoxStorages.getSelectedValue());
storage.delSet(listBoxStorages.getSelectedValue(), trashCollection);
reloadObjects();
}
private void buttonTrashClick(){
if(queue.size() == 0)
private void buttonTrashClick() {
if (trashCollection.size() == 0)
return;
FrameTrolleybus frame;
try{
try {
frame = new FrameTrolleybus();
frame.ChangeTrolleybus(queue.peek());
queue.remove();
}
catch (IOException e){
frame.ChangeTrolleybus(trashCollection.peek());
trashCollection.remove();
} catch (IOException e) {
throw new RuntimeException();
}
}
private void saveFile() {
JFileChooser fc = new JFileChooser("C:\\Users\\niyaz\\OneDrive\\Документы");
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 saveCollection() {
JFileChooser fc = new JFileChooser("C:\\Users\\niyaz\\OneDrive\\Документы");
fc.addChoosableFileFilter(new TxtSaveFilter());
int retrieval = fc.showSaveDialog(null);
if (retrieval == JFileChooser.APPROVE_OPTION) {
File file = new File(fc.getSelectedFile() + "." + "txt");
try {
if (listBoxStorages.getSelectedIndex() == -1) {
return;
}
storage._busStorages.get(listBoxStorages.getSelectedValue()).SaveData(file, listBoxStorages.getSelectedValue());
reloadObjects();
} catch (IOException ex) {
throw new RuntimeException(ex);
}
}
}
private void loadFile() {
JFileChooser fc = new JFileChooser("C:\\Users\\niyaz\\OneDrive\\Документы");
fc.addChoosableFileFilter(new TxtSaveFilter());
int ret = fc.showDialog(null, "Открыть файл");
if (ret == JFileChooser.APPROVE_OPTION) {
File file = fc.getSelectedFile();
try {
storage.LoadData(file);
reloadObjects();
pictureBoxCollection.repaint();
} catch (IOException ex) {
throw new RuntimeException(ex);
}
}
}
private void loadCollection() {
JFileChooser fc = new JFileChooser("C:\\Users\\niyaz\\OneDrive\\Документы");
int ret = fc.showDialog(null, "Открыть файл");
if (ret == JFileChooser.APPROVE_OPTION) {
File file = fc.getSelectedFile();
try {
storage.LoadCollection(file);
reloadObjects();
pictureBoxCollection.repaint();
} catch (IOException ex) {
throw new RuntimeException(ex);
}
}
}
}

20
src/TxtSaveFilter.java Normal file
View File

@ -0,0 +1,20 @@
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";
}
}