Compare commits

...

15 Commits
main ... lab5

Author SHA1 Message Date
37d8468889 готово!!! 2023-12-12 13:07:31 +04:00
c007f3e1e1 создана форма 2023-12-11 21:14:51 +04:00
646ecece61 создана форма 2023-12-11 21:14:14 +04:00
791d5205b3 методы добавления из 3ей лабы исправлены на полиморфные 2023-12-03 10:15:33 +04:00
bcc4a0d32f готово!!! 2023-11-28 12:02:52 +04:00
facad042be работа с формой.... 2023-11-27 23:23:06 +04:00
aad104ad8e it's all 2023-11-27 10:20:47 +04:00
492fee19fe in progress 2023-11-26 19:10:56 +04:00
bcf703d795 reducing repetitive code 2023-11-23 15:26:05 +04:00
29e3f74627 lab2 2023-11-18 14:41:33 +04:00
28963e2235 lab2 2023-11-18 14:40:19 +04:00
2ab74c38dc lab2 2023-11-18 14:35:17 +04:00
5980b6eb32 clean2 2023-11-18 13:02:21 +04:00
2c02421db6 done 2023-11-18 12:55:54 +04:00
ec2c529fa5 lab 1 2023-11-18 12:42:03 +04:00
31 changed files with 2231 additions and 0 deletions

106
.gitignore vendored
View File

@ -12,3 +12,109 @@
# Built Visual Studio Code Extensions
*.vsix
# ---> Java
*.class
*.idea
# Log file
*.log
# BlueJ files
*.ctxt
# Mobile Tools for Java (J2ME)
.mtj.tmp/
# Package Files #
*.jar
*.war
*.nar
*.ear
*.zip
*.tar.gz
*.rar
# virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml
hs_err_pid*
replay_pid*
# ---> JetBrains
# Covers JetBrains IDEs: IntelliJ, RubyMine, PhpStorm, AppCode, PyCharm, CLion, Android Studio, WebStorm and Rider
# Reference: https://intellij-support.jetbrains.com/hc/en-us/articles/206544839
# User-specific stuff
.idea/**/workspace.xml
.idea/**/tasks.xml
.idea/**/usage.statistics.xml
.idea/**/dictionaries
.idea/**/shelf
# AWS User-specific
.idea/**/aws.xml
# Generated files
.idea/**/contentModel.xml
# Sensitive or high-churn files
.idea/**/dataSources/
.idea/**/dataSources.ids
.idea/**/dataSources.local.xml
.idea/**/sqlDataSources.xml
.idea/**/dynamic.xml
.idea/**/uiDesigner.xml
.idea/**/dbnavigator.xml
# Gradle
.idea/**/gradle.xml
.idea/**/libraries
# Gradle and Maven with auto-import
# When using Gradle or Maven with auto-import, you should exclude module files,
# since they will be recreated, and may cause churn. Uncomment if using
# auto-import.
# .idea/artifacts
# .idea/compiler.xml
# .idea/jarRepositories.xml
# .idea/modules.xml
# .idea/*.iml
# .idea/modules
# *.iml
# *.ipr
# CMake
cmake-build-*/
# Mongo Explorer plugin
.idea/**/mongoSettings.xml
# File-based project format
*.iws
# IntelliJ
out/
# mpeltonen/sbt-idea plugin
.idea_modules/
# JIRA plugin
atlassian-ide-plugin.xml
# Cursive Clojure plugin
.idea/replstate.xml
# SonarLint plugin
.idea/sonarlint/
# Crashlytics plugin (for Android Studio and IntelliJ)
com_crashlytics_export_strings.xml
crashlytics.properties
crashlytics-build.properties
fabric.properties
# Editor-based Rest Client
.idea/httpRequests
# Android studio 3.1+ serialized cache file
.idea/caches/build_file_checksums.ser
/PIbd-22_Isaeva_A.I._Airbus_Hard.iml

BIN
images/KeyDown.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.4 KiB

BIN
images/KeyLeft.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.4 KiB

BIN
images/KeyRight.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.2 KiB

BIN
images/KeyUp.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.2 KiB

View File

@ -0,0 +1,150 @@
package Drawnings;
import java.awt.*;
import Entities.*;
import MovementStrategy.*;
public class DrawningAirbus {
public EntityAirbus entityAirbus;
public IDrawningPortholes _portholes;
private int _pictureWidth;
private int _pictureHeight;
protected int _startPosX;
protected int _startPosY;
private int _airbusWidth = 124;
private int _airbusHeight = 44;
// Получение объекта IMoveableObject из объекта DrawningCar;
public IMoveableObject GetMoveableObject() {
return new DrawningObjectAirbus(this);
}
public int GetPosX() { return _startPosX; }
public int GetPosY() { return _startPosY; }
public int GetWidth() { return _airbusWidth; }
public int GetHeight() { return _airbusHeight; }
public DrawningAirbus(int speed, float weight, Color bodyColor, int countPortholes, int width, int height) {
if (width < _airbusWidth || height < _airbusHeight)
return;
_pictureWidth = width;
_pictureHeight = height;
entityAirbus = new EntityAirbus(speed, weight, bodyColor);
_portholes = new DrawningPortholesCircle();
_portholes.SetCount(countPortholes);
}
// изменение границы поля, когда закрываем конфиг
public void ChangeBordersPicture(int width, int height)
{
_pictureWidth = width;
_pictureHeight = height;
}
public void SetPosition (int x, int y) {
if (x + _airbusWidth > _pictureWidth || y + _airbusHeight > _pictureHeight) {
_startPosX = _pictureWidth - _airbusWidth;
_startPosY = _pictureHeight - _airbusHeight;
}
else
{
_startPosX = x;
_startPosY = y;
}
}
public boolean CanMove(Direction direction)
{
if (entityAirbus == null)
{
return false;
}
switch (direction)
{
case Left:
return _startPosX - entityAirbus.Step > 0;
case Right:
return _startPosX + _airbusWidth + entityAirbus.Step < _pictureWidth;
case Up:
return _startPosY - entityAirbus.Step > 0;
case Down:
return _startPosY + _airbusHeight + entityAirbus.Step < _pictureHeight;
default:
return false;
}
}
public void MoveTransport(Direction direction){
if (entityAirbus == null) {
return;
}
switch (direction) {
case Left:
_startPosX -= entityAirbus.Step;
break;
case Right:
_startPosX += entityAirbus.Step;
break;
case Up:
_startPosY -= entityAirbus.Step;
break;
case Down:
_startPosY += entityAirbus.Step;
break;
}
}
public void DrawTransport(Graphics2D g) {
if (entityAirbus == null) {
return;
}
// тело
g.setColor(entityAirbus.getBodyColor());
g.fillRect(_startPosX+3, _startPosY+17, 103, 20);
g.setColor(Color.BLACK);
g.drawRect(_startPosX+3, _startPosY+17, 103, 20);
// иллюминаторы
_portholes.Draw(g, _startPosX, _startPosY);
// нос
int[] xPolygonNoise = {_startPosX+106, _startPosX + 120, _startPosX+106,};
int[] yPolygonNoise = {_startPosY+17, _startPosY+27, _startPosY+37};
g.setColor(entityAirbus.getBodyColor());
g.fillPolygon(xPolygonNoise, yPolygonNoise, xPolygonNoise.length);
g.setColor(Color.BLACK);
g.drawPolygon(xPolygonNoise, yPolygonNoise, xPolygonNoise.length);
// хвост
int[] xPolygonTale = { _startPosX+2, _startPosX+27, _startPosX+2};
int[] yPolygonTale = {_startPosY, _startPosY + 18,_startPosY+18};
g.setColor(entityAirbus.getBodyColor());
g.fillPolygon(xPolygonTale, yPolygonTale, xPolygonTale.length);
g.setColor(Color.BLACK);
g.drawPolygon(xPolygonTale, yPolygonTale, xPolygonTale.length);
// крыло
g.setColor(Color.BLACK);
g.fillOval(_startPosX+43, _startPosY+25, 22, 5);
g.drawOval(_startPosX+43, _startPosY+25, 22, 5);
// двигатель
g.setColor(Color.BLACK);
g.fillOval(_startPosX+1, _startPosY+15, 19, 5);
g.drawOval(_startPosX+1, _startPosY+15, 19, 5);
// шасси
g.setColor(entityAirbus.getBodyColor());
g.fillOval(_startPosX+25,_startPosY+38, 6, 6);
g.fillOval(_startPosX+30,_startPosY+38, 6, 6);
g.fillOval(_startPosX+100,_startPosY+38, 6, 6);
g.setColor(Color.BLACK);
g.drawOval(_startPosX+25,_startPosY+38, 6, 6);
g.drawOval(_startPosX+30,_startPosY+38, 6, 6);
g.drawOval(_startPosX+100,_startPosY+38, 6, 6);
}
}

View File

@ -0,0 +1,43 @@
package Drawnings;
import Entities.EntityPlane;
import java.awt.*;
public class DrawningPlane extends DrawningAirbus {
public DrawningPlane(int speed, float weight, Color bodyColor, int countPortholes, Color additionalColor, boolean isCompartment, boolean isAdditionalEngine, int width, int height)
{
super(speed, weight, bodyColor, countPortholes, width, height);
if (entityAirbus != null) {
entityAirbus = new EntityPlane(speed, weight, bodyColor, additionalColor, isCompartment, isAdditionalEngine);
}
}
@Override
public void DrawTransport(Graphics2D g) {
if (entityAirbus == null)
{
return;
}
Color additionalColor = ((EntityPlane)entityAirbus).getAdditionalColor();
// пассажирский отсек
if (((EntityPlane)entityAirbus).IsCompartment()) {
g.setColor(additionalColor);
g.fillOval(_startPosX + 57, _startPosY + 11, 39, 9);
g.setColor(Color.BLACK);
g.drawOval(_startPosX + 57, _startPosY + 11, 39, 9);
}
super.DrawTransport(g);
// доп двигатель
if (((EntityPlane)entityAirbus).IsAdditionalEngine()) {
g.setColor(additionalColor);
g.fillOval(_startPosX, _startPosY + 25, 11, 5);
g.setColor(Color.BLACK);
g.drawOval(_startPosX, _startPosY + 25, 11, 5);
}
}
}

View File

@ -0,0 +1,54 @@
package Drawnings;
import java.awt.*;
import Entities.*;
public class DrawningPortholesCircle implements IDrawningPortholes {
private CountPortholes _porthole;
public int Count;
public int getCount() {
return Count;
}
public void SetCount (int count) {
Count = count;
switch (Count) {
case 10:
_porthole = CountPortholes.Ten;
break;
case 20:
_porthole = CountPortholes.Twenty;
break;
case 30:
_porthole = CountPortholes.Thirty;
break;
default:
_porthole = CountPortholes.Ten;
break;
}
//Draw();
}
protected void drawPortholes(Graphics2D g, int posX, int posY){
g.setColor(Color.cyan);
g.fillOval(posX, posY, 3, 3);
g.setColor(Color.black);
g.drawOval(posX, posY, 3, 3);
}
public void Draw (Graphics2D g, int _startPosX, int _startPosY) {
for (int i = 0; i < 10; ++i) {
drawPortholes(g, _startPosX + 19 + i * 8, _startPosY + 21);
}
if (_porthole == CountPortholes.Ten) {
return;
}
for (int i = 0; i < 5; ++i) {
drawPortholes(g, _startPosX + 15 + i * 5, _startPosY + 26);
drawPortholes(g, _startPosX + 70 + i * 5, _startPosY + 26);
}
if (_porthole == CountPortholes.Twenty) {
return;
}
for (int i = 0; i < 10; ++i) {
drawPortholes(g, _startPosX + 19 + i * 8, _startPosY + 31);
}
}
}

View File

@ -0,0 +1,16 @@
package Drawnings;
import Entities.CountPortholes;
import java.awt.*;
public class DrawningPortholesHeart extends DrawningPortholesCircle {
protected void drawPortholes(Graphics2D g, int posX, int posY) {
int[] HeartX = {posX + 2, posX, posX, posX + 1, posX + 2, posX + 3, posX + 5, posX + 5};
int[] HeartY = {posY + 4, posY + 2, posY, posY, posY + 1, posY, posY, posY + 2};
g.setColor(Color.cyan);
g.fillPolygon(HeartX, HeartY, HeartX.length);
g.setColor(Color.black);
g.drawPolygon(HeartX, HeartY, HeartX.length);
}
}

View File

@ -0,0 +1,14 @@
package Drawnings;
import Entities.CountPortholes;
import java.awt.*;
public class DrawningPortholesSquare extends DrawningPortholesCircle {
protected void drawPortholes(Graphics2D g, int posX, int posY){
g.setColor(Color.cyan);
g.fillRect(posX, posY, 3, 3);
g.setColor(Color.black);
g.drawRect(posX, posY, 3, 3);
}
}

View File

@ -0,0 +1,10 @@
package Drawnings;
import java.awt.*;
import Entities.CountPortholes;
public interface IDrawningPortholes {
public int getCount();
public void SetCount (int count);
public void Draw (Graphics2D g, int _startPosX, int _startPoxY);
}

View File

@ -0,0 +1,6 @@
package Entities;
public enum CountPortholes {
Ten,
Twenty,
Thirty;
}

View File

@ -0,0 +1,34 @@
package Entities;
import java.awt.*;
public class EntityAirbus {
private int Speed;
private float Weight;
private Color BodyColor;
public float Step;
public int getSpeed() {
return Speed;
}
public float getWeight() {
return Weight;
}
public Color getBodyColor() {
return BodyColor;
}
public EntityAirbus(int speed, float weight, Color bodyColor)
{
Weight = weight;
Speed = speed;
BodyColor = bodyColor;
Step = Speed * 100 / (int) Weight;
}
public void changeBodyColor(Color color) {
BodyColor = color;
}
}

View File

@ -0,0 +1,23 @@
package Entities;
import javax.swing.text.AttributeSet;
import java.awt.*;
public class EntityPlane extends EntityAirbus {
private Color AdditionalColor;
private boolean IsCompartment;
private boolean IsAdditionalEngine;
public EntityPlane(int speed, float weight, Color bodyColor, Color additionalColor, boolean isCompartment, boolean isAdditionalEngine) {
super(speed, weight, bodyColor);
AdditionalColor = additionalColor;
IsCompartment = isCompartment;
IsAdditionalEngine = isAdditionalEngine;
}
public Color getAdditionalColor() { return AdditionalColor; }
public boolean IsCompartment() { return IsCompartment; }
public boolean IsAdditionalEngine() { return IsAdditionalEngine; }
public void changeAdditionalColor(Color color) {
AdditionalColor = color;
}
}

291
src/FormAirbus.java Normal file
View File

@ -0,0 +1,291 @@
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import java.util.Random;
import Drawnings.*;
import MovementStrategy.*;
public class FormAirbus extends JFrame {
private int width;
private int height;
public DrawningAirbus _drawningAirbus;
private AbstractStrategy _abstractStrategy;
private Canvas canvas;
// выбор кол-ва иллюминаторов
JLabel labelCount;
private JTextField fieldCount;
// выбор стратегии
JLabel labelStrategy;
JComboBox comboBoxStrategy;
JButton buttonStrategy;
private JButton buttonCreateAirbus;
private JButton buttonCreatePlane;
public JButton buttonSelectAirbus;
private JButton buttonUp;
private JButton buttonDown;
private JButton buttonRight;
private JButton buttonLeft;
public FormAirbus() {
super("Создание самолёта");
InitializeComponent();
setVisible(true);
}
private void InitializeComponent()
{
canvas = new Canvas();
labelCount = new JLabel("Введите число иллюминаторов:");
fieldCount = new JTextField();
labelStrategy = new JLabel("Шаг стратегии:");
comboBoxStrategy = new JComboBox(new Integer[] {0, 1});
buttonStrategy = new JButton("Выбрать стратегию");
buttonStrategy.setMargin(new Insets(0, 0, 0, 0));
buttonCreateAirbus = new JButton("Создать аэробус");
buttonCreateAirbus.setMargin(new Insets(0, 0, 0, 0));
buttonCreatePlane = new JButton("Создать самолёт");
buttonCreatePlane.setMargin(new Insets(0, 0, 0, 0));
buttonSelectAirbus = new JButton("Выбрать");
buttonSelectAirbus.setMargin(new Insets(0, 0, 0, 0));
buttonUp = new JButton();
buttonUp.setName("up");
buttonUp.setIcon(new ImageIcon("images\\KeyUp.png"));
buttonRight = new JButton();
buttonRight.setName("right");
buttonRight.setIcon(new ImageIcon("images\\KeyRight.png"));
buttonLeft = new JButton();
buttonLeft.setName("left");
buttonLeft.setIcon(new ImageIcon("images\\KeyLeft.png"));
buttonDown = new JButton();
buttonDown.setName("down");
buttonDown.setIcon(new ImageIcon("images\\KeyDown.png"));
setSize(800,500);
setLayout(null);
buttonCreateAirbus.setBounds(12, 355, 130, 25);
buttonCreatePlane.setBounds(buttonCreateAirbus.getX()+140, 355, 130, 25);
buttonSelectAirbus. setBounds(buttonCreatePlane.getX()+140, 355, 130, 25);
labelCount.setBounds(42, 405, 240, 20);
fieldCount.setBounds(240, 407, 48, 20);
labelStrategy.setBounds(630, 20, 146, 33);
comboBoxStrategy.setBounds(630, 50, 146, 20);
buttonStrategy.setBounds(630, 80, 146, 33);
buttonUp.setBounds(679, 313, 48, 44);
buttonRight.setBounds( 728, 358, 48, 44);
buttonLeft.setBounds(630, 358, 48, 44);
buttonDown.setBounds( 679, 358, 48, 44);
labelCount.setBounds(12, 405, 240, 20);
fieldCount.setBounds(210, 407, 48, 20);
canvas.setBounds(0,0,790, 460);
add(buttonCreateAirbus);
add(buttonCreatePlane);
add(buttonSelectAirbus);
add(labelCount);
add(fieldCount);
add(labelStrategy);
add(comboBoxStrategy);
add(buttonStrategy);
add(buttonUp);
add(buttonRight);
add(buttonDown);
add(buttonLeft);
add(labelCount);
add(fieldCount);
add(canvas);
// логика формы
buttonCreateAirbus.addActionListener(buttonCreateAirbusListener);
buttonCreatePlane.addActionListener(buttonCreatePlaneListener);
buttonStrategy.addActionListener(buttonStrategyListener);
buttonUp.addActionListener(buttonsMoveListener);
buttonRight.addActionListener(buttonsMoveListener);
buttonDown.addActionListener(buttonsMoveListener);
buttonLeft.addActionListener(buttonsMoveListener);
}
ActionListener buttonCreateAirbusListener = new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
Random rand = new Random();
// базовый цвет
Color color = new Color(rand.nextInt(0, 256), rand.nextInt(0, 256), rand.nextInt(0, 256));
Color selectedColor = JColorChooser.showDialog(null, "Выберите цвет", Color.BLACK);
if (selectedColor != null)
{
color = selectedColor;
}
int countPortholes;
try
{
countPortholes = Integer.parseInt(fieldCount.getText());
}
catch (Exception ex)
{
countPortholes = 0;
}
if (countPortholes != 10 && countPortholes != 20 && countPortholes != 30)
{
JOptionPane.showMessageDialog(null, "Число должно быть равно 10, 20 или 30.\nКол-во иллюминаторов приравнено к 10");
countPortholes = 10;
}
_drawningAirbus = new DrawningAirbus(
rand.nextInt(200) + 100, rand.nextInt(2000) + 1000,
color,
countPortholes,
canvas.getWidth(), canvas.getHeight());
_drawningAirbus.SetPosition(rand.nextInt(100) + 10, rand.nextInt(100) + 10);
comboBoxStrategy.setEnabled(true);
canvas.repaint();
}
};
ActionListener buttonCreatePlaneListener = new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
Random rand = new Random();
// базовый цвет
Color color = new Color(rand.nextInt(0, 256), rand.nextInt(0, 256), rand.nextInt(0, 256));
Color selectedColor = JColorChooser.showDialog(null, "Выберите цвет", Color.BLACK);
if (selectedColor != null)
{
color = selectedColor;
}
// доп цвет
Color additionalColor = new Color(rand.nextInt(0, 256), rand.nextInt(0, 256), rand.nextInt(0, 256));
selectedColor = JColorChooser.showDialog(null, "Выберите доп. цвет", Color.GRAY);
if (selectedColor != null)
{
additionalColor = selectedColor;
}
int countPortholes;
try
{
countPortholes = Integer.parseInt(fieldCount.getText());
}
catch (Exception ex)
{
countPortholes = 0;
}
if (countPortholes != 10 && countPortholes != 20 && countPortholes != 30)
{
JOptionPane.showMessageDialog(null, "Число должно быть равно 10, 20 или 30.\nКол-во иллюминаторов приравнено к 10");
countPortholes = 10;
}
_drawningAirbus = new DrawningPlane(
rand.nextInt(200) + 100, rand.nextInt(2000) + 1000,
color,
countPortholes,
additionalColor,
rand.nextBoolean(), rand.nextBoolean(),
canvas.getWidth(), canvas.getHeight());
_drawningAirbus.SetPosition(rand.nextInt(100) + 10, rand.nextInt(100) + 10);
comboBoxStrategy.setEnabled(true);
canvas.repaint();
}
};
ActionListener buttonStrategyListener = new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
if (_drawningAirbus == 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 DrawningObjectAirbus(_drawningAirbus), canvas.getWidth(), canvas.getHeight());
comboBoxStrategy.setEnabled(false);
}
if (_abstractStrategy == null)
{
return;
}
_abstractStrategy.MakeStep();
if (_abstractStrategy.GetStatus() == Status.Finish)
{
comboBoxStrategy.setEnabled(true);
_abstractStrategy = null;
}
canvas.repaint();
}
};
ActionListener buttonsMoveListener = new ActionListener() {
// реакция на нажатие
public void actionPerformed(ActionEvent e) {
if (_drawningAirbus == null)
{
return;
}
String command = ((JButton)(e.getSource())).getName();
switch (command) {
case "up":
_drawningAirbus.MoveTransport(Direction.Up);
break;
case "down":
_drawningAirbus.MoveTransport(Direction.Down);
break;
case "right":
_drawningAirbus.MoveTransport(Direction.Right);
break;
case "left":
_drawningAirbus.MoveTransport(Direction.Left);
break;
}
canvas.repaint();
}
};
class Canvas extends JComponent{
public Canvas() {}
public void paintComponent (Graphics g){
if (_drawningAirbus == null){
return;
}
super.paintComponents (g) ;
Graphics2D g2d = (Graphics2D)g;
_drawningAirbus.DrawTransport(g2d);
super.repaint();
}
}
}

View File

@ -0,0 +1,295 @@
import Drawnings.DrawningAirbus;
import Generics.AirbusGenericCollection;
import Generics.AirbusGenericStorage;
import MovementStrategy.DrawningObjectAirbus;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.LinkedList;
import javax.swing.*;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
public class FormAirbusCollection extends JFrame {
private Canvas canvas;
private AirbusGenericStorage _storage;
static int pictureBoxWidth = 650;
static int pictureBoxHeight = 460;
private JButton buttonGenerateAirbus;
private JButton buttonUpdate;
private JButton buttonAddAirbus;
private JButton buttonDeleteAirbus;
// работа с наборами
private JButton buttonAddStorage;
private JButton buttonDeleteStorage;
private JButton buttonGetDeleted;
private JTextField textFieldStorage;
private JList<String> listStorage;
private DefaultListModel<String> listModel;
LinkedList<DrawningAirbus> linkedListDeleted;
private JTextField textFieldNumber;
private AirbusGenericCollection<DrawningAirbus, DrawningObjectAirbus> _airbus;
FormAirbusCollection() {
listModel = new DefaultListModel<String>();
listStorage = new JList<String>(listModel);
_airbus = new AirbusGenericCollection<DrawningAirbus, DrawningObjectAirbus> (pictureBoxWidth, pictureBoxHeight);
_storage = new AirbusGenericStorage(pictureBoxWidth, pictureBoxHeight);
linkedListDeleted = new LinkedList<DrawningAirbus>();
canvas = new Canvas();
JFrame frame = new JFrame("Коллекция аэробусов");
buttonAddStorage = new JButton("Добавить набор");
buttonAddStorage.setMargin(new Insets(0, 0, 0, 0));
buttonDeleteStorage = new JButton("Удалить набор");
buttonDeleteStorage.setMargin(new Insets(0, 0, 0, 0));
buttonAddAirbus = new JButton("Добавить аэробус");
buttonAddAirbus.setMargin(new Insets(0, 0, 0, 0));
buttonDeleteAirbus = new JButton("Удалить аэробус");
buttonDeleteAirbus.setMargin(new Insets(0, 0, 0, 0));
buttonUpdate = new JButton("Обновить");
buttonUpdate.setMargin(new Insets(0, 0, 0, 0));
buttonGetDeleted = new JButton("Загрузить удалёнки");
buttonGetDeleted.setMargin(new Insets(0, 0, 0, 0));
buttonGenerateAirbus = new JButton("Форма генерации");
buttonGenerateAirbus.setMargin(new Insets(0,0,0,0));
textFieldStorage = new JTextField();
textFieldNumber = new JTextField();
setSize(800,500);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(null);
textFieldStorage.setBounds(pictureBoxWidth, 20, 120, 25);
buttonAddStorage.setBounds(pictureBoxWidth, textFieldStorage.getY()+30, 120, 25);
listStorage.setBounds(pictureBoxWidth, buttonAddStorage.getY()+30, 120, 120);
buttonDeleteStorage.setBounds(pictureBoxWidth, listStorage.getY()+125, 120, 25);
buttonAddAirbus.setBounds(pictureBoxWidth, buttonDeleteStorage.getY()+30, 120, 25);
textFieldNumber.setBounds(pictureBoxWidth, buttonAddAirbus.getY()+30, 120, 25);
buttonDeleteAirbus.setBounds(pictureBoxWidth, textFieldNumber.getY()+30, 120, 25);
buttonUpdate.setBounds(pictureBoxWidth, buttonDeleteAirbus.getY()+30, 120, 25);
buttonGetDeleted.setBounds(pictureBoxWidth, buttonUpdate.getY()+30, 120, 25);
buttonGenerateAirbus.setBounds(pictureBoxWidth, buttonGetDeleted.getY()+30, 120, 25);
canvas.setBounds(0,0,pictureBoxWidth, pictureBoxHeight);
add(canvas);
add(buttonAddStorage);
add(listStorage);
add(textFieldStorage);
add(buttonDeleteStorage);
add(buttonAddAirbus);
add(buttonDeleteAirbus);
add(buttonUpdate);
add(buttonGenerateAirbus);
add(buttonGetDeleted);
add(textFieldNumber);
setVisible(true);
// логика формы
buttonAddStorage.addActionListener(AddStorageListener);
buttonDeleteStorage.addActionListener(DeleteStorageListener);
buttonGetDeleted.addActionListener(GetDeletedListener);
listStorage.addListSelectionListener(listSelectionListener);
buttonAddAirbus.addActionListener(AddAirbusListener);
buttonDeleteAirbus.addActionListener(DeleteAirbusListener);
buttonUpdate.addActionListener(UpdateAirbusListener);
buttonGenerateAirbus.addActionListener(OpenGenerationForm);
}
// секция работы с наборами
private void ReloadObject()
{
int index = listStorage.getSelectedIndex();
listModel.clear();
for (int i = 0; i < _storage.Keys().size(); i++)
{
listModel.addElement(_storage.Keys().get(i));
}
if (listModel.size() > 0 && (index == -1 || index >= listModel.size()))
{
listStorage.setSelectedIndex(0);
}
else if (listModel.size() > 0 && index > -1 && index < listModel.size())
{
listStorage.setSelectedIndex(index);
}
}
// добавить набор
ActionListener AddStorageListener = new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
if (textFieldStorage.getText().length() == 0)
{
JOptionPane.showMessageDialog(null, "Не все данные заполнены", "Информация", JOptionPane.INFORMATION_MESSAGE);
return;
}
_storage.AddSet(textFieldStorage.getText());
ReloadObject();
}
};
// выбрать
ListSelectionListener listSelectionListener = new ListSelectionListener() {
// public т.к. в интерфейсе метод тоже public
public void valueChanged(ListSelectionEvent e) {
canvas.repaint();
}
};
// удалить набор
ActionListener DeleteStorageListener = new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
if (listStorage.getSelectedIndex() == -1)
return;
if (JOptionPane.showOptionDialog(null, "Удалить " + listStorage.getSelectedValue() + "?", "Удаление", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE, null, new Object[] { "Да", "Нет"}, "Да")
== JOptionPane.NO_OPTION)
return;
_storage.DelSet(listStorage.getSelectedValue());
ReloadObject();
}
};
// загрузить удалёнки
ActionListener GetDeletedListener = new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
if (linkedListDeleted.size() == 0)
{
JOptionPane.showMessageDialog(null, "Нет удалённых аэробусов", "Информация", JOptionPane.INFORMATION_MESSAGE);
return;
}
FormAirbus form = new FormAirbus();
form._drawningAirbus = linkedListDeleted.getLast();
linkedListDeleted.removeLast();
canvas.repaint();
}
};
// конец секции работы с наборами
ActionListener OpenGenerationForm = new ActionListener()
{
@Override
public void actionPerformed(ActionEvent e) {
FormGenerationAirbus form = new FormGenerationAirbus();
dispose();
}
};
// добавить аэробус в набор
ActionListener AddAirbusListener = new ActionListener()
{
@Override
public void actionPerformed(ActionEvent e) {
if (listStorage.getSelectedIndex() == -1)
return;
var obj = _storage.get(listStorage.getSelectedValue());
if (obj == null)
return;
// выбор аэробуса на второй форме
FormAirbusConfig form = new FormAirbusConfig();
form.buttonOk.addActionListener(
new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
if (obj != null && obj.Add(form._airbus) != -1) {
form._airbus.ChangeBordersPicture(pictureBoxWidth, pictureBoxHeight);
canvas.repaint();
JOptionPane.showMessageDialog(null, "Объект добавлен");
} else {
JOptionPane.showMessageDialog(null, "Не удалось добавить объект", "Ошибка", JOptionPane.ERROR_MESSAGE);
}
form.frame.dispose();
}
}
);
}
};
// удалить аэробус
ActionListener DeleteAirbusListener = new ActionListener()
{
@Override
public void actionPerformed(ActionEvent e) {
if (listStorage.getSelectedIndex() == -1)
return;
var obj = _storage.get(listStorage.getSelectedValue());
if (obj == null)
return;
Object[] options= {"да", "нет"};
if (JOptionPane.showOptionDialog(null, "Удалить объект?", "Удаление", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE, null, new Object[] { "Да", "Нет"}, "Да")
== JOptionPane.NO_OPTION)
return;
try {
int pos = Integer.parseInt(textFieldNumber.getText());
// запоминаем удалёнку
DrawningAirbus deleted = obj.GetT(pos);
if (obj.Remove(pos)) {
// добавить в список удалёнок
linkedListDeleted.add(deleted);
JOptionPane.showMessageDialog(null, "Объект удален", "Информация", JOptionPane.INFORMATION_MESSAGE);
canvas.repaint();
}
else
{
JOptionPane.showMessageDialog(null, "Не удалось удалить объект", "Информация", JOptionPane.INFORMATION_MESSAGE);
}
}
catch (Exception ex)
{
JOptionPane.showMessageDialog(null, "Не удалось удалить объект", "Информация", JOptionPane.INFORMATION_MESSAGE);
return;
}
}
};
// обновить
ActionListener UpdateAirbusListener = new ActionListener()
{
@Override
public void actionPerformed(ActionEvent e) {
canvas.repaint();
}
};
class Canvas extends JComponent {
public Canvas() {}
public void paintComponent(Graphics g) {
super.paintComponents(g);
if (listStorage.getSelectedIndex() == -1)
return;
var obj = _storage.get(listStorage.getSelectedValue());
if (obj == null)
return;
if (obj.ShowAirbus() != null)
g.drawImage(obj.ShowAirbus(), 0, 0, this);
super.repaint();
}
}
}

545
src/FormAirbusConfig.java Normal file
View File

@ -0,0 +1,545 @@
import Drawnings.*;
import Entities.EntityAirbus;
import Entities.EntityPlane;
import javax.swing.*;
import javax.swing.border.Border;
import java.awt.*;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.StringSelection;
import java.awt.datatransfer.Transferable;
import java.awt.datatransfer.UnsupportedFlavorException;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.io.IOException;
import java.util.Random;
public class FormAirbusConfig extends JFrame {
DrawningAirbus _airbus = null;
ComponentPortholes compPortholesCircle;
ComponentPortholes compPortholesHeart;
ComponentPortholes compPortholesSquare;
FormAirbusConfig() {
InitializeComponent();
}
//// drag and drop
// для переноса типа объекта в лэйбл
private class LabelTransferHandler extends TransferHandler {
@Override
public int getSourceActions(JComponent c) {
return TransferHandler.COPY;
}
@Override
protected Transferable createTransferable(JComponent c) {
return new StringSelection(((JLabel)c).getText());
}
}
// перетаскиваемый panel.color
private class ColorTransferable implements Transferable {
private Color color;
private static final DataFlavor colorDataFlavor = new DataFlavor(Color.class, "Color");
public ColorTransferable(Color color) {
this.color = color;
}
@Override
public DataFlavor[] getTransferDataFlavors() {
return new DataFlavor[]{colorDataFlavor};
}
@Override
public boolean isDataFlavorSupported(DataFlavor flavor) {
return colorDataFlavor.equals(flavor);
}
@Override
public Object getTransferData(DataFlavor flavor) throws UnsupportedFlavorException, IOException {
if (isDataFlavorSupported(flavor)) {
return color;
} else {
throw new UnsupportedFlavorException(flavor);
}
}
}
// для переноса цвета в лэйбл
private 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());
}
}
// нажатие на панель/лэйбл
private class LabelMouseAdapter extends MouseAdapter {
@Override
public void mousePressed(MouseEvent e) {
((JLabel)e.getComponent()).getTransferHandler().exportAsDrag(((JLabel)e.getComponent()), e, TransferHandler.COPY);
}
}
private class PanelMouseAdapter extends MouseAdapter{
@Override
public void mousePressed(MouseEvent e) {
((JPanel)e.getComponent()).getTransferHandler().exportAsDrag(((JPanel)e.getComponent()), e, TransferHandler.COPY);
}
}
// приём перетаскиваемого цвета
private class ColorBody_DragDrop extends TransferHandler {
@Override
public boolean canImport(TransferHandler.TransferSupport support) {
return support.isDataFlavorSupported(ColorTransferable.colorDataFlavor);
}
@Override
public boolean importData(TransferHandler.TransferSupport support) {
if (canImport(support)) {
try {
Color color = (Color) support.getTransferable().getTransferData(ColorTransferable.colorDataFlavor);
if (_airbus == null)
return false;
_airbus.entityAirbus.changeBodyColor(color);
canvas.repaint();
return true;
} catch (UnsupportedFlavorException | IOException e) {
e.printStackTrace();
}
}
return false;
}
}
private class ColorAdditional_DragDrop extends TransferHandler {
@Override
public boolean canImport(TransferHandler.TransferSupport support) {
return support.isDataFlavorSupported(ColorTransferable.colorDataFlavor);
}
@Override
public boolean importData(TransferHandler.TransferSupport support) {
if (canImport(support)) {
try {
Color color = (Color) support.getTransferable().getTransferData(ColorTransferable.colorDataFlavor);
if (_airbus == null)
return false;
if (!(_airbus instanceof DrawningPlane))
return false;
((EntityPlane)_airbus.entityAirbus).changeAdditionalColor(color);
return true;
} catch (UnsupportedFlavorException | IOException e) {
e.printStackTrace();
}
}
return false;
}
}
// перетаскиваемые иллюминаторы
private class PortholesTransferable implements Transferable {
private IDrawningPortholes drawningPortholes;
private static final DataFlavor portholesDrawingDataFlavor = new DataFlavor(IDrawningPortholes.class, "Portholes Drawning");
public PortholesTransferable(IDrawningPortholes portholes)
{
drawningPortholes = portholes;
}
@Override
public DataFlavor[] getTransferDataFlavors() {
return new DataFlavor[]{ portholesDrawingDataFlavor };
}
@Override
public boolean isDataFlavorSupported(DataFlavor flavor) {
return flavor.equals(portholesDrawingDataFlavor);
}
@Override
public Object getTransferData(DataFlavor flavor) throws UnsupportedFlavorException, IOException {
if (isDataFlavorSupported(flavor)) {
return drawningPortholes;
} else {
throw new UnsupportedFlavorException(flavor);
}
}
}
private class ComponentPortholes extends JComponent{
public IDrawningPortholes drawningPortholes;
public ComponentPortholes(IDrawningPortholes drawningPortholes1)
{
drawningPortholes = drawningPortholes1;
addMouseListener(new LabelPortholesMouseAdapter());
setTransferHandler(new LabelPortholesTransferHandler());
}
private class LabelPortholesMouseAdapter extends MouseAdapter {
@Override
public void mousePressed(MouseEvent e) {
((ComponentPortholes)e.getComponent()).getTransferHandler().exportAsDrag(((ComponentPortholes)e.getComponent()), e, TransferHandler.COPY);
}
}
private class LabelPortholesTransferHandler extends TransferHandler {
@Override
public int getSourceActions(JComponent c) {
return TransferHandler.COPY;
}
@Override
protected Transferable createTransferable(JComponent c) {
return new PortholesTransferable(((ComponentPortholes)c).drawningPortholes);
}
}
public void paintComponent (Graphics g){
super.paintComponents (g) ;
Graphics2D g2d = (Graphics2D)g;
drawningPortholes.Draw(g2d, -13,-15);
super.repaint();
}
}
// приём иллюминаторов
private class LabelPortholesTransferHandler extends TransferHandler {
@Override
public boolean canImport(TransferHandler.TransferSupport support) {
return support.isDataFlavorSupported(PortholesTransferable.portholesDrawingDataFlavor);
}
@Override
public boolean importData(TransferHandler.TransferSupport support) {
if (canImport(support)) {
try {
IDrawningPortholes portholes = (IDrawningPortholes) support.getTransferable().getTransferData(PortholesTransferable.portholesDrawingDataFlavor);
if (_airbus == null)
return false;
portholes.SetCount(_airbus._portholes.getCount());
_airbus._portholes = portholes;
canvas.repaint();
} catch (UnsupportedFlavorException | IOException e) {
e.printStackTrace();
}
}
return false;
}
}
private void InitializeComponent() {
// инициализация
Random rand = new Random();
frame = new JFrame("Конструирование самолёта");
canvas = new Canvas();
groupBoxConfig = new JPanel();
groupBoxColors = new JPanel();
groupBoxPortholes = new JPanel();
panelObject = new JPanel();
panelRed = new JPanel();
panelYellow = new JPanel();
panelBlue = new JPanel();
panelViolet = new JPanel();
panelGreen = new JPanel();
panelWhite = new JPanel();
panelOrange = new JPanel();
panelSilver = new JPanel();
labelAdditionalColor = new JLabel("Доп.цвет", SwingConstants.CENTER);
labelBodyColor = new JLabel("Основной цвет", SwingConstants.CENTER);
labelSimpleObject = new JLabel("Простой", SwingConstants.CENTER);
labelComplexObject = new JLabel("Продвинутый", SwingConstants.CENTER);
labelPortholes = new JLabel("Иллюминаторы", SwingConstants.CENTER);
labelSpeed = new JLabel("Скорость: ");
labelWeight = new JLabel("Вес: ");
labelPortholesCount = new JLabel("Кол-во иллюминаторов:");
buttonOk = new JButton("Добавить");
buttonCancel = new JButton("Отмена");
checkBoxAdditionalEngine = new JCheckBox("Добавить доп. двигатель");
checkBoxCompartment = new JCheckBox("Добавить пассажирский отсек");
spinnerModelSpeed = new SpinnerNumberModel(rand.nextInt(900)+100, 100, 1000, 1);
numericUpDownSpeed = new JSpinner(spinnerModelSpeed);
spinnerModelWeight = new SpinnerNumberModel(rand.nextInt(1000)+100, 100, 1000, 1);
numericUpDownWeight = new JSpinner(spinnerModelWeight);
spinnerModelPortholesCount = new SpinnerNumberModel(10, 10, 30, 10);
numericUpDownPortholesCount = new JSpinner(spinnerModelPortholesCount);
compPortholesCircle = new ComponentPortholes(new DrawningPortholesCircle());
compPortholesHeart = new ComponentPortholes(new DrawningPortholesHeart());
compPortholesSquare = new ComponentPortholes(new DrawningPortholesSquare());
// реализация
// groupBoxConfig
groupBoxConfig.setBorder(BorderFactory.createTitledBorder("Параметры"));
groupBoxConfig.setSize(620, 273);
groupBoxConfig.setLocation(24, 16);
groupBoxConfig.setLayout(null);
groupBoxConfig.add(numericUpDownSpeed);
groupBoxConfig.add(numericUpDownWeight);
groupBoxConfig.add(numericUpDownPortholesCount);
groupBoxConfig.add(labelSpeed);
groupBoxConfig.add(labelWeight);
groupBoxConfig.add(labelPortholesCount);
groupBoxConfig.add(checkBoxAdditionalEngine);
groupBoxConfig.add(checkBoxCompartment);
groupBoxConfig.add(groupBoxColors);
groupBoxConfig.add(labelSimpleObject);
groupBoxConfig.add(labelComplexObject);
groupBoxConfig.add(groupBoxPortholes);
// numericUpDownSpeed
numericUpDownSpeed.setSize(79, 27);
numericUpDownSpeed.setLocation(176, 41);
// numericUpDownWeight
numericUpDownWeight.setSize(79, 27);
numericUpDownWeight.setLocation(176, 73);
// numericUpDownPortholesCount
numericUpDownPortholesCount.setSize(79, 27);
numericUpDownPortholesCount.setLocation(176, 105);
// checkBoxAdditionalEngine
checkBoxAdditionalEngine.setSize(204, 24);
checkBoxAdditionalEngine.setLocation(22, 201);
// checkBoxCompartment
checkBoxCompartment.setSize(204, 24);
checkBoxCompartment.setLocation(22, 231);
// labelSpeed
labelSpeed.setSize(80, 20);
labelSpeed.setLocation(22, 43);
// labelWeight
labelWeight.setSize(36, 20);
labelWeight.setLocation(22, 75);
// labelPortholesCount
labelPortholesCount.setSize(150, 20);
labelPortholesCount.setLocation(22, 107);
// groupBoxColors
groupBoxColors.setBorder(BorderFactory.createTitledBorder("Цвета"));
groupBoxColors.setSize(279, 155);
groupBoxColors.setLocation(310, 21);
groupBoxColors.add(panelRed);
groupBoxColors.add(panelYellow);
groupBoxColors.add(panelBlue);
groupBoxColors.add(panelViolet);
groupBoxColors.add(panelGreen);
groupBoxColors.add(panelSilver);
groupBoxColors.add(panelOrange);
groupBoxColors.add(panelWhite);
groupBoxConfig.add(compPortholesCircle);
groupBoxConfig.add(compPortholesHeart);
groupBoxConfig.add(compPortholesSquare);
groupBoxColors.setLayout(null);
// panelRed
panelRed.setBackground(Color.RED);
panelRed.setSize(40, 40);
panelRed.setLocation(38, 43);
panelRed.setTransferHandler(new PanelTransferHandler());
panelRed.addMouseListener(new PanelMouseAdapter());
// panelYellow
panelYellow.setBackground(Color.YELLOW);
panelYellow.setSize(40, 40);
panelYellow.setLocation(93, 43);
panelYellow.setTransferHandler(new PanelTransferHandler());
panelYellow.addMouseListener(new PanelMouseAdapter());
// panelBlue
panelBlue.setBackground(Color.BLUE);
panelBlue.setSize(40, 40);
panelBlue.setLocation(148, 43);
panelBlue.setTransferHandler(new PanelTransferHandler());
panelBlue.addMouseListener(new PanelMouseAdapter());
// panelViolet
panelViolet.setBackground(Color.MAGENTA);
panelViolet.setSize(40, 40);
panelViolet.setLocation(204, 43);
panelViolet.setTransferHandler(new PanelTransferHandler());
panelViolet.addMouseListener(new PanelMouseAdapter());
// panelGreen
panelGreen.setBackground(Color.GREEN);
panelGreen.setSize(40, 40);
panelGreen.setLocation(38, 96);
panelGreen.setTransferHandler(new PanelTransferHandler());
panelGreen.addMouseListener(new PanelMouseAdapter());
// panelSilver
panelSilver.setBackground(Color.LIGHT_GRAY);
panelSilver.setSize(40, 40);
panelSilver.setLocation(148, 96);
panelSilver.setTransferHandler(new PanelTransferHandler());
panelSilver.addMouseListener(new PanelMouseAdapter());
// panelOrange
panelOrange.setBackground(Color.ORANGE);
panelOrange.setSize(40, 40);
panelOrange.setLocation(204, 96);
panelOrange.setTransferHandler(new PanelTransferHandler());
panelOrange.addMouseListener(new PanelMouseAdapter());
// panelWhite
panelWhite.setBackground(Color.WHITE);
panelWhite.setSize(40, 40);
panelWhite.setLocation(93, 96);
panelWhite.setTransferHandler(new PanelTransferHandler());
panelWhite.addMouseListener(new PanelMouseAdapter());
// groupBoxPortholes
groupBoxPortholes.setBorder(BorderFactory.createTitledBorder("Иллюминаторы"));
groupBoxPortholes.setSize(200, 58);
groupBoxPortholes.setLocation(43, 130);
groupBoxPortholes.setLayout(null);
groupBoxPortholes.add(compPortholesCircle);
groupBoxPortholes.add(compPortholesHeart);
groupBoxPortholes.add(compPortholesSquare);
// compPortholesCircle
compPortholesCircle.setSize(30,30);
compPortholesCircle.setLocation(25, 20);
compPortholesCircle.setBorder(BorderFactory.createLineBorder(Color.lightGray));
// compPortholesHeart
compPortholesHeart.setSize(30,30);
compPortholesHeart.setLocation(75, 20);
compPortholesHeart.setBorder(BorderFactory.createLineBorder(Color.lightGray));
// compPortholesSquare
compPortholesSquare.setSize(30,30);
compPortholesSquare.setLocation(125, 20);
compPortholesSquare.setBorder(BorderFactory.createLineBorder(Color.lightGray));
// labelComplexObject
labelComplexObject.setSize(120, 38);
labelComplexObject.setLocation(464, 185);
labelComplexObject.setBorder(BorderFactory.createLineBorder(Color.lightGray));
labelComplexObject.setTransferHandler(new LabelTransferHandler());
labelComplexObject.addMouseListener(new LabelMouseAdapter());
// labelSimpleObject
labelSimpleObject.setSize(120, 38);
labelSimpleObject.setLocation(314, 185);
labelSimpleObject.setBorder(BorderFactory.createLineBorder(Color.lightGray));
labelSimpleObject.setTransferHandler(new LabelTransferHandler());
labelSimpleObject.addMouseListener(new LabelMouseAdapter());
// panelObject
panelObject.setSize(382, 190);
panelObject.setLocation(650, 21);
panelObject.setBorder(BorderFactory.createLineBorder(Color.lightGray));
panelObject.add(labelAdditionalColor);
panelObject.add(labelBodyColor);
panelObject.add(labelPortholes);
panelObject.add(canvas);
panelObject.setLayout(null);
// labelBodyColor
labelBodyColor.setSize(107, 38);
labelBodyColor.setLocation(18, 9);
labelBodyColor.setBorder(BorderFactory.createLineBorder(Color.lightGray));
labelBodyColor.setTransferHandler(new ColorBody_DragDrop());
// labelAdditionalColor
labelAdditionalColor.setSize(107, 38);
labelAdditionalColor.setLocation(138, 9);
labelAdditionalColor.setBorder(BorderFactory.createLineBorder(Color.lightGray));
labelAdditionalColor.setTransferHandler(new ColorAdditional_DragDrop());
// labelPortholes
labelPortholes.setSize(107, 38);
labelPortholes.setLocation(258, 9);
labelPortholes.setBorder(BorderFactory.createLineBorder(Color.lightGray));
labelPortholes.setTransferHandler(new LabelPortholesTransferHandler());
// canvas
canvas.setSize(347, 109);
canvas.setLocation(18,55);
canvas.setBorder(BorderFactory.createLineBorder(Color.lightGray));
canvas.setTransferHandler(new Canvas_Drop());
// buttonOk
buttonOk.setSize(107, 43);
buttonOk.setLocation(726, 242);
// buttonCancel
buttonCancel.setSize(107, 43);
buttonCancel.setLocation(856, 242);
buttonCancel.addActionListener(buttonCancel_Click);
// FormAirbusConfig
frame.setSize(1074, 360);
frame.setLayout(null);
frame.add(groupBoxConfig);
frame.add(panelObject);
frame.add(buttonOk);
frame.add(buttonCancel);
frame.setVisible(true);
}
ActionListener buttonCancel_Click = new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
frame.dispose();
}
};
private class Canvas_Drop extends TransferHandler {
@Override
public boolean canImport(TransferHandler.TransferSupport support) {
return support.isDataFlavorSupported(DataFlavor.stringFlavor);
}
@Override
public boolean importData(TransferHandler.TransferSupport support) {
if (canImport(support)) {
try {
String data = (String) support.getTransferable().getTransferData(DataFlavor.stringFlavor);
switch (data) {
case "Простой":
_airbus = new DrawningAirbus((int)numericUpDownSpeed.getValue(), (int)numericUpDownWeight.getValue(), Color.DARK_GRAY, (int)numericUpDownPortholesCount.getValue(), canvas.getWidth(), canvas.getHeight());
break;
case "Продвинутый":
_airbus = new DrawningPlane((int)numericUpDownSpeed.getValue(), (int)numericUpDownWeight.getValue(), Color.DARK_GRAY, (int)numericUpDownPortholesCount.getValue(), Color.BLACK, checkBoxCompartment.isSelected(), checkBoxAdditionalEngine.isSelected(), canvas.getWidth(), canvas.getHeight());
break;
}
canvas.repaint();
return true;
} catch (UnsupportedFlavorException | IOException e) {
e.printStackTrace();
}
}
return false;
}
}
class Canvas extends JComponent {
public Canvas() {}
public void paintComponent(Graphics g) {
if (_airbus == null){
return;
}
super.paintComponents(g);
Graphics2D g2d = (Graphics2D)g;
_airbus.SetPosition(5, 5);
_airbus.DrawTransport(g2d);
super.repaint();
}
}
JFrame frame;
private Canvas canvas;
private JPanel groupBoxConfig;
private JPanel groupBoxPortholes;
private JSpinner numericUpDownWeight;
private SpinnerModel spinnerModelWeight;
private JSpinner numericUpDownSpeed;
private SpinnerModel spinnerModelSpeed;
private JSpinner numericUpDownPortholesCount;
private SpinnerModel spinnerModelPortholesCount;
private JCheckBox checkBoxAdditionalEngine;
private JCheckBox checkBoxCompartment;
private JLabel labelWeight;
private JLabel labelSpeed;
private JLabel labelPortholesCount;
private JPanel groupBoxColors;
private JPanel panelRed;
private JPanel panelYellow;
private JPanel panelBlue;
private JPanel panelViolet;
private JPanel panelGreen;
private JPanel panelWhite;
private JPanel panelOrange;
private JPanel panelSilver;
private JLabel labelComplexObject;
private JLabel labelSimpleObject;
private JLabel labelBodyColor;
private JLabel labelAdditionalColor;
private JLabel labelPortholes;
public JButton buttonOk;
private JButton buttonCancel;
private JPanel panelObject;
}

View File

@ -0,0 +1,91 @@
import Drawnings.*;
import Entities.EntityAirbus;
import Entities.EntityPlane;
import Generics.AirbusGenericCollection;
import Generics.GenericParametrized;
import MovementStrategy.DrawningObjectAirbus;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Random;
import javax.swing.*;
public class FormGenerationAirbus extends JFrame {
Canvas canvas;
GenericParametrized<EntityAirbus, IDrawningPortholes> generic;
DrawningAirbus _airbus;
private int _width = 800;
private int _height = 500;
JButton buttonGenerate;
FormGenerationAirbus() {
JFrame frame = new JFrame("Генерация аэробусов");
setSize(800,500);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(null);
generic = new GenericParametrized<>(50, 50, _width, _height);
canvas = new FormGenerationAirbus.Canvas();
canvas.setBounds(0 , 0, _width, _height);
buttonGenerate = new JButton("Сгенерировать аэробус");
buttonGenerate.setMargin(new Insets(0, 0, 0, 0));
buttonGenerate.setBounds(600, 20, 170, 25);
add(canvas);
add(buttonGenerate);
setVisible(true);
buttonGenerate.addActionListener(GenerateAirbus);
}
ActionListener GenerateAirbus = new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
Random rand = new Random();
// генерация сущности
EntityAirbus entity;
if (rand.nextBoolean()) {
entity = new EntityAirbus(
rand.nextInt(200) + 100, rand.nextInt(2000) + 1000,
new Color(rand.nextInt(0, 256), rand.nextInt(0, 256), rand.nextInt(0, 256)));
} else {
entity = new EntityPlane(rand.nextInt(200) + 100, rand.nextInt(2000) + 1000,
new Color(rand.nextInt(0, 256), rand.nextInt(0, 256), rand.nextInt(0, 256)),
new Color(rand.nextInt(0, 256), rand.nextInt(0, 256), rand.nextInt(0, 256)),
rand.nextBoolean(), rand.nextBoolean());
}
generic.add(entity);
// генерация иллюминаторов
IDrawningPortholes potholes;
int n = rand.nextInt(3);
if (n == 0)
potholes = new DrawningPortholesCircle();
else if (n == 1)
potholes = new DrawningPortholesHeart();
else
potholes = new DrawningPortholesSquare();
potholes.SetCount(rand.nextInt(1,4)*10);
generic.add(potholes);
// отрисовка
_airbus = generic.randomDrawingObject();
_airbus.SetPosition(100, 100);
canvas.repaint();
}
};
class Canvas extends JComponent {
public Canvas() {}
public void paintComponent(Graphics g) {
super.paintComponents(g);
Graphics2D g2d = (Graphics2D)g;
if (_airbus != null)
_airbus.DrawTransport(g2d);
super.repaint();
}
}
}

View File

@ -0,0 +1,102 @@
package Generics;
import java.awt.*;
import java.awt.image.BufferedImage;
import Drawnings.DrawningAirbus;
import MovementStrategy.IMoveableObject;
public class AirbusGenericCollection<T extends DrawningAirbus, U extends IMoveableObject> {
private int _pictureWidth;
private int _pictureHeight;
private int _placeSizeWidth = 124;
private int _placeSizeHeight = 44;
private SetGeneric<T> _collection;
public AirbusGenericCollection(int picWidth, int picHeight)
{
int width = picWidth / _placeSizeWidth;
int height = picHeight / _placeSizeHeight;
_pictureWidth = picWidth;
_pictureHeight = picHeight;
_collection = new SetGeneric<T>(width * height);
}
// сложение
public int Add(T obj)
{
if (obj == null)
return -1;
return _collection.Insert(obj);
}
// вычитание
public boolean Remove(int pos)
{
if (_collection.Get(pos) == null)
return false;
return _collection.Remove(pos);
}
// получение объекта IMoveableObjecr
public U GetU(int pos)
{
if (_collection.Get(pos) != null)
return (U)_collection.Get(pos).GetMoveableObject();
return null;
}
// получение объекта DrawningAirbus
public T GetT(int pos)
{
if (_collection.Get(pos) != null)
return (T)_collection.GetAirbus().get(pos);
return null;
}
// вывод всего набора
public BufferedImage ShowAirbus()
{
BufferedImage bmp = new BufferedImage(_pictureWidth, _pictureHeight, BufferedImage.TYPE_INT_ARGB);
Graphics2D gr = bmp.createGraphics();
DrawBackground(gr);
DrawObjects(gr);
return bmp;
}
// прорисовка фона
private void DrawBackground(Graphics gr)
{
gr.setColor(Color.BLACK);
for (int i = 0; i < _pictureWidth / _placeSizeWidth; ++i)
{
for (int j = 0; j < _pictureHeight / _placeSizeHeight + 1; ++j)
{
// линия разметки
gr.drawLine(i * _placeSizeWidth, j * _placeSizeHeight, i * _placeSizeWidth + _placeSizeWidth / 2, j * _placeSizeHeight);
gr.drawLine(i * _placeSizeWidth, 0, i * _placeSizeWidth, _pictureHeight / _placeSizeHeight * _placeSizeHeight);
}
}
}
// прорисовка объекта
private void DrawObjects(Graphics2D gr)
{
// координаты
int x = _pictureWidth / _placeSizeWidth - 1;
int y = _pictureHeight / _placeSizeHeight - 1;
for (var _airbus : _collection.GetAirbus())
{
if (_airbus != null) {
if (x < 0)
{
x = _pictureWidth / _placeSizeWidth - 1;
--y;
}
_airbus.SetPosition(_placeSizeWidth * x, _placeSizeHeight * y);
_airbus.DrawTransport(gr);
--x;
}
}
}
}

View File

@ -0,0 +1,52 @@
package Generics;
import Drawnings.DrawningAirbus;
import MovementStrategy.DrawningObjectAirbus;
import java.util.HashMap;
import java.util.List;
public class AirbusGenericStorage {
HashMap <String, AirbusGenericCollection<DrawningAirbus, DrawningObjectAirbus>> _airbusStorages;
public List<String> Keys() {
return _airbusStorages.keySet().stream().toList();
}
private int _pictureWidth;
private int _pictureHeight;
public AirbusGenericStorage(int pictureWidth, int pictureHeight)
{
_airbusStorages = new HashMap<String, AirbusGenericCollection<DrawningAirbus, DrawningObjectAirbus>> ();
_pictureWidth = pictureWidth;
_pictureHeight = pictureHeight;
}
public void AddSet(String name)
{
if (_airbusStorages.containsKey(name))
// уже занят
return;
_airbusStorages.put(name, new AirbusGenericCollection<DrawningAirbus, DrawningObjectAirbus>(_pictureWidth, _pictureHeight));
}
public void DelSet(String name)
{
if (!_airbusStorages.containsKey(name))
return;
_airbusStorages.remove(name);
}
// Доступ к набору
public AirbusGenericCollection<DrawningAirbus, DrawningObjectAirbus> get(String ind)
{
if (_airbusStorages.containsKey(ind))
return _airbusStorages.get(ind);
return null;
}
// вызов удалёнок
public DrawningObjectAirbus get(String iStorage, int iAirbus){
if (!_airbusStorages.containsKey(iStorage))
return null;
return _airbusStorages.get(iStorage).GetU(iAirbus);
}
}

View File

@ -0,0 +1,76 @@
package Generics;
import java.util.ArrayList;
import java.util.Random;
import Entities.*;
import Drawnings.*;
public class GenericParametrized<T extends EntityAirbus, U extends IDrawningPortholes> {
private ArrayList<T> _airbus;
private ArrayList<U> _portholes;
private int CountAirbus;
private int CountPortholes;
private int MaxCountAirbus;
private int MaxCountPortoles;
private int _pictureWidth;
private int _pictureHeight;
public GenericParametrized(int maxCountAirbus, int maxCountPortoles, int pictureWidth, int pictureHeight)
{
MaxCountAirbus = maxCountAirbus;
CountAirbus = 0;
MaxCountPortoles = maxCountPortoles;
CountPortholes = 0;
_pictureWidth = pictureWidth;
_pictureHeight = pictureHeight;
_airbus = new ArrayList<T>();
_portholes = new ArrayList<U>();
}
public boolean add(T airbus)
{
if (airbus == null || CountAirbus >= MaxCountAirbus)
return false;
_airbus.add(airbus);
CountAirbus++;
return true;
}
public boolean add(U porthole)
{
if (porthole == null || CountPortholes >= MaxCountPortoles)
return false;
_portholes.add(porthole);
CountPortholes++;
return true;
}
public DrawningAirbus randomDrawingObject()
{
Random rand = new Random();
if (CountAirbus == 0 || CountPortholes == 0)
return null;
int ar = rand.nextInt(CountAirbus);
int port = rand.nextInt(CountPortholes);
DrawningAirbus drawningAirbus;
if (_airbus.get(ar) instanceof EntityPlane)
drawningAirbus = new DrawningPlane(
_airbus.get(ar).getSpeed(),
_airbus.get(ar).getWeight(),
_airbus.get(ar).getBodyColor(),
_portholes.get(port).getCount(),
((EntityPlane)_airbus.get(ar)).getAdditionalColor(),
((EntityPlane)_airbus.get(ar)).IsCompartment(),
((EntityPlane)_airbus.get(ar)).IsAdditionalEngine(),
_pictureWidth, _pictureHeight);
else
drawningAirbus = new DrawningAirbus(
_airbus.get(ar).getSpeed(),
_airbus.get(ar).getWeight(),
_airbus.get(ar).getBodyColor(),
_portholes.get(port).getCount(),
_pictureWidth, _pictureHeight);
return drawningAirbus;
}
}

View File

@ -0,0 +1,65 @@
package Generics;
import java.util.ArrayList;
import java.util.Iterator;
public class SetGeneric<T extends Object> {
// список объектов
private ArrayList<T> _places;
// кол-во объектов
private int maxCount;
public int Count()
{
return _places.size();
};
public SetGeneric(int count)
{
_places = new ArrayList<>(count);
maxCount = count;
}
// Добавление объекта в набор
public int Insert(T airbus)
{
return Insert(airbus, 0);
}
// Добавление объекта в набор на конкретную позицию
public int Insert(T airbus, int position)
{
if (position < 0 || position >= maxCount || Count() >= maxCount)
{
return -1;
}
_places.add(position, airbus);
return position;
}
// Удаление объекта из набора с конкретной позиции
public boolean Remove(int position)
{
if (position < 0 || position >= Count())
{
return false;
}
_places.remove(position);
return true;
}
// Получение объекта из набора по позиции
public T Get(int position)
{
if (position < 0 || position >= Count())
{
return null;
}
return _places.get(position);
}
public ArrayList<T> GetAirbus()
{
return _places;
}
}

5
src/Main.java Normal file
View File

@ -0,0 +1,5 @@
public class Main {
public static void main(String[] args) {
new FormAirbusCollection();
}
}

View File

@ -0,0 +1,76 @@
package MovementStrategy;
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(Direction.Left); }
protected boolean MoveRight() { return MoveTo(Direction.Right); }
protected boolean MoveUp() { return MoveTo(Direction.Up); }
protected boolean MoveDown() { return MoveTo(Direction.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(Direction directionType)
{
if (_state != Status.InProgress)
{
return false;
}
if (_moveableObject.CheckCanMove(directionType))
{
_moveableObject.MoveObject(directionType);
return true;
}
return false;
}
}

View File

@ -0,0 +1,7 @@
package MovementStrategy;
public enum Direction {
Up,
Down,
Left,
Right;
}

View File

@ -0,0 +1,24 @@
package MovementStrategy;
import Drawnings.*;
public class DrawningObjectAirbus implements IMoveableObject {
private DrawningAirbus _drawningAirbus = null;
public DrawningObjectAirbus(DrawningAirbus drawningAirbus)
{
_drawningAirbus = drawningAirbus;
}
public ObjectParameters GetObjectPosition()
{
if (_drawningAirbus == null || _drawningAirbus.entityAirbus == null)
{
return null;
}
return new ObjectParameters(_drawningAirbus.GetPosX(), _drawningAirbus.GetPosY(), _drawningAirbus.GetWidth(), _drawningAirbus.GetHeight());
}
public int GetStep() { return (int)_drawningAirbus.entityAirbus.Step; }
public boolean CheckCanMove(Direction direction) { return _drawningAirbus.CanMove(direction); }
public void MoveObject(Direction direction) { _drawningAirbus.MoveTransport(direction); }
}

View File

@ -0,0 +1,8 @@
package MovementStrategy;
public interface IMoveableObject {
ObjectParameters GetObjectPosition();
int GetStep();
boolean CheckCanMove(Direction direction);
void MoveObject(Direction direction);
}

View File

@ -0,0 +1,53 @@
package MovementStrategy;
public class MoveToBorder extends AbstractStrategy {
@Override
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;
}
// движение к цели
@Override
protected void MoveToTarget()
{
var objParams = GetObjectParameters();
if (objParams == null)
{
return;
}
var diffX = FieldWidth;
if (Math.abs(diffX) > GetStep())
{
if (diffX < 0)
{
MoveLeft();
}
else
{
MoveRight();
}
}
var diffY = FieldHeight;
if (Math.abs(diffY) > GetStep())
{
if (diffY < 0)
{
MoveUp();
}
else
{
MoveDown();
}
}
}
}

View File

@ -0,0 +1,53 @@
package MovementStrategy;
public class MoveToCenter extends AbstractStrategy {
@Override
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;
}
// движение к цели
@Override
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,25 @@
package MovementStrategy;
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,7 @@
package MovementStrategy;
public enum Status {
NotInit,
InProgress,
Finish
}