From 1a883f79706b53026f2aed71c37385ee3b79a036 Mon Sep 17 00:00:00 2001 From: Factorino73 Date: Sat, 11 Nov 2023 21:55:29 +0400 Subject: [PATCH 1/2] PIbd-21_MasenkinMS_LabWork04 --- AccordionBus/BusCollectionForm.form | 159 ++++++++++++++++--------- AccordionBus/BusCollectionForm.java | 144 +++++++++++++++++++--- AccordionBus/BusGenericCollection.java | 16 +-- AccordionBus/SetGeneric.java | 86 +++++++------ 4 files changed, 283 insertions(+), 122 deletions(-) diff --git a/AccordionBus/BusCollectionForm.form b/AccordionBus/BusCollectionForm.form index 046e602..117aad5 100644 --- a/AccordionBus/BusCollectionForm.form +++ b/AccordionBus/BusCollectionForm.form @@ -8,64 +8,6 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - @@ -75,6 +17,107 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/AccordionBus/BusCollectionForm.java b/AccordionBus/BusCollectionForm.java index 52c26f2..67a6a16 100644 --- a/AccordionBus/BusCollectionForm.java +++ b/AccordionBus/BusCollectionForm.java @@ -1,12 +1,18 @@ package AccordionBus; import javax.swing.*; +import javax.swing.event.ListSelectionEvent; +import javax.swing.event.ListSelectionListener; import java.awt.*; +import java.util.LinkedList; +import java.util.Random; // Форма для работы с набором объектов класса DrawingBus public class BusCollectionForm extends JFrame { // Набор объектов - private final BusGenericCollection _buses; + private final BusGenericStorage _storage; + // Набор удаленных объектов + private final LinkedList _deletedBuses; // Выбранный автобус public DrawingBus SelectedBus; private FrameBusGeneric frameBusGeneric; @@ -17,26 +23,76 @@ public class BusCollectionForm extends JFrame { } private JPanel pictureBoxCollection; private JButton buttonAddBus; - private JTextField textField; + private JTextField textFieldNumber; private JButton buttonRemoveBus; private JButton buttonRefreshCollection; private JPanel toolsPanel; private JLabel toolsLabel; private JButton buttonGenerateBus; + private JTextField textFieldStorage; + private JButton buttonAddObject; + private DefaultListModel listModel; + private JList listStorages; + private JButton buttonDeleteObject; + private JButton buttonShowDeletedBus; // Конструктор public BusCollectionForm() { pictureBoxCollection.setSize(new Dimension(700, 450)); - _buses = new BusGenericCollection<>(pictureBoxCollection.getWidth(), pictureBoxCollection.getHeight()); + _storage = new BusGenericStorage(pictureBoxCollection.getWidth(), pictureBoxCollection.getHeight()); + _deletedBuses = new LinkedList(); + listModel = new DefaultListModel(); + listStorages.setModel(listModel); + // Добавление набора + buttonAddObject.addActionListener(e -> { + if (textFieldStorage.getText().length() == 0) { + JOptionPane.showMessageDialog(null, "Не все данные заполнены", "Ошибка", JOptionPane.ERROR_MESSAGE); + return; + } + _storage.AddSet(textFieldStorage.getText()); + ReloadObjects(); + }); + + // Выбор набора + listStorages.addListSelectionListener(new ListSelectionListener() { + @Override + public void valueChanged(ListSelectionEvent e) { + Refresh(); + } + }); + + // Удаление набора + buttonDeleteObject.addActionListener(e -> { + if (listStorages.getSelectedIndex() == -1) { + return; + } + + if (JOptionPane.showConfirmDialog(null, "Удалить объект " + listStorages.getSelectedValue() + "?", "Удаление", JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION) { + _storage.DelSet(listStorages.getSelectedValue().toString()); + ReloadObjects(); + } + }); + + // Добавление объета в набор buttonAddBus.addActionListener(e -> { + if (listStorages.getSelectedIndex() == -1) { + return; + } + + var obj = _storage.get(listStorages.getSelectedValue().toString()); + if (obj == null) { + return; + } + FrameAccordionBus frameAccordionBus = new FrameAccordionBus(); frameAccordionBus.setVisible(true); + frameAccordionBus.accordionBusForm.buttonSelectBus.addActionListener(ev -> { SelectedBus = frameAccordionBus.accordionBusForm.drawingBus; frameAccordionBus.dispose(); if (SelectedBus != null) { - if (_buses.plus(SelectedBus) > -2) { + if (obj.plus(SelectedBus) > -2) { Refresh(); JOptionPane.showMessageDialog(this.getMainPanel(), "Объект добавлен", "Успех", JOptionPane.INFORMATION_MESSAGE); } @@ -47,32 +103,39 @@ public class BusCollectionForm extends JFrame { }); }); + // Удаление объекта из набора buttonRemoveBus.addActionListener(e -> { - Object[] options = {"Да", "Нет"}; - int n = JOptionPane.showOptionDialog(this.getMainPanel(), "Удалить объект?", "Удаление", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE, null, options, options[0]); - if (n == 1) { + if (listStorages.getSelectedIndex() == -1) { return; } - try { - int pos = Integer.parseInt(textField.getText()); - if (_buses.minus(pos) != null) { - Refresh(); - JOptionPane.showMessageDialog(this.getMainPanel(), "Объект удален", "Успех", JOptionPane.INFORMATION_MESSAGE); - } - else { - JOptionPane.showMessageDialog(this.getMainPanel(), "Не удалось удалить объект", "Ошибка", JOptionPane.ERROR_MESSAGE); - } + var obj = _storage.get(listStorages.getSelectedValue().toString()); + if (obj == null) { + return; } - catch (Exception ex) { - JOptionPane.showMessageDialog(this.getMainPanel(), "Неверное значение", "Ошибка", JOptionPane.ERROR_MESSAGE); + + if (JOptionPane.showConfirmDialog(null, "Удалить объект?", "Удаление", JOptionPane.YES_NO_OPTION) == JOptionPane.NO_OPTION) { + return; + } + + int pos = Integer.parseInt(textFieldNumber.getText()); + var removed = obj.minus(pos); + if (removed != null) { + _deletedBuses.add(removed); + JOptionPane.showMessageDialog(null, "Объект удален", "Удаление", JOptionPane.INFORMATION_MESSAGE); + Refresh(); + } + else { + JOptionPane.showMessageDialog(null, "Не удалось удалить объект", "Удаление", JOptionPane.INFORMATION_MESSAGE); } }); + // Обновить коллекцию buttonRefreshCollection.addActionListener(e -> { Refresh(); }); + // Сгенерировать автобус buttonGenerateBus.addActionListener(e -> { if (frameBusGeneric != null) { frameBusGeneric.dispose(); @@ -81,12 +144,55 @@ public class BusCollectionForm extends JFrame { frameBusGeneric = new FrameBusGeneric(); frameBusGeneric.setVisible(true); }); + + // Показать удаленный автобус + buttonShowDeletedBus.addActionListener(e -> { + if (_deletedBuses.size() == 0) { + JOptionPane.showMessageDialog(null, "Удаленные автобусы отсутствуют", "Ошибка", JOptionPane.ERROR_MESSAGE); + return; + } + + Random random = new Random(); + FrameAccordionBus frameAccordionBus = new FrameAccordionBus(); + frameAccordionBus.setVisible(true); + frameAccordionBus.accordionBusForm.drawingBus = _deletedBuses.pop(); + frameAccordionBus.accordionBusForm.drawingBus.SetPosition(random.nextInt(100), random.nextInt(100)); + frameAccordionBus.accordionBusForm.Draw(); + frameAccordionBus.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); + }); + } + + // Заполнение ListBoxObject + private void ReloadObjects() { + int index = listStorages.getSelectedIndex(); + + listModel.clear(); + for (String key : _storage.Keys()) { + listModel.addElement(key); + } + + if (listModel.size() > 0 && (index == -1 || index >= listModel.size())) { + listStorages.setSelectedIndex(0); + } + else if (listModel.size() > 0 && index > -1 && index < listModel.size()) { + listStorages.setSelectedIndex(index); + } } // Обновить картинку public void Refresh() { Graphics g = mainPanel.getGraphics(); mainPanel.paint(g); - _buses.ShowBuses(g); + + if (listStorages.getSelectedIndex() == -1) { + return; + } + + var obj = _storage.get(listStorages.getSelectedValue().toString()); + if (obj == null) { + return; + } + + obj.ShowBuses(g); } } diff --git a/AccordionBus/BusGenericCollection.java b/AccordionBus/BusGenericCollection.java index f36dc77..379e4aa 100644 --- a/AccordionBus/BusGenericCollection.java +++ b/AccordionBus/BusGenericCollection.java @@ -42,8 +42,7 @@ public class BusGenericCollection { - // Массив объектов, которые храним - private final Object[] _places; + // Список объектов, которые храним + private final ArrayList _places; - // Количество объектов в массиве - public int Count; + // Количество объектов в списке + public int Count() { + return _places.size(); + } + + // Максимальное количество объектов в списке + private final int _maxCount; // Конструктор public SetGeneric(int count) { - _places = new Object[count]; - Count = count; + _maxCount = count; + _places = new ArrayList(count); } // Добавление объекта в набор @@ -22,58 +31,61 @@ public class SetGeneric { // Добавление объекта в набор на конкретную позицию public int Insert(T bus, int position) { // Проверка позиции - if (position < 0 || position >= Count) { + if (position < 0 || position >= _maxCount) { return -1; } - // Проверка, что элемент массива по этой позиции пустой - if (_places[position] != null) { - // Проверка, что после вставляемого элемента в массиве есть пустой элемент - int index = -1; - for (int i = position + 1; i < Count; i++) { - if (_places[i] == null) { - index = i; - break; - } - } - - // Проверка, если пустого элемента нет - if (index == -1) { - return -1; - } - - // Сдвиг всех объектов, находящихся справа от позиции до первого пустого элемента - int j = index - 1; - while (j >= position) { - _places[j + 1] = _places[j]; - j--; - } - } - // Вставка по позиции - _places[position] = bus; + _places.add(position, bus); return position; } // Удаление объекта из набора с конкретной позиции public boolean Remove(int position) { // Проверка позиции - if (position < 0 || position >= Count) { + if (position < 0 || position >= _maxCount) { return false; } - // Удаление объекта из массива, присвоив элементу массива значение null - _places[position] = null; + // Удаление объекта из списка + _places.remove(position); return true; } // Получение объекта из набора по позиции public T Get(int position) { // Проверка позиции - if (position < 0 || position >= Count) { + if (position < 0 || position >= _maxCount) { return null; } - return (T)_places[position]; + return _places.get(position); + } + + // Проход по списку + public Iterable GetBuses(final Integer maxBuses) { + return new Iterable() { + @Override + public Iterator iterator() { + return new Iterator() { + private int currentIndex = 0; + private int count = 0; + + @Override + public boolean hasNext() { + return (currentIndex < Count()) && (maxBuses == null || count < maxBuses); + } + + @Override + public T next() { + if (hasNext()) { + count++; + return _places.get(currentIndex++); + } + throw new NoSuchElementException(); + } + }; + } + }; } } -- 2.25.1 From b636a9becb80b99510d6280001ea544499cbc6cf Mon Sep 17 00:00:00 2001 From: Factorino73 Date: Sat, 18 Nov 2023 23:27:56 +0400 Subject: [PATCH 2/2] Bug fix --- AccordionBus/BusGenericStorage.java | 62 +++++++++++++++++++++++++++++ 1 file changed, 62 insertions(+) create mode 100644 AccordionBus/BusGenericStorage.java diff --git a/AccordionBus/BusGenericStorage.java b/AccordionBus/BusGenericStorage.java new file mode 100644 index 0000000..70e119d --- /dev/null +++ b/AccordionBus/BusGenericStorage.java @@ -0,0 +1,62 @@ +package AccordionBus; + +import java.util.HashMap; +import java.util.List; +import java.util.stream.Collectors; + +// Класс для хранения коллекции +public class BusGenericStorage { + // Словарь (хранилище) + final HashMap> _busStorages; + + // Возвращение списка названий наборов + public List Keys() { + return _busStorages.keySet().stream().collect(Collectors.toList()); + } + + // Ширина окна отрисовки + private final int _pictureWidth; + + // Высота окна отрисовки + private final int _pictureHeight; + + // Конструктор + public BusGenericStorage(int pictureWidth, int pictureHeight) { + _busStorages = new HashMap>(); + _pictureWidth = pictureWidth; + _pictureHeight = pictureHeight; + } + + // Добавление набора + public void AddSet(String name) { + _busStorages.put(name, new BusGenericCollection(_pictureWidth, _pictureHeight)); + } + + // Удаление набора + public void DelSet(String name) { + // Проверка наличия ключа + if (!_busStorages.containsKey(name)) { + return; + } + + _busStorages.remove(name); + } + + // Доступ к набору + public BusGenericCollection get(String ind) { + // Проверка наличия ключа + if (_busStorages.containsKey(ind)) { + return _busStorages.get(ind); + } + return null; + } + + // Доступ к объекту из набору + public DrawingObjectBus get(String ind1, int ind2) { + // Проверка наличия ключа + if (_busStorages.containsKey(ind1)) { + return _busStorages.get(ind1).GetU(ind2); + } + return null; + } +} -- 2.25.1