PIbd-21_MasenkinMS_LabWork04 #4

Closed
Factorino73 wants to merge 2 commits from LabWork04 into LabWork03
4 changed files with 283 additions and 122 deletions
Showing only changes of commit 1a883f7970 - Show all commits

View File

@ -8,64 +8,6 @@
<properties/>
<border type="none"/>
<children>
<grid id="8de60" binding="toolsPanel" layout-manager="GridLayoutManager" row-count="6" column-count="1" same-size-horizontally="false" same-size-vertically="false" hgap="-1" vgap="-1">
<margin top="0" left="0" bottom="0" right="0"/>
<constraints>
<grid row="0" column="1" row-span="1" col-span="1" vsize-policy="3" hsize-policy="3" anchor="4" fill="2" indent="0" use-parent-layout="false"/>
</constraints>
<properties/>
<border type="none"/>
<children>
<component id="5fb24" class="javax.swing.JTextField" binding="textField">
<constraints>
<grid row="2" column="0" row-span="1" col-span="1" vsize-policy="0" hsize-policy="6" anchor="0" fill="0" indent="0" use-parent-layout="false">
<preferred-size width="150" height="-1"/>
</grid>
</constraints>
<properties/>
</component>
<component id="4c213" class="javax.swing.JButton" binding="buttonRemoveBus">
<constraints>
<grid row="3" column="0" row-span="1" col-span="1" vsize-policy="0" hsize-policy="3" anchor="0" fill="1" indent="0" use-parent-layout="false"/>
</constraints>
<properties>
<text value="Удалить автобус"/>
</properties>
</component>
<component id="2fbac" class="javax.swing.JButton" binding="buttonAddBus">
<constraints>
<grid row="1" column="0" row-span="1" col-span="1" vsize-policy="0" hsize-policy="3" anchor="0" fill="0" indent="0" use-parent-layout="false"/>
</constraints>
<properties>
<text value="Добавить автобус"/>
</properties>
</component>
<component id="ef2b7" class="javax.swing.JButton" binding="buttonRefreshCollection">
<constraints>
<grid row="4" column="0" row-span="1" col-span="1" vsize-policy="0" hsize-policy="3" anchor="0" fill="0" indent="0" use-parent-layout="false"/>
</constraints>
<properties>
<text value=" Обновить коллекцию"/>
</properties>
</component>
<component id="ddf17" class="javax.swing.JLabel" binding="toolsLabel">
<constraints>
<grid row="0" column="0" row-span="1" col-span="1" vsize-policy="0" hsize-policy="0" anchor="9" fill="0" indent="0" use-parent-layout="false"/>
</constraints>
<properties>
<text value="Инструменты"/>
</properties>
</component>
<component id="37e63" class="javax.swing.JButton" binding="buttonGenerateBus">
<constraints>
<grid row="5" column="0" row-span="1" col-span="1" vsize-policy="0" hsize-policy="3" anchor="0" fill="1" indent="0" use-parent-layout="false"/>
</constraints>
<properties>
<text value="Сгенерировать автобус"/>
</properties>
</component>
</children>
</grid>
<grid id="8237" binding="pictureBoxCollection" layout-manager="GridLayoutManager" row-count="1" column-count="1" same-size-horizontally="false" same-size-vertically="false" hgap="-1" vgap="-1">
<margin top="0" left="0" bottom="0" right="0"/>
<constraints>
@ -75,6 +17,107 @@
<border type="none"/>
<children/>
</grid>
<grid id="afc9e" binding="toolsPanel" layout-manager="GridLayoutManager" row-count="11" column-count="1" same-size-horizontally="false" same-size-vertically="false" hgap="-1" vgap="-1">
<margin top="0" left="0" bottom="0" right="0"/>
<constraints>
<grid row="0" column="1" row-span="1" col-span="1" vsize-policy="3" hsize-policy="3" anchor="4" fill="2" indent="0" use-parent-layout="false"/>
</constraints>
<properties/>
<border type="none"/>
<children>
<component id="a57ce" class="javax.swing.JTextField" binding="textFieldNumber">
<constraints>
<grid row="6" column="0" row-span="1" col-span="1" vsize-policy="0" hsize-policy="6" anchor="0" fill="0" indent="0" use-parent-layout="false">
<preferred-size width="150" height="-1"/>
</grid>
</constraints>
<properties/>
</component>
<component id="d50cb" class="javax.swing.JButton" binding="buttonRemoveBus">
<constraints>
<grid row="7" column="0" row-span="1" col-span="1" vsize-policy="0" hsize-policy="3" anchor="0" fill="0" indent="0" use-parent-layout="false"/>
</constraints>
<properties>
<text value="Удалить автобус"/>
</properties>
</component>
<component id="3dc96" class="javax.swing.JButton" binding="buttonAddBus">
<constraints>
<grid row="5" column="0" row-span="1" col-span="1" vsize-policy="0" hsize-policy="3" anchor="0" fill="0" indent="0" use-parent-layout="false"/>
</constraints>
<properties>
<text value="Добавить автобус"/>
</properties>
</component>
<component id="9cc50" class="javax.swing.JButton" binding="buttonRefreshCollection">
<constraints>
<grid row="8" column="0" row-span="1" col-span="1" vsize-policy="0" hsize-policy="3" anchor="0" fill="0" indent="0" use-parent-layout="false"/>
</constraints>
<properties>
<horizontalTextPosition value="0"/>
<text value=" Обновить коллекцию"/>
</properties>
</component>
<component id="354c6" class="javax.swing.JLabel" binding="toolsLabel">
<constraints>
<grid row="0" column="0" row-span="1" col-span="1" vsize-policy="0" hsize-policy="0" anchor="9" fill="0" indent="0" use-parent-layout="false"/>
</constraints>
<properties>
<text value="Инструменты"/>
</properties>
</component>
<component id="2a7de" class="javax.swing.JButton" binding="buttonGenerateBus">
<constraints>
<grid row="9" column="0" row-span="1" col-span="1" vsize-policy="0" hsize-policy="3" anchor="0" fill="0" indent="0" use-parent-layout="false"/>
</constraints>
<properties>
<horizontalTextPosition value="0"/>
<text value="Сгенерировать автобус"/>
</properties>
</component>
<component id="61fbd" class="javax.swing.JTextField" binding="textFieldStorage">
<constraints>
<grid row="1" column="0" row-span="1" col-span="1" vsize-policy="0" hsize-policy="6" anchor="0" fill="0" indent="0" use-parent-layout="false">
<preferred-size width="150" height="-1"/>
</grid>
</constraints>
<properties/>
</component>
<component id="b20a4" class="javax.swing.JButton" binding="buttonAddObject">
<constraints>
<grid row="2" column="0" row-span="1" col-span="1" vsize-policy="0" hsize-policy="3" anchor="0" fill="0" indent="0" use-parent-layout="false"/>
</constraints>
<properties>
<text value="Добавить набор"/>
</properties>
</component>
<component id="93129" class="javax.swing.JList" binding="listStorages">
<constraints>
<grid row="3" column="0" row-span="1" col-span="1" vsize-policy="6" hsize-policy="2" anchor="0" fill="3" indent="0" use-parent-layout="false">
<preferred-size width="150" height="50"/>
</grid>
</constraints>
<properties/>
</component>
<component id="98ed2" class="javax.swing.JButton" binding="buttonDeleteObject">
<constraints>
<grid row="4" column="0" row-span="1" col-span="1" vsize-policy="0" hsize-policy="3" anchor="0" fill="0" indent="0" use-parent-layout="false"/>
</constraints>
<properties>
<text value="Удалить набор"/>
</properties>
</component>
<component id="e67a1" class="javax.swing.JButton" binding="buttonShowDeletedBus">
<constraints>
<grid row="10" column="0" row-span="1" col-span="1" vsize-policy="0" hsize-policy="3" anchor="0" fill="0" indent="0" use-parent-layout="false"/>
</constraints>
<properties>
<horizontalTextPosition value="0"/>
<text value="Показать удаленный автобус"/>
</properties>
</component>
</children>
</grid>
</children>
</grid>
</form>

View File

@ -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<DrawingBus, DrawingObjectBus> _buses;
private final BusGenericStorage _storage;
// Набор удаленных объектов
private final LinkedList<DrawingBus> _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<DrawingBus>();
listModel = new DefaultListModel<String>();
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);
}
}

View File

@ -42,8 +42,7 @@ public class BusGenericCollection<T extends DrawingBus, U extends IMoveableObjec
public T minus(int pos) {
T obj = _collection.Get(pos);
if (obj != null)
{
if (obj != null) {
_collection.Remove(pos);
}
@ -79,18 +78,19 @@ public class BusGenericCollection<T extends DrawingBus, U extends IMoveableObjec
private void DrawObjects(Graphics g) {
int width = _pictureWidth / _placeSizeWidth;
int height = _pictureHeight / _placeSizeHeight;
for (int i = 0; i < _collection.Count; i++) {
// Получение объекта
var obj = _collection.Get(i);
if (obj != null) {
int i = 0;
for (T bus : _collection.GetBuses(_collection.Count())) {
if (bus != null) {
// Установка позиции
obj.SetPosition(
bus.SetPosition(
(int)((width - 1) * _placeSizeWidth - (i % width * _placeSizeWidth)),
(int)((height - 1) * _placeSizeHeight - (i / width * _placeSizeHeight))
);
// Прорисовка объекта
obj.DrawTransport(g);
bus.DrawTransport(g);
}
i++;
}
}
}

View File

@ -1,17 +1,26 @@
package AccordionBus;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.NoSuchElementException;
// Параметризованный набор рбъектов
public class SetGeneric<T extends Object> {
// Массив объектов, которые храним
private final Object[] _places;
// Список объектов, которые храним
private final ArrayList<T> _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<T>(count);
}
// Добавление объекта в набор
@ -22,58 +31,61 @@ public class SetGeneric<T extends Object> {
// Добавление объекта в набор на конкретную позицию
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<T> GetBuses(final Integer maxBuses) {
return new Iterable<T>() {
@Override
public Iterator<T> iterator() {
return new Iterator<T>() {
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();
}
};
}
};
}
}