Compare commits

...

7 Commits

Author SHA1 Message Date
e76067faa2 PIbd-21_MasenkinMS_LabWork05 2023-11-22 18:41:34 +04:00
b636a9becb Bug fix 2023-11-18 23:27:56 +04:00
1a883f7970 PIbd-21_MasenkinMS_LabWork04 2023-11-11 21:55:29 +04:00
28468bcf41 Add additions 2023-11-11 21:45:36 +04:00
879902a606 PIbd-21_MasenkinMS_LabWork03 2023-11-11 21:42:32 +04:00
b664cc97ff PIbd-21_MasenkinMS_LabWork02 2023-10-24 21:15:37 +04:00
5da451e1b5 PIbd-21_MasenkinMS_LabWork01 2023-10-24 20:22:03 +04:00
48 changed files with 2743 additions and 2 deletions

View File

@ -1,4 +1,3 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ProjectRootManager" version="2" languageLevel="JDK_20" default="true" project-jdk-name="20" project-jdk-type="JavaSDK">
<output url="file://$PROJECT_DIR$/out" />

View File

@ -0,0 +1,86 @@
package AccordionBus;
// Класс-стратегия перемещения объекта
public abstract class AbstractStrategy {
// Перемещаемый объект
private IMoveableObject _moveableObject;
// Статус перемещения
private Status _state = Status.NotInit;
// Ширина поля
protected int FieldWidth;
// Высота поля
protected int FieldHeight;
// Статус перемещения
public Status GetStatus() { return _state; }
// Установка данных
public void SetData(IMoveableObject moveableObject, int width, int height) {
if (moveableObject == null) {
_state = Status.NotInit;
return;
}
_state = Status.InProgress;
_moveableObject = moveableObject;
FieldWidth = width;
FieldHeight = height;
}
// Шаг перемещения
public void MakeStep() {
if (_state != Status.InProgress) {
return;
}
if (IsTargetDestination()) {
_state = Status.Finish;
return;
}
MoveToTarget();
}
// Перемещение влево
protected boolean MoveLeft() { return MoveTo(DirectionType.Left); }
// Перемещение вправо
protected boolean MoveRight() { return MoveTo(DirectionType.Right); }
// Перемещение вверх
protected boolean MoveUp() { return MoveTo(DirectionType.Up); }
// Перемещение вниз
protected boolean MoveDown() { return MoveTo(DirectionType.Down); }
// Параметры объекта
protected ObjectParameters GetObjectParameters() { return _moveableObject.GetObjectPosition(); }
// Шаг объекта
protected int GetStep() {
if (_state != Status.InProgress)
{
return 0;
}
return _moveableObject.GetStep();
}
// Перемещение к цели
protected abstract void MoveToTarget();
// Достигнута ли цель
protected abstract boolean IsTargetDestination();
// Попытка перемещения в требуемом направлении
private boolean MoveTo(DirectionType directionType) {
if (_state != Status.InProgress) {
return false;
}
if (_moveableObject.CheckCanMove(directionType)) {
_moveableObject.MoveObject(directionType);
return true;
}
return false;
}
}

View File

@ -0,0 +1,135 @@
<?xml version="1.0" encoding="UTF-8"?>
<form xmlns="http://www.intellij.com/uidesigner/form/" version="1" bind-to-class="AccordionBus.AccordionBusForm">
<grid id="27dc6" binding="pictureBox" layout-manager="GridLayoutManager" row-count="2" column-count="2" same-size-horizontally="false" same-size-vertically="false" hgap="-1" vgap="-1">
<margin top="0" left="0" bottom="0" right="0"/>
<constraints>
<xy x="20" y="20" width="792" height="400"/>
</constraints>
<properties/>
<border type="none"/>
<children>
<grid id="b336e" binding="createPanel" layout-manager="GridLayoutManager" row-count="1" column-count="3" same-size-horizontally="false" same-size-vertically="false" hgap="-1" vgap="-1">
<margin top="0" left="0" bottom="0" right="0"/>
<constraints>
<grid row="1" column="0" row-span="1" col-span="1" vsize-policy="3" hsize-policy="3" anchor="10" fill="0" indent="0" use-parent-layout="false"/>
</constraints>
<properties/>
<border type="none"/>
<children>
<component id="7b96e" class="javax.swing.JButton" binding="buttonCreateAccordionBus">
<constraints>
<grid row="0" column="0" row-span="1" col-span="1" vsize-policy="0" hsize-policy="3" anchor="10" fill="0" indent="0" use-parent-layout="false"/>
</constraints>
<properties>
<text value="Создать автобус-гармошку"/>
</properties>
</component>
<component id="5708d" class="javax.swing.JButton" binding="buttonCreateBus">
<constraints>
<grid row="0" column="1" row-span="1" col-span="1" vsize-policy="3" hsize-policy="3" anchor="10" fill="0" indent="0" use-parent-layout="false"/>
</constraints>
<properties>
<text value="Создать автобус"/>
</properties>
</component>
<component id="7cf79" class="javax.swing.JButton" binding="buttonSelectBus">
<constraints>
<grid row="0" column="2" row-span="1" col-span="1" vsize-policy="0" hsize-policy="3" anchor="10" fill="0" indent="0" use-parent-layout="false"/>
</constraints>
<properties>
<text value="Выбрать автобус"/>
</properties>
</component>
</children>
</grid>
<vspacer id="b9759">
<constraints>
<grid row="0" column="0" row-span="1" col-span="1" vsize-policy="6" hsize-policy="1" anchor="0" fill="2" indent="0" use-parent-layout="false"/>
</constraints>
</vspacer>
<grid id="5a846" binding="movePanel" layout-manager="GridLayoutManager" row-count="2" column-count="3" same-size-horizontally="false" same-size-vertically="false" hgap="-1" vgap="-1">
<margin top="0" left="0" bottom="0" right="0"/>
<constraints>
<grid row="1" column="1" row-span="1" col-span="1" vsize-policy="3" hsize-policy="3" anchor="6" fill="0" indent="0" use-parent-layout="false"/>
</constraints>
<properties/>
<border type="none"/>
<children>
<component id="67e80" class="javax.swing.JButton" binding="buttonRight">
<constraints>
<grid row="1" column="2" row-span="1" col-span="1" vsize-policy="0" hsize-policy="3" anchor="0" fill="0" indent="0" use-parent-layout="false">
<maximum-size width="30" height="30"/>
</grid>
</constraints>
<properties>
<icon value="AccordionBus/img/Right.png"/>
<text value=""/>
</properties>
</component>
<component id="a51a7" class="javax.swing.JButton" binding="buttonDown">
<constraints>
<grid row="1" column="1" row-span="1" col-span="1" vsize-policy="0" hsize-policy="3" anchor="0" fill="0" indent="0" use-parent-layout="false">
<maximum-size width="30" height="30"/>
</grid>
</constraints>
<properties>
<icon value="AccordionBus/img/Down.png"/>
<text value=""/>
</properties>
</component>
<component id="32158" class="javax.swing.JButton" binding="buttonLeft">
<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">
<maximum-size width="30" height="30"/>
</grid>
</constraints>
<properties>
<icon value="AccordionBus/img/Left.png"/>
<text value=""/>
</properties>
</component>
<component id="3b3f5" class="javax.swing.JButton" binding="buttonUp">
<constraints>
<grid row="0" column="1" row-span="1" col-span="1" vsize-policy="0" hsize-policy="3" anchor="0" fill="0" indent="0" use-parent-layout="false">
<maximum-size width="30" height="30"/>
</grid>
</constraints>
<properties>
<icon value="AccordionBus/img/Up.png"/>
<text value=""/>
</properties>
</component>
</children>
</grid>
<grid id="da58b" binding="strategyPanel" layout-manager="GridLayoutManager" row-count="3" 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="0" hsize-policy="0" anchor="5" fill="0" indent="0" use-parent-layout="false"/>
</constraints>
<properties/>
<border type="none"/>
<children>
<component id="2959" class="javax.swing.JComboBox" binding="comboBoxStrategy">
<constraints>
<grid row="0" column="0" row-span="1" col-span="1" vsize-policy="0" hsize-policy="2" anchor="5" fill="0" indent="0" use-parent-layout="false"/>
</constraints>
<properties/>
</component>
<vspacer id="5e742">
<constraints>
<grid row="2" column="0" row-span="1" col-span="1" vsize-policy="6" hsize-policy="1" anchor="0" fill="2" indent="0" use-parent-layout="false"/>
</constraints>
</vspacer>
<component id="8c54d" class="javax.swing.JButton" binding="buttonStep">
<constraints>
<grid row="1" 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>
</children>
</grid>
</form>

View File

@ -0,0 +1,143 @@
package AccordionBus;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionListener;
import java.util.Random;
public class AccordionBusForm {
public DrawingBus drawingBus;
private AbstractStrategy abstractStrategy;
private JPanel pictureBox;
public JPanel getPictureBox() {
return pictureBox;
}
private JPanel createPanel;
private JButton buttonCreateAccordionBus;
private JPanel movePanel;
private JButton buttonLeft;
private JButton buttonDown;
private JButton buttonRight;
private JButton buttonUp;
private JPanel strategyPanel;
private JPanel controlPanel;
private JButton buttonCreateBus;
private JComboBox comboBoxStrategy;
private JButton buttonStep;
public JButton buttonSelectBus;
public AccordionBusForm() {
buttonUp.setName("buttonUp");
buttonDown.setName("buttonDown");
buttonLeft.setName("buttonLeft");
buttonRight.setName("buttonRight");
comboBoxStrategy.addItem("MoveToCenter");
comboBoxStrategy.addItem("MoveToBorder");
buttonCreateAccordionBus.addActionListener(e -> {
Random random = new Random();
Color bodyColor = JColorChooser.showDialog(this.pictureBox, "Выберите цвет", Color.BLACK);
Color additionalColor = JColorChooser.showDialog(this.pictureBox, "Выберите дополнительный цвет", Color.BLACK);
drawingBus = new DrawingAccordionBus(random.nextInt(100, 300),
random.nextInt(1000, 3000),
bodyColor,
additionalColor,
random.nextBoolean(),
random.nextBoolean(),
pictureBox.getWidth(),
pictureBox.getHeight());
drawingBus.SetPosition(random.nextInt(10, 100),
random.nextInt(10, 100));
Draw();
});
buttonCreateBus.addActionListener(e -> {
Random random = new Random();
Color bodyColor = JColorChooser.showDialog(this.pictureBox, "Выберите цвет", Color.BLACK);
drawingBus = new DrawingBus(random.nextInt(100, 300),
random.nextInt(1000, 3000),
bodyColor,
pictureBox.getWidth(),
pictureBox.getHeight());
drawingBus.SetPosition(random.nextInt(10, 100),
random.nextInt(10, 100));
Draw();
});
ActionListener buttonMoveClickedListener = e -> {
String name = ((JButton)e.getSource()).getName();
switch (name) {
case "buttonUp" -> {
drawingBus.MoveTransport(DirectionType.Up);
}
case "buttonDown" -> {
drawingBus.MoveTransport(DirectionType.Down);
}
case "buttonLeft" -> {
drawingBus.MoveTransport(DirectionType.Left);
}
case "buttonRight" -> {
drawingBus.MoveTransport(DirectionType.Right);
}
}
Draw();
};
buttonStep.addActionListener(e -> {
if (drawingBus == null) {
return;
}
if (comboBoxStrategy.isEnabled()) {
switch (comboBoxStrategy.getSelectedIndex()) {
case 0:
abstractStrategy = new MoveToCenter();
break;
case 1:
abstractStrategy = new MoveToBorder();
break;
default:
abstractStrategy = null;
break;
}
if (abstractStrategy == null) {
return;
}
abstractStrategy.SetData(new DrawingObjectBus(drawingBus),
pictureBox.getWidth(),
pictureBox.getHeight());
comboBoxStrategy.setEditable(false);
}
if (abstractStrategy == null) {
return;
}
abstractStrategy.MakeStep();
Draw();
if (abstractStrategy.GetStatus() == Status.Finish) {
comboBoxStrategy.setEnabled(true);
abstractStrategy = null;
}
});
buttonUp.addActionListener(buttonMoveClickedListener);
buttonDown.addActionListener(buttonMoveClickedListener);
buttonLeft.addActionListener(buttonMoveClickedListener);
buttonRight.addActionListener(buttonMoveClickedListener);
}
public void Draw() {
if (drawingBus == null) {
return;
}
Graphics g = pictureBox.getGraphics();
pictureBox.paint(g);
drawingBus.DrawTransport(g);
}
}

View File

@ -0,0 +1,123 @@
<?xml version="1.0" encoding="UTF-8"?>
<form xmlns="http://www.intellij.com/uidesigner/form/" version="1" bind-to-class="AccordionBus.BusCollectionForm">
<grid id="27dc6" binding="mainPanel" layout-manager="GridLayoutManager" row-count="1" column-count="2" same-size-horizontally="false" same-size-vertically="false" hgap="-1" vgap="-1">
<margin top="0" left="0" bottom="0" right="0"/>
<constraints>
<xy x="20" y="20" width="500" height="400"/>
</constraints>
<properties/>
<border type="none"/>
<children>
<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>
<grid row="0" column="0" row-span="1" col-span="1" vsize-policy="3" hsize-policy="3" anchor="0" fill="3" indent="0" use-parent-layout="false"/>
</constraints>
<properties/>
<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

@ -0,0 +1,200 @@
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 BusGenericStorage _storage;
// Набор удаленных объектов
private final LinkedList<DrawingBus> _deletedBuses;
// Выбранный автобус
public DrawingBus SelectedBus;
private FrameBusGeneric frameBusGeneric;
private JPanel mainPanel;
public JPanel getMainPanel() {
return mainPanel;
}
private JPanel pictureBoxCollection;
private JButton buttonAddBus;
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));
_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;
}
FrameBusConfig frameBusConfig = new FrameBusConfig();
frameBusConfig.setVisible(true);
frameBusConfig.busConfigForm.addButton.addActionListener(ev -> {
SelectedBus = frameBusConfig.busConfigForm._bus;
frameBusConfig.dispose();
if (SelectedBus != null) {
if (obj.plus(SelectedBus) > -2) {
Refresh();
JOptionPane.showMessageDialog(this.getMainPanel(), "Объект добавлен", "Успех", JOptionPane.INFORMATION_MESSAGE);
}
else {
JOptionPane.showMessageDialog(this.getMainPanel(), " Объект не добавлен", "Ошибка", JOptionPane.INFORMATION_MESSAGE);
}
}
});
frameBusConfig.busConfigForm.cancelButton.addActionListener(ee -> frameBusConfig.dispose());
});
// Удаление объекта из набора
buttonRemoveBus.addActionListener(e -> {
if (listStorages.getSelectedIndex() == -1) {
return;
}
var obj = _storage.get(listStorages.getSelectedValue().toString());
if (obj == null) {
return;
}
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();
}
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);
if (listStorages.getSelectedIndex() == -1) {
return;
}
var obj = _storage.get(listStorages.getSelectedValue().toString());
if (obj == null) {
return;
}
obj.ShowBuses(g);
}
}

View File

@ -0,0 +1,300 @@
<?xml version="1.0" encoding="UTF-8"?>
<form xmlns="http://www.intellij.com/uidesigner/form/" version="1" bind-to-class="AccordionBus.BusConfigForm">
<grid id="27dc6" binding="configPanel" layout-manager="GridLayoutManager" row-count="2" column-count="3" same-size-horizontally="false" same-size-vertically="false" hgap="-1" vgap="-1">
<margin top="0" left="0" bottom="0" right="0"/>
<constraints>
<xy x="20" y="20" width="883" height="400"/>
</constraints>
<properties/>
<border type="none"/>
<children>
<grid id="2f0df" binding="objectPanel" layout-manager="GridLayoutManager" row-count="2" column-count="3" 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="2" vsize-policy="3" hsize-policy="3" anchor="0" fill="3" indent="0" use-parent-layout="false"/>
</constraints>
<properties/>
<border type="etched"/>
<children>
<component id="20f52" class="javax.swing.JLabel" binding="bodyColorLabel">
<constraints>
<grid row="0" column="0" row-span="1" col-span="1" vsize-policy="0" hsize-policy="0" anchor="1" fill="0" indent="0" use-parent-layout="false"/>
</constraints>
<properties>
<text value="Осн. цвет"/>
</properties>
</component>
<component id="da4f5" class="javax.swing.JLabel" binding="additionalColorLabel">
<constraints>
<grid row="0" column="1" row-span="1" col-span="1" vsize-policy="0" hsize-policy="0" anchor="1" fill="0" indent="0" use-parent-layout="false"/>
</constraints>
<properties>
<text value="Доп. цвет"/>
</properties>
</component>
<component id="c025e" class="javax.swing.JLabel" binding="doorsTypeLabel">
<constraints>
<grid row="0" column="2" row-span="1" col-span="1" vsize-policy="0" hsize-policy="0" anchor="1" fill="0" indent="0" use-parent-layout="false"/>
</constraints>
<properties>
<text value="Тип дверей"/>
</properties>
</component>
<grid id="31030" binding="pictureBoxPanel" 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>
<grid row="1" column="0" row-span="1" col-span="3" vsize-policy="3" hsize-policy="3" anchor="0" fill="3" indent="0" use-parent-layout="false"/>
</constraints>
<properties/>
<border type="line"/>
<children/>
</grid>
</children>
</grid>
<component id="e7176" class="javax.swing.JButton" binding="addButton">
<constraints>
<grid row="1" column="1" 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="44b67" class="javax.swing.JButton" binding="cancelButton">
<constraints>
<grid row="1" column="2" 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>
<grid id="77ec7" binding="parametersPanel" layout-manager="GridLayoutManager" row-count="5" column-count="5" 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="0" row-span="2" col-span="1" vsize-policy="3" hsize-policy="3" anchor="0" fill="3" indent="0" use-parent-layout="false"/>
</constraints>
<properties/>
<border type="etched" title="Параметры"/>
<children>
<component id="ac4f6" class="javax.swing.JLabel" binding="speedSpinnerLabel">
<constraints>
<grid row="0" column="0" row-span="1" col-span="1" vsize-policy="0" hsize-policy="0" anchor="8" fill="0" indent="0" use-parent-layout="false"/>
</constraints>
<properties>
<labelFor value="a8b1d"/>
<text value="Скорость:"/>
</properties>
</component>
<component id="97f64" class="javax.swing.JLabel" binding="weightSpinnerLabel">
<constraints>
<grid row="1" column="0" row-span="1" col-span="1" vsize-policy="0" hsize-policy="0" anchor="8" fill="0" indent="0" use-parent-layout="false"/>
</constraints>
<properties>
<labelFor value="ba8dc"/>
<text value="Вес:"/>
</properties>
</component>
<component id="8413" class="javax.swing.JLabel" binding="doorsSpinnerLabel">
<constraints>
<grid row="2" column="0" row-span="1" col-span="1" vsize-policy="0" hsize-policy="0" anchor="8" fill="0" indent="0" use-parent-layout="false"/>
</constraints>
<properties>
<labelFor value="a9cd0"/>
<text value="Количество&#10; дверей:"/>
</properties>
</component>
<component id="a8b1d" class="javax.swing.JSpinner" binding="speedSpinner">
<constraints>
<grid row="0" column="1" row-span="1" col-span="1" vsize-policy="0" hsize-policy="6" anchor="8" fill="1" indent="0" use-parent-layout="false"/>
</constraints>
<properties/>
</component>
<component id="ba8dc" class="javax.swing.JSpinner" binding="weightSpinner">
<constraints>
<grid row="1" column="1" row-span="1" col-span="1" vsize-policy="0" hsize-policy="6" anchor="8" fill="1" indent="0" use-parent-layout="false"/>
</constraints>
<properties/>
</component>
<component id="a9cd0" class="javax.swing.JSpinner" binding="doorsSpinner">
<constraints>
<grid row="2" column="1" row-span="1" col-span="1" vsize-policy="0" hsize-policy="6" anchor="8" fill="1" indent="0" use-parent-layout="false"/>
</constraints>
<properties/>
</component>
<component id="69782" class="javax.swing.JCheckBox" binding="additionalBodyCheckBox">
<constraints>
<grid row="3" column="0" row-span="1" col-span="1" vsize-policy="0" hsize-policy="3" anchor="8" fill="0" indent="0" use-parent-layout="false"/>
</constraints>
<properties>
<text value="Дополнительный отсек"/>
</properties>
</component>
<component id="3f80a" class="javax.swing.JCheckBox" binding="additionalDoorCheckBox">
<constraints>
<grid row="4" column="0" row-span="1" col-span="1" vsize-policy="0" hsize-policy="3" anchor="8" fill="0" indent="0" use-parent-layout="false"/>
</constraints>
<properties>
<text value="Дополнительная дверь"/>
</properties>
</component>
<grid id="39012" binding="colorPanel" layout-manager="GridLayoutManager" row-count="2" column-count="4" 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="2" row-span="3" col-span="3" vsize-policy="3" hsize-policy="3" anchor="0" fill="3" indent="0" use-parent-layout="false"/>
</constraints>
<properties/>
<border type="etched" title="Цвета"/>
<children>
<grid id="38233" binding="redPanel" 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>
<grid row="0" column="0" row-span="1" col-span="1" vsize-policy="3" hsize-policy="3" anchor="0" fill="0" indent="0" use-parent-layout="false">
<minimum-size width="50" height="50"/>
<preferred-size width="50" height="50"/>
<maximum-size width="50" height="50"/>
</grid>
</constraints>
<properties>
<background color="-65536"/>
</properties>
<border type="none"/>
<children/>
</grid>
<grid id="f7c8a" binding="greenPanel" 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>
<grid row="0" column="1" row-span="1" col-span="1" vsize-policy="3" hsize-policy="3" anchor="0" fill="0" indent="0" use-parent-layout="false">
<minimum-size width="50" height="50"/>
<preferred-size width="50" height="50"/>
<maximum-size width="50" height="50"/>
</grid>
</constraints>
<properties>
<background color="-16711936"/>
</properties>
<border type="none"/>
<children/>
</grid>
<grid id="31ef7" binding="bluePanel" 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>
<grid row="0" column="2" row-span="1" col-span="1" vsize-policy="3" hsize-policy="3" anchor="0" fill="0" indent="0" use-parent-layout="false">
<minimum-size width="50" height="50"/>
<preferred-size width="50" height="50"/>
<maximum-size width="50" height="50"/>
</grid>
</constraints>
<properties>
<background color="-16776961"/>
</properties>
<border type="none"/>
<children/>
</grid>
<grid id="1cd3a" binding="yellowPanel" 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>
<grid row="0" column="3" row-span="1" col-span="1" vsize-policy="3" hsize-policy="3" anchor="0" fill="0" indent="0" use-parent-layout="false">
<minimum-size width="50" height="50"/>
<preferred-size width="50" height="50"/>
<maximum-size width="50" height="50"/>
</grid>
</constraints>
<properties>
<background color="-256"/>
</properties>
<border type="none"/>
<children/>
</grid>
<grid id="68a86" binding="whitePanel" 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>
<grid row="1" column="0" row-span="1" col-span="1" vsize-policy="3" hsize-policy="3" anchor="0" fill="0" indent="0" use-parent-layout="false">
<minimum-size width="50" height="50"/>
<preferred-size width="50" height="50"/>
<maximum-size width="50" height="50"/>
</grid>
</constraints>
<properties>
<background color="-1"/>
</properties>
<border type="none"/>
<children/>
</grid>
<grid id="f31b6" binding="grayPanel" 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>
<grid row="1" column="1" row-span="1" col-span="1" vsize-policy="3" hsize-policy="3" anchor="0" fill="0" indent="0" use-parent-layout="false">
<minimum-size width="50" height="50"/>
<preferred-size width="50" height="50"/>
<maximum-size width="50" height="50"/>
</grid>
</constraints>
<properties>
<background color="-8355712"/>
</properties>
<border type="none"/>
<children/>
</grid>
<grid id="95b8b" binding="blackPanel" 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>
<grid row="1" column="2" row-span="1" col-span="1" vsize-policy="3" hsize-policy="3" anchor="0" fill="0" indent="0" use-parent-layout="false">
<minimum-size width="50" height="50"/>
<preferred-size width="50" height="50"/>
<maximum-size width="50" height="50"/>
</grid>
</constraints>
<properties>
<background color="-16777216"/>
</properties>
<border type="none"/>
<children/>
</grid>
<grid id="d2e96" binding="magentaPanel" 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>
<grid row="1" column="3" row-span="1" col-span="1" vsize-policy="3" hsize-policy="3" anchor="0" fill="0" indent="0" use-parent-layout="false">
<minimum-size width="50" height="50"/>
<preferred-size width="50" height="50"/>
<maximum-size width="50" height="50"/>
</grid>
</constraints>
<properties>
<background color="-65281"/>
</properties>
<border type="none"/>
<children/>
</grid>
</children>
</grid>
<component id="dc93a" class="javax.swing.JLabel" binding="simpleObjectLabel">
<constraints>
<grid row="3" column="2" row-span="1" col-span="1" vsize-policy="0" hsize-policy="0" anchor="0" fill="0" indent="0" use-parent-layout="false"/>
</constraints>
<properties>
<name value="simpleObjectLabel"/>
<text value="Простой"/>
</properties>
</component>
<component id="a3a8e" class="javax.swing.JLabel" binding="modifiedObjectLabel">
<constraints>
<grid row="3" column="4" row-span="1" col-span="1" vsize-policy="0" hsize-policy="0" anchor="0" fill="0" indent="0" use-parent-layout="false"/>
</constraints>
<properties>
<name value="modifiedObjectLabel"/>
<text value="Продвинутый"/>
</properties>
</component>
<grid id="1f954" binding="componentPanel" 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>
<grid row="4" column="2" row-span="1" col-span="3" vsize-policy="3" hsize-policy="3" anchor="0" fill="3" indent="0" use-parent-layout="false"/>
</constraints>
<properties/>
<border type="none"/>
<children/>
</grid>
</children>
</grid>
</children>
</grid>
</form>

View File

@ -0,0 +1,257 @@
package AccordionBus;
import javax.swing.*;
import java.awt.*;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.UnsupportedFlavorException;
import java.io.Console;
import java.io.IOException;
public class BusConfigForm {
// Переменная выбранный автобус
DrawingBus _bus = null;
// Переменная выбранный тип дверей
IDrawingDoors _doors = null;
// Компоненты DoorComponent
DoorComponent doorComponentTypeOne = new DoorComponent(new DrawingDoorsTypeOne());
DoorComponent doorComponentTypeTwo = new DoorComponent(new DrawingDoorsTypeTwo());
DoorComponent doorComponentTypeThree = new DoorComponent(new DrawingDoorsTypeThree());
private JPanel configPanel;
public JPanel getConfigPanel() {
return configPanel;
}
private JPanel objectPanel;
public JButton addButton;
public JButton cancelButton;
private JLabel bodyColorLabel;
private JLabel additionalColorLabel;
private JLabel doorsTypeLabel;
private JPanel pictureBoxPanel;
private JPanel parametersPanel;
private JLabel speedSpinnerLabel;
private JLabel weightSpinnerLabel;
private JLabel doorsSpinnerLabel;
private JSpinner speedSpinner;
private JSpinner weightSpinner;
private JSpinner doorsSpinner;
private JCheckBox additionalBodyCheckBox;
private JCheckBox additionalDoorCheckBox;
private JPanel colorPanel;
private JPanel redPanel;
private JPanel greenPanel;
private JPanel bluePanel;
private JPanel yellowPanel;
private JPanel whitePanel;
private JPanel grayPanel;
private JPanel blackPanel;
private JPanel magentaPanel;
private JLabel doorsTypeOneLabel = new JLabel("Дверь 1 типа");
private JLabel doorsTypeTwoLabel = new JLabel("Дверь 2 типа");
private JLabel doorsTypeThreeLabel = new JLabel("Дверь 3 типа");
private JLabel simpleObjectLabel;
private JLabel modifiedObjectLabel;
private JPanel componentPanel;
// Конструктор
public BusConfigForm() {
// Устанавливаем границы Label
simpleObjectLabel.setBorder(BorderFactory.createLineBorder(Color.BLACK));
modifiedObjectLabel.setBorder(BorderFactory.createLineBorder(Color.BLACK));
doorsTypeOneLabel.setBorder(BorderFactory.createLineBorder(Color.BLACK));
doorsTypeTwoLabel.setBorder(BorderFactory.createLineBorder(Color.BLACK));
doorsTypeThreeLabel.setBorder(BorderFactory.createLineBorder(Color.BLACK));
bodyColorLabel.setBorder(BorderFactory.createLineBorder(Color.BLACK));
additionalColorLabel.setBorder(BorderFactory.createLineBorder(Color.BLACK));
doorsTypeLabel.setBorder(BorderFactory.createLineBorder(Color.BLACK));
// Добавляем компоненты DoorComponent на форму
componentPanel.setLayout(new GridLayout());
componentPanel.add(doorComponentTypeOne);
componentPanel.add(doorComponentTypeTwo);
componentPanel.add(doorComponentTypeThree);
doorComponentTypeOne.setLayout(new GridLayout(1, 1));
doorComponentTypeTwo.setLayout(new GridLayout(1, 1));
doorComponentTypeThree.setLayout(new GridLayout(1, 1));
doorComponentTypeOne.add(doorsTypeOneLabel);
doorComponentTypeTwo.add(doorsTypeTwoLabel);
doorComponentTypeThree.add(doorsTypeThreeLabel);
// Устанавливаем допустимые значения Spinner
speedSpinner.setModel(new SpinnerNumberModel(100, 100, 1000, 1));
weightSpinner.setModel(new SpinnerNumberModel(100, 100, 1000, 1));
doorsSpinner.setModel(new SpinnerNumberModel(3, 3, 5, 1));
// Устанавливаем возможность перетаскивания Panel (цвета объекта)
redPanel.setTransferHandler(new PanelTransferHandler());
greenPanel.setTransferHandler(new PanelTransferHandler());
bluePanel.setTransferHandler(new PanelTransferHandler());
yellowPanel.setTransferHandler(new PanelTransferHandler());
whitePanel.setTransferHandler(new PanelTransferHandler());
grayPanel.setTransferHandler(new PanelTransferHandler());
blackPanel.setTransferHandler(new PanelTransferHandler());
magentaPanel.setTransferHandler(new PanelTransferHandler());
redPanel.addMouseListener(new PanelMouseAdapter());
greenPanel.addMouseListener(new PanelMouseAdapter());
bluePanel.addMouseListener(new PanelMouseAdapter());
yellowPanel.addMouseListener(new PanelMouseAdapter());
whitePanel.addMouseListener(new PanelMouseAdapter());
grayPanel.addMouseListener(new PanelMouseAdapter());
blackPanel.addMouseListener(new PanelMouseAdapter());
magentaPanel.addMouseListener(new PanelMouseAdapter());
// Устанавливаем возможность перетаскивания Label (типа объекта)
simpleObjectLabel.setTransferHandler(new LabelTransferHandler());
modifiedObjectLabel.setTransferHandler(new LabelTransferHandler());
simpleObjectLabel.addMouseListener(new LabelMouseAdapter());
modifiedObjectLabel.addMouseListener(new LabelMouseAdapter());
// Действия при приеме получаемой информации (получение типа объекта)
pictureBoxPanel.setTransferHandler(new TransferHandler() {
@Override
public boolean canImport(TransferHandler.TransferSupport support) {
return support.isDataFlavorSupported(DataFlavor.stringFlavor);
}
@Override
public boolean importData(TransferHandler.TransferSupport support) {
if (!canImport(support)) {
return false;
}
try {
String data = (String)support.getTransferable().getTransferData(DataFlavor.stringFlavor);
switch (data) {
case "Простой":
_bus = new DrawingBus((int)speedSpinner.getValue(),
(int) weightSpinner.getValue(),
Color.WHITE,
900,
500);
_bus.drawingDoors.setNumDoors((int)doorsSpinner.getValue());
break;
case "Продвинутый":
_bus = new DrawingAccordionBus((int)speedSpinner.getValue(),
(int) weightSpinner.getValue(),
Color.WHITE,
Color.BLACK,
additionalBodyCheckBox.isSelected(),
additionalDoorCheckBox.isSelected(),
900,
500);
_bus.drawingDoors.setNumDoors((int)doorsSpinner.getValue());
break;
}
} catch (UnsupportedFlavorException | IOException e) {
e.printStackTrace();
}
DrawBus();
return true;
}
});
// Действия при приеме получаемой информации (получение основного цвета объекта)
bodyColorLabel.setTransferHandler(new LabelTransferHandler() {
@Override
public boolean canImport(TransferHandler.TransferSupport support) {
return support.isDataFlavorSupported(ColorTransferable.colorDataFlavor);
}
@Override
public boolean importData(TransferHandler.TransferSupport support) {
if (!canImport(support)) {
return false;
}
if (_bus instanceof DrawingBus) {
try {
Color color = (Color)support.getTransferable().getTransferData(ColorTransferable.colorDataFlavor);
bodyColorLabel.setBackground(color);
_bus.SetBodyColor(color);
}
catch (UnsupportedFlavorException | IOException e) {
e.printStackTrace();
}
}
DrawBus();
return true;
}
});
// Действия при приеме получаемой информации (получение дополнительного цвета объекта)
additionalColorLabel.setTransferHandler(new LabelTransferHandler() {
@Override
public boolean canImport(TransferHandler.TransferSupport support) {
return support.isDataFlavorSupported(ColorTransferable.colorDataFlavor);
}
@Override
public boolean importData(TransferHandler.TransferSupport support) {
if (!canImport(support)) {
return false;
}
if (_bus instanceof DrawingAccordionBus) {
try {
Color color = (Color)support.getTransferable().getTransferData(ColorTransferable.colorDataFlavor);
additionalColorLabel.setBackground(color);
((DrawingAccordionBus)_bus).SetAdditionalColor(color);
}
catch (UnsupportedFlavorException | IOException e) {
e.printStackTrace();
}
}
DrawBus();
return true;
}
});
// Действия при приеме получаемой информации (получение типа дверей)
doorsTypeLabel.setTransferHandler(new TransferHandler() {
@Override
public boolean canImport(TransferHandler.TransferSupport support) {
return support.isDataFlavorSupported(IDrawingDoorsTransferable.IDrawingDoorsDataFlavor);
}
@Override
public boolean importData(TransferHandler.TransferSupport support) {
if (!canImport(support)) {
return false;
}
try {
IDrawingDoors drawingDoors = (IDrawingDoors)support.getTransferable().getTransferData(IDrawingDoorsTransferable.IDrawingDoorsDataFlavor);
drawingDoors.setNumDoors((int)doorsSpinner.getValue());
_bus.drawingDoors = drawingDoors;
}
catch (UnsupportedFlavorException | IOException e) {
e.printStackTrace();
}
DrawBus();
return true;
}
});
}
// Отрисовать автобус
private void DrawBus () {
if (_bus == null) {
return;
}
Graphics g = pictureBoxPanel.getGraphics();
_bus.SetPosition((pictureBoxPanel.getWidth() - _bus.GetWidth()) / 2, (pictureBoxPanel.getHeight() - _bus.GetHeigth()) / 2);
pictureBoxPanel.paint(g);
_bus.DrawTransport(g);
}
}

View File

@ -0,0 +1,96 @@
package AccordionBus;
import java.awt.*;
// Параметризованный класс для набора объектов DrawingBus
public class BusGenericCollection<T extends DrawingBus, U extends IMoveableObject> {
// Ширина окна прорисовки
private final int _pictureWidth;
// Высота окна прорисовки
private final int _pictureHeight;
// Размер занимаемого объектом места (ширина)
private final int _placeSizeWidth = 215;
// Размер занимаемого объектом места (высота)
private final int _placeSizeHeight = 50;
// Набор объектов
private final SetGeneric<T> _collection;
// Конструктор
public BusGenericCollection(int picWidth, int picHeight) {
int width = picWidth / _placeSizeWidth;
int height = picHeight / _placeSizeHeight;
_pictureWidth = picWidth;
_pictureHeight = picHeight;
_collection = new SetGeneric<T>(width * height);
}
// Перегрузка оператора сложения
public int plus(T obj) {
if (obj == null) {
return -1;
}
return _collection.Insert(obj);
}
// Перегрузка оператора вычитания
public T minus(int pos) {
T obj = _collection.Get(pos);
if (obj != null) {
_collection.Remove(pos);
}
return obj;
}
// Получение объекта IMoveableObject
public U GetU(int pos)
{
return (U)_collection.Get(pos).GetMoveableObject();
}
// Вывод всего набора объектов
public void ShowBuses(Graphics g) {
DrawBackground(g);
DrawObjects(g);
}
// Метод отрисовки фона
private void DrawBackground(Graphics g) {
Graphics2D g2d = (Graphics2D)g;
g2d.setColor(Color.BLACK);
g2d.setStroke(new BasicStroke(3));
for (int i = 0; i < _pictureWidth / _placeSizeWidth; i++) {
for (int j = 0; j < _pictureHeight / _placeSizeHeight + 1; j++) {
// Линия разметки места
g2d.drawLine(i * _placeSizeWidth, j * _placeSizeHeight, i * _placeSizeWidth + _placeSizeWidth / 2, j * _placeSizeHeight);
}
g2d.drawLine(i * _placeSizeWidth, 0, i * _placeSizeWidth, _pictureHeight / _placeSizeHeight * _placeSizeHeight);
}
}
private void DrawObjects(Graphics g) {
int width = _pictureWidth / _placeSizeWidth;
int height = _pictureHeight / _placeSizeHeight;
int i = 0;
for (T bus : _collection.GetBuses(_collection.Count())) {
if (bus != null) {
// Установка позиции
bus.SetPosition(
(int)((width - 1) * _placeSizeWidth - (i % width * _placeSizeWidth)),
(int)((height - 1) * _placeSizeHeight - (i / width * _placeSizeHeight))
);
// Прорисовка объекта
bus.DrawTransport(g);
}
i++;
}
}
}

View File

@ -0,0 +1,31 @@
<?xml version="1.0" encoding="UTF-8"?>
<form xmlns="http://www.intellij.com/uidesigner/form/" version="1" bind-to-class="AccordionBus.BusGenericForm">
<grid id="27dc6" binding="pictureBox" layout-manager="GridLayoutManager" row-count="2" column-count="2" same-size-horizontally="false" same-size-vertically="false" hgap="-1" vgap="-1">
<margin top="0" left="0" bottom="0" right="0"/>
<constraints>
<xy x="20" y="20" width="500" height="400"/>
</constraints>
<properties/>
<border type="none"/>
<children>
<component id="b0cd2" class="javax.swing.JButton" binding="buttonGenerateBus">
<constraints>
<grid row="1" column="0" row-span="1" col-span="1" vsize-policy="0" hsize-policy="3" anchor="10" fill="0" indent="0" use-parent-layout="false"/>
</constraints>
<properties>
<text value="Сгенерировать автоубс"/>
</properties>
</component>
<hspacer id="19ae4">
<constraints>
<grid row="1" column="1" row-span="1" col-span="1" vsize-policy="1" hsize-policy="6" anchor="0" fill="1" indent="0" use-parent-layout="false"/>
</constraints>
</hspacer>
<vspacer id="68bda">
<constraints>
<grid row="0" column="0" row-span="1" col-span="1" vsize-policy="6" hsize-policy="1" anchor="0" fill="2" indent="0" use-parent-layout="false"/>
</constraints>
</vspacer>
</children>
</grid>
</form>

View File

@ -0,0 +1,86 @@
package AccordionBus;
import javax.swing.*;
import java.awt.*;
import java.util.Random;
public class BusGenericForm {
private DrawingBus drawingBus;
private SetBusGeneric<EntityBus, IDrawingDoors> _busGeneric;
private JPanel pictureBox;
public JPanel getPictureBox() {
return pictureBox;
}
private JButton buttonGenerateBus;
// Конструктор
public BusGenericForm() {
_busGeneric = new SetBusGeneric<>(15, 15);
buttonGenerateBus.addActionListener(e -> {
addEntityBus();
addDrawingDoors();
drawingBus = _busGeneric.NewBus(pictureBox.getWidth(), pictureBox.getHeight());
drawingBus.SetPosition((pictureBox.getWidth() - drawingBus.GetWidth()) / 2, (pictureBox.getHeight() - drawingBus.GetHeigth()) / 2);
Draw();
});
}
// Добавить объект-сущность в набор
private void addEntityBus() {
Random random = new Random();
EntityBus entityBus;
if (random.nextBoolean()) {
entityBus = new EntityBus(random.nextInt(100, 300),
random.nextInt(1000, 3000),
new Color(random.nextInt(256), random.nextInt(256), random.nextInt(256)));
}
else {
entityBus = new EntityAccordionBus(random.nextInt(100, 300),
random.nextInt(1000, 3000),
new Color(random.nextInt(256), random.nextInt(256), random.nextInt(256)),
new Color(random.nextInt(256), random.nextInt(256), random.nextInt(256)),
random.nextBoolean(),
random.nextBoolean());
}
_busGeneric.Insert(entityBus);
}
// Добавить тип отрисовки дверей в набор
public void addDrawingDoors() {
Random random = new Random();
IDrawingDoors drawingDoors;
switch (random.nextInt(0, 3)) {
case 0:
drawingDoors = new DrawingDoorsTypeOne();
break;
case 1:
drawingDoors = new DrawingDoorsTypeTwo();
break;
case 2:
drawingDoors = new DrawingDoorsTypeThree();
break;
default:
drawingDoors = new DrawingDoorsTypeOne();
break;
}
drawingDoors.setNumDoors(random.nextInt(3, 6));
_busGeneric.Insert(drawingDoors);
}
public void Draw() {
if (drawingBus == null) {
return;
}
Graphics g = pictureBox.getGraphics();
pictureBox.paint(g);
drawingBus.DrawTransport(g);
}
}

View File

@ -0,0 +1,62 @@
package AccordionBus;
import java.util.HashMap;
import java.util.List;
import java.util.stream.Collectors;
// Класс для хранения коллекции
public class BusGenericStorage {
// Словарь (хранилище)
final HashMap<String, BusGenericCollection<DrawingBus, DrawingObjectBus>> _busStorages;
// Возвращение списка названий наборов
public List<String> 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<String, BusGenericCollection<DrawingBus, DrawingObjectBus>>();
_pictureWidth = pictureWidth;
_pictureHeight = pictureHeight;
}
// Добавление набора
public void AddSet(String name) {
_busStorages.put(name, new BusGenericCollection<DrawingBus, DrawingObjectBus>(_pictureWidth, _pictureHeight));
}
// Удаление набора
public void DelSet(String name) {
// Проверка наличия ключа
if (!_busStorages.containsKey(name)) {
return;
}
_busStorages.remove(name);
}
// Доступ к набору
public BusGenericCollection<DrawingBus, DrawingObjectBus> 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;
}
}

View File

@ -0,0 +1,37 @@
package AccordionBus;
import java.awt.*;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.Transferable;
import java.awt.datatransfer.UnsupportedFlavorException;
import java.io.IOException;
// Класс для реализации поддержки передачи данных типа Color
public class ColorTransferable implements Transferable {
private Color color;
public 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, IOException {
if (isDataFlavorSupported(flavor)) {
return color;
}
else {
throw new UnsupportedFlavorException(flavor);
}
}
}

View File

@ -0,0 +1,13 @@
package AccordionBus;
// Направление перемещения
public enum DirectionType {
// Вверх
Up,
// Вниз
Down,
// Влево
Left,
// Вправо
Right,
}

View File

@ -0,0 +1,34 @@
package AccordionBus;
import javax.swing.*;
import java.awt.datatransfer.Transferable;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
// Класс для создания компонента DrawingDoors для формы
public class DoorComponent extends JComponent {
public IDrawingDoors DrawingDoors;
public DoorComponent(IDrawingDoors drawingDoors) {
DrawingDoors = drawingDoors;
this.addMouseListener(new MouseAdapter() {
@Override
public void mousePressed(MouseEvent e) {
((DoorComponent)e.getComponent()).getTransferHandler().exportAsDrag(((DoorComponent)e.getComponent()), e, TransferHandler.COPY);
}
});
this.setTransferHandler(new TransferHandler() {
@Override
public int getSourceActions(JComponent c) {
return TransferHandler.COPY;
}
@Override
protected Transferable createTransferable(JComponent c) {
return new IDrawingDoorsTransferable(((DoorComponent)c).DrawingDoors);
}
});
}
}

View File

@ -0,0 +1,102 @@
package AccordionBus;
import java.awt.*;
// Класс, отвечающий за прорисовку и перемещение объекта-сущности
public class DrawingAccordionBus extends DrawingBus {
// Конструктор
public DrawingAccordionBus(int speed, double weight, Color bodyColor, Color additionalColor, boolean additionalBody, boolean additionalDoor, int width, int height) {
super(speed, weight, bodyColor, width, height, 215, 50);
if (EntityBus != null) {
EntityBus = new EntityAccordionBus(speed, weight, bodyColor, additionalColor, additionalBody, additionalDoor);
}
}
// Конструктор
public DrawingAccordionBus(EntityBus bus, IDrawingDoors door, int width, int height) {
super(bus, door, width, height);
drawingDoors = door;
}
// Смена дополнительного цвета
public void SetAdditionalColor(Color additionalColor) {
if (EntityBus instanceof EntityAccordionBus) {
((EntityAccordionBus)EntityBus).SetAdditionalColor(additionalColor);
}
}
// Прорисовка объекта
public void DrawTransport(Graphics g) {
if (EntityBus == null) {
return;
}
Graphics2D g2d = (Graphics2D)g;
super.DrawTransport(g2d);
Color bodyColor = EntityBus.getBodyColor();
Color additionalColor = ((EntityAccordionBus)EntityBus).getAdditionalColor();
Color blackColor = Color.BLACK;
Color whiteColor = Color.WHITE;
// Дополнительный отсек
if (((EntityAccordionBus)EntityBus).isAdditionalBody()) {
// Граница дополнительного отсека
g2d.setColor(blackColor);
g2d.setStroke(new BasicStroke(3));
g2d.drawRect(_startPosX + 115, _startPosY, 100, 40);
// Кузов дополнительного отсека
g2d.setColor(bodyColor);
g2d.fillRect(_startPosX + 116, _startPosY + 1, 99, 39);
// Окна главного отсека
g2d.setColor(Color.CYAN);
g2d.fillRect(_startPosX + 115, _startPosY + 5, 100, 15);
g2d.setColor(blackColor);
g2d.setStroke(new BasicStroke(2));
g2d.drawLine(_startPosX + 115, _startPosY + 5, _startPosX + 215, _startPosY + 5);
g2d.drawLine(_startPosX + 115, _startPosY + 20, _startPosX + 215, _startPosY + 20);
// Дверь дополнительного отсека
if (((EntityAccordionBus)EntityBus).isAdditionalDoor()) {
g2d.setColor(blackColor);
g2d.setStroke(new BasicStroke(2));
g2d.drawRect(_startPosX + 175, _startPosY + 10, 15, 30);
g2d.setColor(whiteColor);
g2d.fillRect(_startPosX + 176, _startPosY + 11, 14, 29);
}
// Гармошка
g2d.setColor(blackColor);
g2d.setStroke(new BasicStroke(2));
for (int i = 0; i < 5; i++) {
g2d.drawLine(_startPosX + 100 + i * 3, _startPosY, _startPosX + 100 + i * 3, _startPosY + 40);
}
}
// Дополнительные двери
drawingDoors.DrawDoors(g2d, additionalColor, ((EntityAccordionBus) EntityBus).isAdditionalBody(), _startPosX, _startPosY);
// Колеса главного отсека
g2d.setColor(blackColor);
g2d.setStroke(new BasicStroke(3));
g2d.drawOval(_startPosX + 15, _startPosY + 33, 15, 15);
g2d.drawOval(_startPosX + 70, _startPosY + 33, 15, 15);
g2d.setColor(whiteColor);
g2d.fillOval(_startPosX + 15, _startPosY + 33, 15, 15);
g2d.fillOval(_startPosX + 70, _startPosY + 33, 15, 15);
// Колеса дополнительного отсека
if (((EntityAccordionBus)EntityBus).isAdditionalBody()) {
g2d.setColor(blackColor);
g2d.drawOval(_startPosX + 130, _startPosY + 33, 15, 15);
g2d.drawOval(_startPosX + 185, _startPosY + 33, 15, 15);
g2d.setColor(whiteColor);
g2d.fillOval(_startPosX + 131, _startPosY + 33, 15, 15);
g2d.fillOval(_startPosX + 186, _startPosY + 33, 15, 15);
}
}
}

View File

@ -0,0 +1,235 @@
package AccordionBus;
import java.awt.*;
import java.util.Random;
// Класс, отвечающий за прорисовку и перемещение объекта-сущности
public class DrawingBus {
// Класс-сущность
public EntityBus EntityBus;
// Прорисовка дверей
public IDrawingDoors drawingDoors;
// Ширина окна
private int _pictureWidth;
// Высота окна
private int _pictureHeight;
// Левая координата прорисовки автобуса
protected int _startPosX;
// Координата X объекта
public int GetPosX() { return _startPosX; }
// Верхняя координата прорисовки автобуса
protected int _startPosY;
// Координата Y объекта
public int GetPosY() { return _startPosY; }
// Ширина прорисовки автобуса
private int _busWidth = 100;
// Ширина объекта
public int GetWidth() { return _busWidth; }
// Высота прорисовки автобуса
private int _busHeight = 50;
// Высота объекта
public int GetHeigth() { return _busHeight; }
// Получение объекта IMoveableObject из объекта DrawingBus
public IMoveableObject GetMoveableObject() {
return new DrawingObjectBus(this);
}
// Проверка, что объект может перемещаться по указанному направлению
public boolean CanMove(DirectionType direction) {
if (EntityBus == null) {
return false;
}
switch (direction) {
// Влево
case Left:
return _startPosX - EntityBus.Step() > 0;
// Вверх
case Up:
return _startPosY - EntityBus.Step() > 0;
// Вправо
case Right:
return _startPosX + EntityBus.Step() < _pictureWidth - _busWidth;
// Вниз
case Down:
return _startPosY + EntityBus.Step() < _pictureHeight - _busHeight;
default:
return false;
}
}
// Смена основного цвета
public void SetBodyColor(Color bodyColor) {
EntityBus.SetBodyColor(bodyColor);
}
// Конструктор
public DrawingBus(int speed, int weight, Color bodyColor, int width, int height) {
// Проверка на вместимость объекта в размеры картинки
if ((_busWidth >= width) || (_busHeight >= height)) {
return;
}
_pictureWidth = width;
_pictureHeight = height;
EntityBus = new EntityBus(speed, weight, bodyColor);
Random random = new Random();
switch (random.nextInt(0, 3)) {
case 0:
drawingDoors = new DrawingDoorsTypeOne();
break;
case 1:
drawingDoors = new DrawingDoorsTypeTwo();
break;
case 2:
drawingDoors = new DrawingDoorsTypeThree();
break;
default:
drawingDoors = new DrawingDoorsTypeOne();
break;
}
}
// Конструктор
protected DrawingBus(int speed, double weight, Color bodyColor, int width, int height, int busWidth, int busHeight) {
// Проверка на вместимость объекта в размеры картинки
if ((_busWidth >= width) || (_busHeight >= height)) {
return;
}
_pictureWidth = width;
_pictureHeight = height;
_busWidth = busWidth;
_busHeight = busHeight;
EntityBus = new EntityBus(speed, weight, bodyColor);
Random random = new Random();
switch (random.nextInt(0, 3)) {
case 0:
drawingDoors = new DrawingDoorsTypeOne();
break;
case 1:
drawingDoors = new DrawingDoorsTypeTwo();
break;
case 2:
drawingDoors = new DrawingDoorsTypeThree();
break;
default:
drawingDoors = new DrawingDoorsTypeOne();
break;
}
}
// Конструктор
public DrawingBus(EntityBus bus, IDrawingDoors door, int width, int height) {
EntityBus = bus;
drawingDoors = door;
_pictureWidth = width;
_pictureHeight = height;
}
// Установка позиции
public void SetPosition(int x, int y) {
if (x < 0 || y < 0) {
x = 0;
y = 0;
}
else if ((x + _busWidth > _pictureWidth) || (y + _busHeight > _pictureHeight)) {
_startPosX = _pictureWidth - _busWidth;
_startPosY = _pictureHeight - _busHeight;
}
else {
_startPosX = x;
_startPosY = y;
}
}
// Изменение направления перемещения
public void MoveTransport(DirectionType direction) {
if (!CanMove(direction) || EntityBus == null) {
return;
}
switch (direction) {
// Влево
case Left:
_startPosX -= (int)EntityBus.Step();
break;
// Вверх
case Up:
_startPosY -= (int)EntityBus.Step();
break;
// Вправо
case Right:
_startPosX += (int)EntityBus.Step();
break;
// Вниз
case Down:
_startPosY += (int)EntityBus.Step();
break;
}
}
// Прорисовка объекта
public void DrawTransport(Graphics g) {
if (EntityBus == null)
{
return;
}
Graphics2D g2d = (Graphics2D)g;
Color bodyColor = EntityBus.getBodyColor();
Color blackColor = Color.BLACK;
Color whiteColor = Color.WHITE;
// Граница главного отсека
g2d.setColor(blackColor);
g2d.setStroke(new BasicStroke(3));
g2d.drawRect(_startPosX, _startPosY, 100, 40);
// Кузов главного отсека
g2d.setColor(bodyColor);
g2d.fillRect(_startPosX + 1, _startPosY + 1, 99, 39);
// Окна главного отсека
g2d.setColor(Color.CYAN);
g2d.fillRect(_startPosX, _startPosY + 5, 100, 15);
g2d.setColor(blackColor);
g2d.setStroke(new BasicStroke(2));
g2d.drawLine(_startPosX, _startPosY + 5, _startPosX + 100, _startPosY + 5);
g2d.drawLine(_startPosX, _startPosY + 20, _startPosX + 100, _startPosY + 20);
// Дверь главного отсека
g2d.setColor(blackColor);
g2d.setStroke(new BasicStroke(2));
g2d.drawRect(_startPosX + 10, _startPosY + 10, 15, 30);
g2d.setColor(whiteColor);
g2d.fillRect(_startPosX + 11, _startPosY + 11, 14, 29);
// Дополнительные двери
drawingDoors.DrawDoors(g2d, bodyColor, false, _startPosX, _startPosY);
// Колеса главного отсека
g2d.setColor(blackColor);
g2d.setStroke(new BasicStroke(3));
g2d.drawOval(_startPosX + 15, _startPosY + 33, 15, 15);
g2d.drawOval(_startPosX + 70, _startPosY + 33, 15, 15);
g2d.setColor(whiteColor);
g2d.fillOval(_startPosX + 15, _startPosY + 33, 15, 15);
g2d.fillOval(_startPosX + 70, _startPosY + 33, 15, 15);
}
}

View File

@ -0,0 +1,43 @@
package AccordionBus;
import java.awt.*;
// Класс, отвечающий за прорисовку дополнительных дверей
public class DrawingDoors {
private NumDoors numDoors;
public void setNumDoors(int num) {
for (NumDoors temp : numDoors.values()) {
if (temp.getNumDoors() == num) {
numDoors = temp;
return;
}
}
}
public void DrawDoors(Graphics2D g2d, EntityAccordionBus AccordionBus, Color additionalColor, int _startPosX, int _startPosY) {
g2d.setColor(additionalColor);
int value = numDoors.getNumDoors();
if (value >= 3) {
g2d.setColor(Color.BLACK);
g2d.setStroke(new BasicStroke(2));
g2d.drawRect(_startPosX + 40, _startPosY + 10, 15, 30);
g2d.setColor(Color.WHITE);
g2d.fillRect(_startPosX + 41, _startPosY + 11, 14, 29);
}
if (value >= 4) {
g2d.setColor(Color.BLACK);
g2d.setStroke(new BasicStroke(2));
g2d.drawRect(_startPosX + 75, _startPosY + 10, 15, 30);
g2d.setColor(Color.WHITE);
g2d.fillRect(_startPosX + 76, _startPosY + 11, 14, 29);
}
if (value >= 5 && AccordionBus.isAdditionalBody()) {
g2d.setColor(Color.BLACK);
g2d.setStroke(new BasicStroke(2));
g2d.drawRect(_startPosX + 145, _startPosY + 10, 15, 30);
g2d.setColor(Color.WHITE);
g2d.fillRect(_startPosX + 146, _startPosY + 11, 14, 29);
}
}
}

View File

@ -0,0 +1,42 @@
package AccordionBus;
import java.awt.*;
// Класс, отвечающий за первый тип орнамента отрисовки дополнительных дверей
public class DrawingDoorsTypeOne implements IDrawingDoors {
private NumDoors numDoors;
public void setNumDoors(int num) {
for (NumDoors temp : numDoors.values()) {
if (temp.getNumDoors() == num) {
numDoors = temp;
return;
}
}
}
public void DrawDoors(Graphics2D g2d, Color color, boolean isAdditionalBody, int _startPosX, int _startPosY) {
int value = numDoors.getNumDoors();
if (value >= 3) {
g2d.setColor(Color.BLACK);
g2d.setStroke(new BasicStroke(2));
g2d.drawRect(_startPosX + 40, _startPosY + 10, 15, 30);
g2d.setColor(color);
g2d.fillRect(_startPosX + 41, _startPosY + 11, 14, 29);
}
if (value >= 4) {
g2d.setColor(Color.BLACK);
g2d.setStroke(new BasicStroke(2));
g2d.drawRect(_startPosX + 75, _startPosY + 10, 15, 30);
g2d.setColor(color);
g2d.fillRect(_startPosX + 76, _startPosY + 11, 14, 29);
}
if (value >= 5 && isAdditionalBody) {
g2d.setColor(Color.BLACK);
g2d.setStroke(new BasicStroke(2));
g2d.drawRect(_startPosX + 145, _startPosY + 10, 15, 30);
g2d.setColor(color);
g2d.fillRect(_startPosX + 146, _startPosY + 11, 14, 29);
}
}
}

View File

@ -0,0 +1,51 @@
package AccordionBus;
import java.awt.*;
// Класс, отвечающий за третий тип орнамента отрисовки дополнительных дверей
public class DrawingDoorsTypeThree implements IDrawingDoors {
private NumDoors numDoors;
public void setNumDoors(int num) {
for (NumDoors temp : numDoors.values()) {
if (temp.getNumDoors() == num) {
numDoors = temp;
return;
}
}
}
public void DrawDoors(Graphics2D g2d, Color color, boolean isAdditionalBody, int _startPosX, int _startPosY) {
int value = numDoors.getNumDoors();
if (value >= 3) {
g2d.setStroke(new BasicStroke(2));
Polygon firstDoor = new Polygon(new int[] { _startPosX + 45, _startPosX + 50, _startPosX + 55, _startPosX + 50, _startPosX + 55, _startPosX + 50, _startPosX + 55, _startPosX + 50, _startPosX + 45, _startPosX + 40, _startPosX + 45, _startPosX + 40, _startPosX + 45,_startPosX + 40 },
new int[] { _startPosY + 10, _startPosY + 10, _startPosY + 15, _startPosY + 20, _startPosY + 25, _startPosY + 30, _startPosY + 35, _startPosY + 40, _startPosY + 40, _startPosY + 35, _startPosY + 30, _startPosY + 25, _startPosY + 20, _startPosY + 15 },
14);
g2d.setColor(color);
g2d.fillPolygon(firstDoor);
g2d.setColor(Color.BLACK);
g2d.drawPolygon(firstDoor);
}
if (value >= 4) {
g2d.setStroke(new BasicStroke(2));
Polygon secondDoor = new Polygon(new int[] { _startPosX + 80, _startPosX + 85, _startPosX + 90, _startPosX + 85, _startPosX + 90, _startPosX + 85, _startPosX + 90, _startPosX + 85, _startPosX + 80, _startPosX + 75, _startPosX + 80, _startPosX + 75, _startPosX + 80, _startPosX + 75 },
new int[] { _startPosY + 10, _startPosY + 10, _startPosY + 15, _startPosY + 20, _startPosY + 25, _startPosY + 30, _startPosY + 35, _startPosY + 40, _startPosY + 40, _startPosY + 35, _startPosY + 30, _startPosY + 25, _startPosY + 20, _startPosY + 15 },
14);
g2d.setColor(color);
g2d.fillPolygon(secondDoor);
g2d.setColor(Color.BLACK);
g2d.drawPolygon(secondDoor);
}
if (value >= 5 && isAdditionalBody) {
g2d.setStroke(new BasicStroke(2));
Polygon thirdDoor = new Polygon(new int[] { _startPosX + 150, _startPosX + 155, _startPosX + 160, _startPosX + 155, _startPosX + 160, _startPosX + 155, _startPosX + 160, _startPosX + 155, _startPosX + 150, _startPosX + 145, _startPosX + 150, _startPosX + 145, _startPosX + 150, _startPosX + 145 },
new int[] { _startPosY + 10, _startPosY + 10, _startPosY + 15, _startPosY + 20, _startPosY + 25, _startPosY + 30, _startPosY + 35, _startPosY + 40, _startPosY + 40, _startPosY + 35, _startPosY + 30, _startPosY + 25, _startPosY + 20, _startPosY + 15 },
14);
g2d.setColor(color);
g2d.fillPolygon(thirdDoor);
g2d.setColor(Color.BLACK);
g2d.drawPolygon(thirdDoor);
}
}
}

View File

@ -0,0 +1,53 @@
package AccordionBus;
import java.awt.*;
// Класс, отвечающий за второй тип орнамента отрисовки дополнительных дверей
public class DrawingDoorsTypeTwo implements IDrawingDoors {
private NumDoors numDoors;
public void setNumDoors(int num) {
for (NumDoors temp : numDoors.values()) {
if (temp.getNumDoors() == num) {
numDoors = temp;
return;
}
}
}
public void DrawDoors(Graphics2D g2d, Color color, boolean isAdditionalBody, int _startPosX, int _startPosY) {
int value = numDoors.getNumDoors();
if (value >= 3) {
g2d.setStroke(new BasicStroke(2));
Polygon firstDoor = new Polygon(new int[] { _startPosX + 45, _startPosX + 50, _startPosX + 55, _startPosX + 55, _startPosX + 50, _startPosX + 45, _startPosX + 40, _startPosX + 40 },
new int[] { _startPosY + 10, _startPosY + 10, _startPosY + 20, _startPosY + 30, _startPosY + 40, _startPosY + 40, _startPosY + 30, _startPosY + 20 },
8);
g2d.setColor(color);
g2d.fillPolygon(firstDoor);
g2d.setColor(Color.BLACK);
g2d.drawPolygon(firstDoor);
}
if (value >= 4) {
g2d.setColor(Color.BLACK);
g2d.setStroke(new BasicStroke(2));
Polygon secondDoor = new Polygon(new int[] { _startPosX + 80, _startPosX + 85, _startPosX + 90, _startPosX + 90, _startPosX + 85, _startPosX + 80, _startPosX + 75, _startPosX + 75 },
new int[] { _startPosY + 10, _startPosY + 10, _startPosY + 20, _startPosY + 30, _startPosY + 40, _startPosY + 40, _startPosY + 30, _startPosY + 20 },
8);
g2d.setColor(color);
g2d.fillPolygon(secondDoor);
g2d.setColor(Color.BLACK);
g2d.drawPolygon(secondDoor);
}
if (value >= 5 && isAdditionalBody) {
g2d.setColor(Color.BLACK);
g2d.setStroke(new BasicStroke(2));
Polygon thirdDoor = new Polygon(new int[] { _startPosX + 150, _startPosX + 155, _startPosX + 160, _startPosX + 160, _startPosX + 155, _startPosX + 150, _startPosX + 145, _startPosX + 145 },
new int[] { _startPosY + 10, _startPosY + 10, _startPosY + 20, _startPosY + 30, _startPosY + 40, _startPosY + 40, _startPosY + 30, _startPosY + 20 },
8);
g2d.setColor(color);
g2d.fillPolygon(thirdDoor);
g2d.setColor(Color.BLACK);
g2d.drawPolygon(thirdDoor);
}
}
}

View File

@ -0,0 +1,23 @@
package AccordionBus;
// Реализация интерфейса IMoveableObject для работы с объектом DrawingBus (паттерн Adapter)
public class DrawingObjectBus implements IMoveableObject {
private DrawingBus _drawingBus = null;
public DrawingObjectBus(DrawingBus drawingBus) {
_drawingBus = drawingBus;
}
public ObjectParameters GetObjectPosition() {
if (_drawingBus == null || _drawingBus.EntityBus == null) {
return null;
}
return new ObjectParameters(_drawingBus.GetPosX(), _drawingBus.GetPosY(), _drawingBus.GetWidth(), _drawingBus.GetHeigth());
}
public int GetStep() { return (int)(_drawingBus.EntityBus.Step()); }
public boolean CheckCanMove(DirectionType direction) { return _drawingBus.CanMove(direction); }
public void MoveObject(DirectionType direction) { _drawingBus.MoveTransport(direction); }
}

View File

@ -0,0 +1,37 @@
package AccordionBus;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
// Класс-сущность "Автобус-гармошка"
public class EntityAccordionBus extends EntityBus {
// Дополнительный цвет
private Color AdditionalColor;;
public Color getAdditionalColor() {
return AdditionalColor;
}
public void SetAdditionalColor(Color additionalColor) {
AdditionalColor = additionalColor;
}
// Дополнительный отсек
private boolean AdditionalBody;
public boolean isAdditionalBody() {
return AdditionalBody;
}
// Дополнительная дверь
private boolean AdditionalDoor;
public boolean isAdditionalDoor() {
return AdditionalDoor;
}
// Конструктор с параметрами
public EntityAccordionBus(int speed, double weight, Color bodyColor, Color additionalColor, boolean additionalBody, boolean additionalDoor) {
super(speed, weight, bodyColor);
AdditionalColor = additionalColor;
AdditionalBody = additionalBody;
AdditionalDoor = additionalDoor;
}
}

View File

@ -0,0 +1,37 @@
package AccordionBus;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
// Класс-сущность "Автобус"
public class EntityBus {
// Скорость
public int Speed;
public int getSpeed() { return Speed; }
// Вес
public double Weight;
public double getWeight() {
return Weight;
}
// Основной цвет
public Color BodyColor;
public Color getBodyColor() {
return BodyColor;
}
public void SetBodyColor(Color bodyColor) {
BodyColor = bodyColor;
}
// Шаг перемещения автобуса
public double Step() { return (double)Speed * 100 / Weight; }
// Конструктор с параметрами
public EntityBus(int speed, double weight, Color bodyColor) {
Speed = speed;
Weight = weight;
BodyColor = bodyColor;
}
}

View File

@ -0,0 +1,21 @@
package AccordionBus;
import javax.swing.*;
import java.awt.*;
public class FrameAccordionBus extends JFrame {
public AccordionBusForm accordionBusForm;
public FrameAccordionBus() {
super();
setTitle("AccordionBus");
setDefaultCloseOperation(EXIT_ON_CLOSE);
accordionBusForm = new AccordionBusForm();
setContentPane(accordionBusForm.getPictureBox());
setDefaultLookAndFeelDecorated(false);
setPreferredSize(new Dimension(900, 500));
setLocation(500, 500);
pack();
setVisible(true);
}
}

View File

@ -0,0 +1,21 @@
package AccordionBus;
import javax.swing.*;
import java.awt.*;
public class FrameBusCollection extends JFrame {
public BusCollectionForm busCollectionForm;
public FrameBusCollection() {
super();
setTitle("Набор автобусов");
setDefaultCloseOperation(EXIT_ON_CLOSE);
busCollectionForm = new BusCollectionForm();
setContentPane(busCollectionForm.getMainPanel());
setDefaultLookAndFeelDecorated(false);
setPreferredSize(new Dimension(900, 500));
setLocation(500, 500);
pack();
setVisible(true);
}
}

View File

@ -0,0 +1,21 @@
package AccordionBus;
import javax.swing.*;
import java.awt.*;
public class FrameBusConfig extends JFrame {
public BusConfigForm busConfigForm;
public FrameBusConfig() {
super();
setTitle("BusConfig");
setDefaultCloseOperation(EXIT_ON_CLOSE);
busConfigForm = new BusConfigForm();
setContentPane(busConfigForm.getConfigPanel());
setDefaultLookAndFeelDecorated(false);
setPreferredSize(new Dimension(900, 300));
setLocation(500, 500);
pack();
setVisible(true);
}
}

View File

@ -0,0 +1,21 @@
package AccordionBus;
import javax.swing.*;
import java.awt.*;
public class FrameBusGeneric extends JFrame {
public BusGenericForm busGenericForm;
public FrameBusGeneric() {
super();
setTitle("Генерация автобуса");
setDefaultCloseOperation(EXIT_ON_CLOSE);
busGenericForm = new BusGenericForm();
setContentPane(busGenericForm.getPictureBox());
setDefaultLookAndFeelDecorated(false);
setPreferredSize(new Dimension(900, 500));
setLocation(500, 500);
pack();
setVisible(true);
}
}

View File

@ -0,0 +1,10 @@
package AccordionBus;
import java.awt.*;
// Интерфейс для отрисовки дополнительных дверей
public interface IDrawingDoors {
public void setNumDoors(int num);
public void DrawDoors(Graphics2D g2d, Color additionalColor, boolean isAdditionalBody, int _startPosX, int _startPosY);
}

View File

@ -0,0 +1,36 @@
package AccordionBus;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.Transferable;
import java.awt.datatransfer.UnsupportedFlavorException;
import java.io.IOException;
// Класс для реализации поддержки передачи данных типа IDrawingDoors
public class IDrawingDoorsTransferable implements Transferable {
private IDrawingDoors IDrawingDoorsObject;
public static final DataFlavor IDrawingDoorsDataFlavor = new DataFlavor(IDrawingDoors.class, "IDrawingDoors");
public IDrawingDoorsTransferable(IDrawingDoors IDrawingDoorsObject) {
this.IDrawingDoorsObject = IDrawingDoorsObject;
}
@Override
public DataFlavor[] getTransferDataFlavors() {
return new DataFlavor[] {IDrawingDoorsDataFlavor};
}
@Override
public boolean isDataFlavorSupported(DataFlavor flavor) {
return IDrawingDoorsDataFlavor.equals(flavor);
}
@Override
public Object getTransferData(DataFlavor flavor) throws UnsupportedFlavorException, IOException {
if (isDataFlavorSupported(flavor)) {
return IDrawingDoorsObject;
}
else {
throw new UnsupportedFlavorException(flavor);
}
}
}

View File

@ -0,0 +1,16 @@
package AccordionBus;
// Интерфейс для работы с перемещаемым объектом
public interface IMoveableObject {
// Получение координаты X объекта
ObjectParameters GetObjectPosition();
// Шаг объекта
int GetStep();
// Проверка, можно ли переместиться по нужному направлению
boolean CheckCanMove(DirectionType direction);
// Изменение направления перемещения объекта
void MoveObject(DirectionType direction);
}

View File

@ -0,0 +1,13 @@
package AccordionBus;
import javax.swing.*;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
// Передаем информацию при нажатии на Label
public class LabelMouseAdapter extends MouseAdapter {
@Override
public void mousePressed(MouseEvent e) {
((JLabel)e.getComponent()).getTransferHandler().exportAsDrag(((JLabel)e.getComponent()), e, TransferHandler.COPY);
}
}

View File

@ -0,0 +1,18 @@
package AccordionBus;
import javax.swing.*;
import java.awt.datatransfer.StringSelection;
import java.awt.datatransfer.Transferable;
// Класс для реализации поддержки передачи данных в Label
public class LabelTransferHandler extends TransferHandler {
@Override
public int getSourceActions(JComponent c) {
return TransferHandler.COPY;
}
@Override
public Transferable createTransferable(JComponent c) {
return new StringSelection(((JLabel)c).getText());
}
}

View File

@ -2,6 +2,6 @@ package AccordionBus;
public class Main {
public static void main(String[] args) {
new FrameBusCollection();
}
}

View File

@ -0,0 +1,21 @@
package AccordionBus;
import javax.swing.*;
import java.awt.*;
public class MainFrameAccordionBus extends JFrame {
private AccordionBusForm accordionBusForm;
public MainFrameAccordionBus() {
super();
setTitle("AccordionBus");
setDefaultCloseOperation(EXIT_ON_CLOSE);
accordionBusForm = new AccordionBusForm();
setContentPane(accordionBusForm.getPictureBox());
setDefaultLookAndFeelDecorated(false);
setPreferredSize(new Dimension(900, 500));
setLocation(500, 500);
pack();
setVisible(true);
}
}

View File

@ -0,0 +1,33 @@
package AccordionBus;
// Стратегия перемещения объекта в правый нижний угол экрана
public class MoveToBorder extends AbstractStrategy {
protected boolean IsTargetDestination() {
var objParams = GetObjectParameters();
if (objParams == null) {
return false;
}
return objParams.RightBorder() <= FieldWidth &&
objParams.RightBorder() + GetStep() >= FieldWidth &&
objParams.DownBorder() <= FieldHeight &&
objParams.DownBorder() + GetStep() >= FieldHeight;
}
protected void MoveToTarget() {
var objParams = GetObjectParameters();
if (objParams == null) {
return;
}
var diffX = objParams.RightBorder() - FieldWidth;
if (Math.abs(diffX) > GetStep()) {
MoveRight();
}
var diffY = objParams.ObjectMiddleVertical() - FieldWidth;
if (Math.abs(diffY) > GetStep()) {
MoveDown();
}
}
}

View File

@ -0,0 +1,43 @@
package AccordionBus;
// Стратегия перемещения объекта в центр экрана
public class MoveToCenter extends AbstractStrategy {
protected boolean IsTargetDestination() {
var objParams = GetObjectParameters();
if (objParams == null) {
return false;
}
return objParams.ObjectMiddleHorizontal() <= FieldWidth / 2 &&
objParams.ObjectMiddleHorizontal() + GetStep() >= FieldWidth / 2 &&
objParams.ObjectMiddleVertical() <= FieldHeight / 2 &&
objParams.ObjectMiddleVertical() + GetStep() >= FieldHeight / 2;
}
protected void MoveToTarget() {
var objParams = GetObjectParameters();
if (objParams == null) {
return;
}
var diffX = objParams.ObjectMiddleHorizontal() - FieldWidth / 2;
if (Math.abs(diffX) > GetStep()) {
if (diffX > 0) {
MoveLeft();
}
else {
MoveRight();
}
}
var diffY = objParams.ObjectMiddleVertical() - FieldHeight / 2;
if (Math.abs(diffY) > GetStep()) {
if (diffY > 0) {
MoveUp();
}
else {
MoveDown();
}
}
}
}

View File

@ -0,0 +1,22 @@
package AccordionBus;
// Количество дополнительных дверей
public enum NumDoors {
// 3 двери
Three(3),
// 4 двери
Four(4),
// 5 дверей
Five(5);
// Количество дверей
private final int Value;
public int getNumDoors() { return Value; }
// Конструктор
NumDoors(int value) {
Value = value;
}
}

View File

@ -0,0 +1,35 @@
package AccordionBus;
// Параметры-координаты рбъекта
public class ObjectParameters {
private int _x;
private int _y;
private int _width;
private int _height;
// Левая граница
public int LeftBorder() { return _x; }
// Верхняя граница
public int TopBorder() { return _y; }
// Правая граница
public int RightBorder() { return _x + _width; }
// Нижняя граница
public int DownBorder() { return _y + _height; }
// Середина объекта
public int ObjectMiddleHorizontal() { return _x + _width / 2; }
// Середина объекта
public int ObjectMiddleVertical() { return _y + _height / 2; }
// Конструктор
public ObjectParameters(int x, int y, int width, int height) {
_x = x;
_y = y;
_width = width;
_height = height;
}
}

View File

@ -0,0 +1,13 @@
package AccordionBus;
import javax.swing.*;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
// Передаем информацию при нажатии на Panel
public class PanelMouseAdapter extends MouseAdapter {
@Override
public void mousePressed(MouseEvent e) {
((JPanel)e.getComponent()).getTransferHandler().exportAsDrag(((JPanel)e.getComponent()), e, TransferHandler.COPY);
}
}

View File

@ -0,0 +1,17 @@
package AccordionBus;
import javax.swing.*;
import java.awt.datatransfer.Transferable;
// Класс для реализации поддержки передачи данных в Panel
public class PanelTransferHandler extends TransferHandler {
@Override
public int getSourceActions(JComponent c) {
return TransferHandler.COPY;
}
@Override
protected Transferable createTransferable(JComponent c) {
return new ColorTransferable(((JPanel)c).getBackground());
}
}

View File

@ -0,0 +1,54 @@
package AccordionBus;
import java.util.Random;
// Дополнительный параметризованный набор объектов
public class SetBusGeneric<T extends EntityBus, U extends IDrawingDoors> {
// Набор объектов от первого параметра
private final T[] _buses;
public int BusesCount;
// Набор объектов от второго параметра
private final U[] _doors;
public int DoorsCount;
// Конструктор
public SetBusGeneric(int busesCount, int doorsCount) {
_buses = (T[]) new EntityBus[busesCount];
_doors = (U[]) new IDrawingDoors[doorsCount];
}
// Добавление объекта в первый набор
public int Insert(T bus) {
// Проверка на вместимость
if (BusesCount >= _buses.length) {
return -1;
}
_buses[BusesCount++] = bus;
return BusesCount;
}
// Добавление объекта во второй набор
public int Insert(U door) {
// Проверка на вместимость
if (DoorsCount >= _doors.length) {
return -1;
}
_doors[DoorsCount++] = door;
return DoorsCount;
}
// Создание объекта класса прорисовки
public DrawingBus NewBus(int pictureWidth, int pictureHeight) {
Random random = new Random();
T bus = _buses[random.nextInt(BusesCount)];
U door = _doors[random.nextInt(DoorsCount)];
if (bus instanceof EntityAccordionBus) {
return new DrawingAccordionBus(bus, door, pictureWidth, pictureHeight);
}
return new DrawingBus(bus, door, pictureWidth, pictureHeight);
}
}

View File

@ -0,0 +1,91 @@
package AccordionBus;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.NoSuchElementException;
// Параметризованный набор рбъектов
public class SetGeneric<T extends Object> {
// Список объектов, которые храним
private final ArrayList<T> _places;
// Количество объектов в списке
public int Count() {
return _places.size();
}
// Максимальное количество объектов в списке
private final int _maxCount;
// Конструктор
public SetGeneric(int count) {
_maxCount = count;
_places = new ArrayList<T>(count);
}
// Добавление объекта в набор
public int Insert(T bus) {
return Insert(bus, 0);
}
// Добавление объекта в набор на конкретную позицию
public int Insert(T bus, int position) {
// Проверка позиции
if (position < 0 || position >= _maxCount) {
return -1;
}
// Вставка по позиции
_places.add(position, bus);
return position;
}
// Удаление объекта из набора с конкретной позиции
public boolean Remove(int position) {
// Проверка позиции
if (position < 0 || position >= _maxCount) {
return false;
}
// Удаление объекта из списка
_places.remove(position);
return true;
}
// Получение объекта из набора по позиции
public T Get(int position) {
// Проверка позиции
if (position < 0 || position >= _maxCount) {
return null;
}
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();
}
};
}
};
}
}

10
AccordionBus/Status.java Normal file
View File

@ -0,0 +1,10 @@
package AccordionBus;
// Статус выполнения операции перемещения
public enum Status {
NotInit,
InProgress,
Finish
}

BIN
AccordionBus/img/Down.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.1 KiB

BIN
AccordionBus/img/Left.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.0 KiB

BIN
AccordionBus/img/Right.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.2 KiB

BIN
AccordionBus/img/Up.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.1 KiB