laba3 Кувшинов Тимур Александрович ПИбд-21 Сложная #4

Closed
TImourka wants to merge 5 commits from laba3 into laba2
9 changed files with 561 additions and 23 deletions

View File

@ -26,6 +26,12 @@ public class DrawingLoco extends DrawingTrain{
EntityTrain = new EntityLoco(speed, weight, bodyColor, _numWheel, additionalColor, tube, fuelTank, locoLine);
_locoWidth = ((EntityLoco)EntityTrain).FuelTank ? 169 : 83;
}
// конструктор для 3 сложной лабы
public DrawingLoco(EntityLoco train, IWheelDrawing _wheelDrawing, int width, int height ){
super(train, _wheelDrawing, width, height);
if (height < _locoHeight || width < _locoWidth)
return;
}
/// <summary>
/// Установка позиции
/// </summary>

View File

@ -7,6 +7,8 @@ import javax.swing.Timer;
import java.awt.event.*;
public class DrawingTrain {
public IMoveableObject GetMoveableObject() { return new DrawningObjectTrain(this);}
protected IWheelDrawing wheelDrawing;
/// <summary>
/// Класс-сущность
@ -68,6 +70,16 @@ public class DrawingTrain {
}
wheelDrawing.setNumWheel(_numWheel);
}
// конструктор для 3 сложной лабы
public DrawingTrain(EntityTrain train, IWheelDrawing _wheelDrawing, int width, int height ){
if (height < _locoHeight || width < _locoWidth)
return;
_pictureWidth = width;
_pictureHeight = height;
EntityTrain = train;
wheelDrawing = _wheelDrawing;
wheelDrawing.setNumWheel(EntityTrain.numWheel);
}
/// <summary>
/// Установка позиции
/// </summary>

View File

@ -0,0 +1,62 @@
package laba1Loco;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JFrame;
public class Form4GenericDopClass extends JFrame {
static int pictureBoxWidth = 980;
static int pictureBoxHeight = 560;
public DrawingTrain _drawingTrain;
private class Canvas extends JComponent{
public Canvas(){
}
public void paintComponent (Graphics g){
if (_drawingTrain == null){
return;
}
super.paintComponents (g) ;
Graphics2D g2d = (Graphics2D)g;
_drawingTrain.SetPosition(50, 50);
_drawingTrain.DrawTransport(g2d);
super.repaint();
}
}
GenericDopClass<EntityTrain, IWheelDrawing> genericDopClass;
public Form4GenericDopClass(){
_drawingTrain = null;
Canvas canv = new Canvas();
setSize (1000, 600);
setLayout(null);
canv.setBounds(0,0,pictureBoxWidth, pictureBoxHeight);
genericDopClass = new GenericDopClass<>(100, 100, pictureBoxWidth, pictureBoxHeight);
genericDopClass.addTrain(new EntityTrain(100, 100, Color.BLUE, 2));
genericDopClass.addTrain(new EntityTrain(100, 100, Color.RED, 3));
genericDopClass.addTrain(new EntityTrain(100, 100, Color.GRAY, 4));
genericDopClass.addTrain(new EntityLoco(100, 100, Color.BLUE, 2, Color.ORANGE, true, true, true));
genericDopClass.addWheel(new WheelDrawingDavidStar());
genericDopClass.addWheel(new WheelDrawingBalls());
JButton creatButton = new JButton("createButton");
creatButton.addActionListener(
new ActionListener() {
public void actionPerformed(ActionEvent e){
_drawingTrain = genericDopClass.getRDrawingObject();
canv.repaint();
}
}
);
creatButton.setBounds(pictureBoxWidth/2, pictureBoxHeight-20, 120, 20);
add(canv);
add(creatButton);
setVisible(true);
}
}

View File

@ -7,22 +7,43 @@ import javax.swing.Timer;
import java.awt.event.*;
public class FormTrain{
private DrawingTrain _drawingTrain;
private class Canvas extends JComponent{
public DrawingTrain _drawingTrain;
public Canvas(){
}
public void paintComponent (Graphics g){
if (_drawingTrain == null){
return;
}
super.paintComponents (g) ;
Graphics2D g2d = (Graphics2D)g;
_drawingTrain.DrawTransport(g2d);
super.repaint();
}
}
public DrawingTrain SelectedTrain;
public boolean DialogResult = false;
public DrawingTrain _drawingTrain;
private AbstractStrategy abstractStrategy;
Canvas canv;
static int pictureBoxWidth = 980;
static int pictureBoxHeight = 580;
public JButton buttonSelectTrain;
public JFrame w;
public void Draw(){
canv.repaint();
}
public FormTrain(){
JFrame w=new JFrame ("Loco");
SelectedTrain = null;
w = new JFrame ("Loco");
JButton buttonCreate = new JButton("create");
JButton buttonCreateLocomotive = new JButton("createLocomotive");
JButton buttonCreateLocomotive = new JButton("create locomotive");
JButton buttonStrategysStep = new JButton("strategys step");
JComboBox comboBoxStrategy = new JComboBox(
buttonSelectTrain = new JButton("select train");
JComboBox<String> comboBoxStrategy = new JComboBox<String>(
new String[]{
"к центру",
"к краю",
@ -51,6 +72,7 @@ public class FormTrain{
right.setContentAreaFilled(false);
right.setName("right");
right.setIcon(new ImageIcon("D:\\Coffee\\PIbd-21_Kouvshinoff_T._A._WarmlyLocomotive._Harder\\laba1Loco\\images\\arowR340x259.png"));
buttonStrategysStep.addActionListener(
new ActionListener() {
public void actionPerformed(ActionEvent e){
@ -100,12 +122,26 @@ public class FormTrain{
public void actionPerformed(ActionEvent e){
System.out.println(e.getActionCommand());
Random random = new Random();
Color color = new Color(random.nextInt(0, 256), random.nextInt(0, 256), random.nextInt(0, 256));
// Вызываем диалоговое окно выбора цвета
Color selectedColor = JColorChooser.showDialog(w, "Выберите цвет", Color.WHITE);
if (selectedColor != null)
{
color = selectedColor;
}
Color color2 = new Color(random.nextInt(0, 256), random.nextInt(0, 256), random.nextInt(0, 256));
// Вызываем диалоговое окно выбора цвета
selectedColor = JColorChooser.showDialog(w, "Выберите цвет", Color.WHITE);
if (selectedColor != null)
{
color2 = selectedColor;
}
_drawingTrain = new DrawingLoco(
random.nextInt(100, 300),
random.nextInt(1000, 3000),
new Color(random.nextInt(0, 256), random.nextInt(0, 256), random.nextInt(0, 256)),
color,
random.nextInt(2, 5),
new Color(random.nextInt(0, 256), random.nextInt(0, 256), random.nextInt(0, 256)),
color2,
random.nextInt(0, 2) == 1,
random.nextInt(0, 2) == 1,
random.nextInt(0, 2) == 1,
@ -122,10 +158,17 @@ public class FormTrain{
public void actionPerformed(ActionEvent e){
System.out.println(e.getActionCommand());
Random random = new Random();
Color color = new Color(random.nextInt(0, 256), random.nextInt(0, 256), random.nextInt(0, 256));
// Вызываем диалоговое окно выбора цвета
Color selectedColor = JColorChooser.showDialog(w, "Выберите цвет", Color.WHITE);
if (selectedColor != null)
{
color = selectedColor;
}
_drawingTrain = new DrawingTrain(
random.nextInt(100, 300),
random.nextInt(1000, 3000),
new Color(random.nextInt(0, 256), random.nextInt(0, 256), random.nextInt(0, 256)),
color,
random.nextInt(2, 5),
pictureBoxWidth,
pictureBoxHeight);
@ -165,7 +208,6 @@ public class FormTrain{
right.addActionListener(actioListener);
w.setSize (1000, 600);
w.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
w.setLayout(null);
canv = new Canvas();
canv.setBounds(0, 0, pictureBoxWidth, pictureBoxHeight);
@ -177,6 +219,8 @@ public class FormTrain{
right.setBounds(940, 520, 40, 40);
comboBoxStrategy.setBounds(pictureBoxWidth - 150, 20, 150, 20);
buttonStrategysStep.setBounds(pictureBoxWidth - 150, 45, 150, 20);
buttonSelectTrain.setBounds(pictureBoxWidth/2, 540, 150, 20);
w.add(buttonSelectTrain);
w.add(canv);
w.add(buttonCreate);
w.add(buttonCreateLocomotive);
@ -186,19 +230,6 @@ public class FormTrain{
w.add(right);
w.add(comboBoxStrategy);
w.add(buttonStrategysStep);
}
}
class Canvas extends JComponent{
public DrawingTrain _drawingTrain;
public Canvas(){
}
public void paintComponent (Graphics g){
if (_drawingTrain == null){
return;
}
super.paintComponents (g) ;
Graphics2D g2d = (Graphics2D)g;
_drawingTrain.DrawTransport(g2d);
super.repaint();
w.setVisible(true);
}
}

View File

@ -0,0 +1,141 @@
package laba1Loco;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JTextField;
public class FormTrainCollecltion {
private class Canvas extends JComponent{
public TrainsGenericCollection<DrawingTrain, DrawningObjectTrain> _trains;
public Canvas(){
}
public void paintComponent (Graphics g){
super.paintComponent(g);
if (_trains.ShowTrains() != null) {
g.drawImage(_trains.ShowTrains(), 0, 0, this);
}
super.repaint();
}
}
Canvas canv;
static int pictureBoxWidth = 860;
static int pictureBoxHeight = 580;
private TrainsGenericCollection<DrawingTrain, DrawningObjectTrain> _trains;
public void Draw(){
canv.repaint();
}
FormTrainCollecltion(){
canv = new Canvas();
JFrame w = new JFrame ("TrainCollecltion");
_trains = new TrainsGenericCollection<DrawingTrain, DrawningObjectTrain>(pictureBoxWidth, pictureBoxHeight);
canv._trains = _trains;
JButton ButtonAddTrain = new JButton("ButtonAddTrain");
ButtonAddTrain.addActionListener(
new ActionListener() {
public void actionPerformed(ActionEvent e){
FormTrain form = new FormTrain();
form.buttonSelectTrain.addActionListener(
new ActionListener() {
public void actionPerformed(ActionEvent e){
if (_trains.Add(form._drawingTrain) != -1)
{
JOptionPane.showMessageDialog(null, "Объект добавлен", "Информация", JOptionPane.INFORMATION_MESSAGE);
System.out.println("Объект добавлен");
Draw();
}
else
{
JOptionPane.showMessageDialog(null, "Не удалось добавить объект", "Информация", JOptionPane.INFORMATION_MESSAGE);
System.out.println("Не удалось добавить объект");
}
form.w.dispose();
}
}
);
}
}
);
JTextField TextBoxNumber = new JTextField();
JButton ButtonRemoveTrain = new JButton("ButtonRemoveTrain");
ButtonRemoveTrain.addActionListener(
new ActionListener() {
public void actionPerformed(ActionEvent e){
if (JOptionPane.showConfirmDialog(null, "Удалить объект?", "Удаление", JOptionPane.YES_NO_OPTION) == JOptionPane.NO_OPTION)
{
return;
}
for (char it : TextBoxNumber.getText().toCharArray())
if (it < '0' || it > '9')
{
JOptionPane.showMessageDialog(null, "Не удалось удалить объект", "Информация", JOptionPane.INFORMATION_MESSAGE);
System.out.println("Не удалось удалить объект");
return;
}
if (TextBoxNumber.getText().length() == 0)
{
JOptionPane.showMessageDialog(null, "Не удалось удалить объект", "Информация", JOptionPane.INFORMATION_MESSAGE);
System.out.println("Не удалось удалить объект");
return;
}
int pos = Integer.parseInt(TextBoxNumber.getText());
if (_trains.remove(pos) != null)
{
JOptionPane.showMessageDialog(null, "Объект удален", "Информация", JOptionPane.INFORMATION_MESSAGE);
System.out.println("Объект удален");
Draw();
}
else
{
JOptionPane.showMessageDialog(null, "Не удалось удалить объект", "Информация", JOptionPane.INFORMATION_MESSAGE);
System.out.println("Не удалось удалить объект");
}
}
}
);
JButton ButtonRefreshCollection = new JButton("ButtonRefreshCollection");
ButtonRefreshCollection.addActionListener(
new ActionListener() {
public void actionPerformed(ActionEvent e){
Draw();
}
}
);
JButton toForm4GenericDopClass = new JButton("ToForm4GenericDopClass");
toForm4GenericDopClass.addActionListener(
new ActionListener() {
public void actionPerformed(ActionEvent e){
Form4GenericDopClass form4GenericDopClass = new Form4GenericDopClass();
}
}
);
w.setSize (1000, 600);
w.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
w.setLayout(null);
canv.setBounds(0, 0, pictureBoxWidth, pictureBoxHeight);
ButtonAddTrain.setBounds(pictureBoxWidth, 0, 120, 20);
TextBoxNumber.setBounds(pictureBoxWidth, 30, 120, 20);
ButtonRemoveTrain.setBounds(pictureBoxWidth, 60, 120, 20);
ButtonRefreshCollection.setBounds(pictureBoxWidth, 90, 120, 20);
toForm4GenericDopClass.setBounds(pictureBoxWidth, 120, 120, 20);
w.add(canv);
w.add(ButtonAddTrain);
w.add(ButtonRemoveTrain);
w.add(ButtonRefreshCollection);
w.add(TextBoxNumber);
w.add(toForm4GenericDopClass);
w.setVisible(true);
}
}

View File

@ -0,0 +1,68 @@
package laba1Loco;
import java.util.ArrayList;
import java.util.Random;
public class GenericDopClass<T extends EntityTrain, U extends IWheelDrawing> {
private ArrayList<T> Trains;
private ArrayList<U> Wheels;
private int maxCountTrains;
private int countTrains;
private int maxCountWheels;
private int countWheels;
private Random random;
/// <summary>
/// Ширина окна
/// </summary>
private int _pictureWidth;
/// <summary>
/// Высота окна
/// </summary>
private int _pictureHeight;
public GenericDopClass(int _maxCountTrains, int _maxCountWheels, int pictureWidth, int pictureHeight){
maxCountTrains = _maxCountTrains;
maxCountWheels = _maxCountWheels;
Trains = new ArrayList<T>(maxCountTrains);
Wheels = new ArrayList<U>(maxCountWheels);
countTrains = 0;
countWheels = 0;
_pictureWidth = pictureWidth;
_pictureHeight = pictureHeight;
random = new Random();
}
public boolean addTrain(T train){
Review

Методы добавления должны быть полиморфными

Методы добавления должны быть полиморфными
if (train == null)
return false;
if (countTrains > maxCountTrains)
return false;
Trains.add(countTrains++, train);
return true;
}
public boolean addWheel(U wheel){
Review

Методы добавления должны быть полиморфными

Методы добавления должны быть полиморфными
if (wheel == null)
return false;
if (countWheels > maxCountWheels)
return false;
Wheels.add(countWheels++, wheel);
return true;
}
public DrawingTrain getRDrawingObject(){
if (countTrains == 0 || countWheels == 0)
return null;
int i = random.nextInt(countTrains);
int j = random.nextInt(countWheels);
DrawingTrain drawingTrain;
if (Trains.get(i) instanceof EntityLoco){
drawingTrain = new DrawingLoco((EntityLoco)Trains.get(i), Wheels.get(j), _pictureWidth, _pictureHeight);
}
else{
drawingTrain = new DrawingTrain(Trains.get(i), Wheels.get(j), _pictureWidth, _pictureHeight);
}
return drawingTrain;
}
}

View File

@ -2,6 +2,6 @@ package laba1Loco;
public class Main{
public static void main(String[] args) {
FormTrain formTrain = new FormTrain();
FormTrainCollecltion formTrainCollecltion = new FormTrainCollecltion();
}
}

90
laba1Loco/SetGeneric.java Normal file
View File

@ -0,0 +1,90 @@
package laba1Loco;
public class SetGeneric<T extends Object> {
/// <summary>
/// Массив объектов, которые храним
/// </summary>
private Object[] _places;
/// <summary>
/// Количество объектов в массиве
/// </summary>
public int Count;
/// <summary>
/// Конструктор
/// </summary>
/// <param name="count"></param>
public SetGeneric(int count)
{
_places = new Object[count];
Count = _places.length;
}
/// <summary>
/// Добавление объекта в набор
/// </summary>
/// <param name="train">Добавляемый поезд</param>
/// <returns></returns>
public int Insert(T train)
{
int i = 0;
for (;i < _places.length; i++)
{
if (_places[i] == null)
break;
}
if (i == _places.length)
return -1;
for (; i > 0; i--)
{
_places[i] = _places[i - 1];
}
_places[i] = train;
return i;
}
/// <summary>
/// Добавление объекта в набор на конкретную позицию
/// </summary>
/// <param name="train">Добавляемый поезд</param>
/// <param name="position">Позиция</param>
/// <returns></returns>
public boolean Insert(T train, int position)
{
if (position < 0 || position >= _places.length)
return false;
for (; position < _places.length; position++)
{
if (_places[position] == null)
break;
}
if (position == _places.length)
return false;
for (; position > 0; position--)
{
_places[position] = _places[position - 1];
}
_places[position] = train;
return true;
}
/// <summary>
/// Удаление объекта из набора с конкретной позиции
/// </summary>
/// <param name="position"></param>
/// <returns></returns>
public boolean Remove(int position)
{
if (position < 0 || position >= _places.length)
return false;
_places[position] = null;
return true;
}
/// <summary>
/// Получение объекта из набора по позиции
/// </summary>
/// <param name="position"></param>
/// <returns></returns>
public T Get(int position)
{
if (position < 0 || position >= _places.length)
return null;
return (T)_places[position];
}
}

View File

@ -0,0 +1,128 @@
package laba1Loco;
import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
public class TrainsGenericCollection<T extends DrawingTrain, U extends IMoveableObject>{
/// <summary>
/// Ширина окна прорисовки
/// </summary>
private int _pictureWidth;
/// <summary>
/// Высота окна прорисовки
/// </summary>
private int _pictureHeight;
/// <summary>
/// Размер занимаемого объектом места (ширина)
/// </summary>
private int _placeSizeWidth = 210;
/// <summary>
/// Размер занимаемого объектом места (высота)
/// </summary>
private int _placeSizeHeight = 90;
/// <summary>
/// Набор объектов
/// </summary>
private SetGeneric<T> _collection;
/// <summary>
/// Конструктор
/// </summary>
/// <param name="picWidth"></param>
/// <param name="picHeight"></param>
public TrainsGenericCollection(int picWidth, int picHeight)
{
int width = picWidth / _placeSizeWidth;
int height = picHeight / _placeSizeHeight;
_pictureWidth = picWidth;
_pictureHeight = picHeight;
_collection = new SetGeneric<T>(width * height);
}
/// <summary>
/// Перегрузка оператора сложения
/// </summary>
/// <param name="collect"></param>
/// <param name="obj"></param>
/// <returns></returns>
public int Add(T obj)
{
if (obj == null)
{
return -1;
}
return _collection.Insert(obj);
}
/// <summary>
/// Перегрузка оператора вычитания
/// </summary>
/// <param name="collect"></param>
/// <param name="pos"></param>
/// <returns></returns>
public T remove(int pos)
{
T obj = _collection.Get(pos);
if (obj != null)
{
_collection.Remove(pos);
}
return obj;
}
/// <summary>
/// Получение объекта IMoveableObject
/// </summary>
/// <param name="pos"></param>
/// <returns></returns>
public U GetU(int pos)
{
return (U)_collection.Get(pos).GetMoveableObject();
}
/// <summary>
/// Вывод всего набора объектов
/// </summary>
/// <returns></returns>
public BufferedImage ShowTrains()
{
BufferedImage bmp = new BufferedImage(_pictureWidth, _pictureHeight, BufferedImage.TYPE_INT_ARGB);
Graphics2D g = bmp.createGraphics();
DrawBackground(g);
DrawObjects(g);
g.dispose();
return bmp;
}
/// <summary>
/// Метод отрисовки фона
/// </summary>
/// <param name="g"></param>
private void DrawBackground(Graphics2D g)
{
g.setColor(Color.BLACK);
for (int i = 0; i < _pictureWidth / _placeSizeWidth; i++)
{
for (int j = 0; j < _pictureHeight / _placeSizeHeight + 1; ++j)
{//линия рамзетки места
g.drawLine( i * _placeSizeWidth, j * _placeSizeHeight, i * _placeSizeWidth + _placeSizeWidth / 2, j * _placeSizeHeight);
}
g.drawLine( i * _placeSizeWidth, 0, i * _placeSizeWidth, _pictureHeight / _placeSizeHeight * _placeSizeHeight);
}
}
/// <summary>
/// Метод прорисовки объектов
/// </summary>
/// <param name="g"></param>
private void DrawObjects(Graphics2D g)
{
for (int i = 0; i < _collection.Count; i++)
{
T t = _collection.Get(i);
if (t != null)
{
t.SetPosition((i % (_pictureWidth / _placeSizeWidth)) * _placeSizeWidth, (i / (_pictureWidth / _placeSizeWidth)) * _placeSizeHeight);
if (t instanceof DrawingLoco)
((DrawingLoco) t).DrawTransport(g);
else
t.DrawTransport(g);
}
}
}
}