Готовая 4 усложненная лабораторная

This commit is contained in:
Даниил Путинцев 2023-12-01 17:00:41 +04:00
parent 6f7f3302c1
commit cd6ed62547
5 changed files with 242 additions and 65 deletions

View File

@ -5,19 +5,30 @@ import RoadTrain.Generics.*;
import RoadTrain.DrawingObjects.*; import RoadTrain.DrawingObjects.*;
import javax.swing.*; import javax.swing.*;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import java.awt.*; import java.awt.*;
import java.awt.event.ActionEvent; import java.awt.event.ActionEvent;
import java.awt.event.ActionListener; import java.awt.event.ActionListener;
import java.util.*;
public class FormTruckCollection { public class FormTruckCollection {
private class Canvas extends JComponent { private class Canvas extends JComponent {
public TrucksGenericCollection<DrawingTruck, DrawingObjectTruck> _truck;
public Canvas() { public Canvas() {
} }
public void paintComponent (Graphics g) { public void paintComponent (Graphics g) {
super.paintComponent(g); super.paintComponent(g);
if (_truck.ShowTrucks() != null) { if (jListStorage.getSelectedIndex() == -1)
g.drawImage(_truck.ShowTrucks(), 0, 10, this); {
return;
}
var obj = _storage.get(jListStorage.getSelectedValue());
if (obj == null)
{
return;
}
if (obj.ShowTrucks() != null) {
g.drawImage(obj.ShowTrucks(), 0, 0, this);
} }
super.repaint(); super.repaint();
} }
@ -25,26 +36,55 @@ public class FormTruckCollection {
Canvas canv; Canvas canv;
static int pictureBoxWidth = 700; static int pictureBoxWidth = 700;
static int pictureBoxHeight = 480; static int pictureBoxHeight = 480;
private TrucksGenericCollection<DrawingTruck, DrawingObjectTruck> _truck; private TrucksGenericStorage _storage;
public void Draw(){ public void Draw(){
canv.repaint(); canv.repaint();
} }
private Stack<DrawingTruck> StackRemoved;
private JList<String> jListStorage;
private DefaultListModel<String> listModel;
private void ReloadObjects()
{
int index = jListStorage.getSelectedIndex();
listModel.clear();
for (String key : _storage.Keys()) {
listModel.addElement(key);
}
if (listModel.size() > 0 && (index == -1 || index >= listModel.size()))
{
jListStorage.setSelectedIndex(0);
}
else if (listModel.size() > 0 && index > -1 && index < listModel.size())
{
jListStorage.setSelectedIndex(index);
}
}
FormTruckCollection() { FormTruckCollection() {
listModel = new DefaultListModel<String>();
jListStorage = new JList<String>(listModel);
canv = new Canvas(); canv = new Canvas();
JFrame Frame = new JFrame ("TrucksCollecltion"); JFrame Frame = new JFrame ("TrucksCollection");
_truck = new TrucksGenericCollection<DrawingTruck, DrawingObjectTruck>(pictureBoxWidth, pictureBoxHeight); _storage = new TrucksGenericStorage(pictureBoxWidth, pictureBoxHeight);
canv._truck = _truck;
JButton ButtonAddTruck = new JButton("Добавить технику"); JButton ButtonAddTruck = new JButton("Добавить технику");
ButtonAddTruck.addActionListener( ButtonAddTruck.addActionListener(
new ActionListener() { new ActionListener() {
public void actionPerformed(ActionEvent e) { public void actionPerformed(ActionEvent e) {
if (jListStorage.getSelectedIndex() == -1)
{
return;
}
var obj = _storage.get(jListStorage.getSelectedValue());
if (obj == null)
{
return;
}
RoadTrainForm form = new RoadTrainForm(); RoadTrainForm form = new RoadTrainForm();
form.buttonSelectTruck.addActionListener( form.buttonSelectTruck.addActionListener(
new ActionListener() { new ActionListener() {
public void actionPerformed(ActionEvent e) { public void actionPerformed(ActionEvent e) {
if (_truck.Add(form._drawingTruck) != -1) { if (obj.Add(form._drawingTruck) != -1) {
JOptionPane.showMessageDialog(null, "Объект добавлен", "Информация", JOptionPane.INFORMATION_MESSAGE); JOptionPane.showMessageDialog(null, "Объект добавлен", "Информация", JOptionPane.INFORMATION_MESSAGE);
Draw(); Draw();
} else { } else {
@ -57,12 +97,22 @@ public class FormTruckCollection {
} }
} }
); );
StackRemoved = new Stack<DrawingTruck>();
JTextField TextBoxNumber = new JTextField(); JTextField TextBoxNumber = new JTextField();
JButton ButtonRemoveTruck = new JButton("Удалить технику"); JButton ButtonRemoveTruck = new JButton("Удалить технику");
ButtonRemoveTruck.addActionListener( ButtonRemoveTruck.addActionListener(
new ActionListener() { new ActionListener() {
public void actionPerformed(ActionEvent e) { public void actionPerformed(ActionEvent e) {
if (jListStorage.getSelectedIndex() == -1)
{
return;
}
var obj = _storage.get(jListStorage.getSelectedValue());
if (obj == null)
{
return;
}
if (JOptionPane.showConfirmDialog(null, "Удалить объект?", "Удаление", JOptionPane.YES_NO_OPTION) == JOptionPane.NO_OPTION) { if (JOptionPane.showConfirmDialog(null, "Удалить объект?", "Удаление", JOptionPane.YES_NO_OPTION) == JOptionPane.NO_OPTION) {
return; return;
} }
@ -75,9 +125,11 @@ public class FormTruckCollection {
JOptionPane.showMessageDialog(null, "Не удалось удалить объект", "Информация", JOptionPane.INFORMATION_MESSAGE); JOptionPane.showMessageDialog(null, "Не удалось удалить объект", "Информация", JOptionPane.INFORMATION_MESSAGE);
return; return;
} }
int pos = Integer.parseInt(TextBoxNumber.getText()); int pos = Integer.parseInt(TextBoxNumber.getText());
if (_truck.remove(pos) != null) { var removed = obj.remove(pos);
if (removed != null)
{
StackRemoved.push(removed);
JOptionPane.showMessageDialog(null, "Объект удален", "Информация", JOptionPane.INFORMATION_MESSAGE); JOptionPane.showMessageDialog(null, "Объект удален", "Информация", JOptionPane.INFORMATION_MESSAGE);
Draw(); Draw();
} else { } else {
@ -87,6 +139,20 @@ public class FormTruckCollection {
} }
); );
JButton buttonGetRemoved = new JButton("Вернуть удаленные");
buttonGetRemoved.addActionListener(
new ActionListener() {
public void actionPerformed(ActionEvent e){
if (StackRemoved.size()==0){
JOptionPane.showMessageDialog(null, "Нет удалённых", "Информация", JOptionPane.INFORMATION_MESSAGE);
return;
}
RoadTrainForm form = new RoadTrainForm();
form._drawingTruck = StackRemoved.pop();
form.Draw();
}
}
);
JButton ButtonRefreshCollection = new JButton("Обновить коллекцию"); JButton ButtonRefreshCollection = new JButton("Обновить коллекцию");
ButtonRefreshCollection.addActionListener( ButtonRefreshCollection.addActionListener(
new ActionListener() { new ActionListener() {
@ -104,22 +170,76 @@ public class FormTruckCollection {
} }
} }
); );
JTextField textBoxSetName = new JTextField();
JButton buttonAddSet = new JButton("Добавить набор");
buttonAddSet.addActionListener(
new ActionListener() {
public void actionPerformed(ActionEvent e){
if (textBoxSetName.getText().length() == 0)
{
JOptionPane.showMessageDialog(null, "Не все данные заполнены", "Информация", JOptionPane.INFORMATION_MESSAGE);
System.out.println("Не все данные заполнены");
return;
}
_storage.AddSet(textBoxSetName.getText());
ReloadObjects();
}
}
);
jListStorage.addListSelectionListener(
new ListSelectionListener() {
public void valueChanged(ListSelectionEvent e){
Draw();
}
}
);
JButton buttonRemoveSet = new JButton("Убрать набор");
buttonRemoveSet.addActionListener(
new ActionListener() {
public void actionPerformed(ActionEvent e){
if (jListStorage.getSelectedIndex() == -1)
{
return;
}
if (JOptionPane.showConfirmDialog(null, "Удалить объект " + jListStorage.getSelectedValue() + "?", "Удаление", JOptionPane.YES_NO_OPTION) == JOptionPane.NO_OPTION)
{
return;
}
_storage.DelSet(jListStorage.getSelectedValue());
ReloadObjects();
}
}
);
Frame.setSize (880, 520); Frame.setSize (880, 520);
Frame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE); Frame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
Frame.setLayout(null); Frame.setLayout(null);
canv.setBounds(0, 0, pictureBoxWidth, pictureBoxHeight); canv.setBounds(0, 0, pictureBoxWidth, pictureBoxHeight);
ButtonAddTruck.setBounds(pictureBoxWidth - 50, 10, 170, 30); ButtonAddTruck.setBounds(pictureBoxWidth, 0, 160, 20);
TextBoxNumber.setBounds(pictureBoxWidth - 50, 50, 170, 20); TextBoxNumber.setBounds(pictureBoxWidth, 30, 160, 20);
ButtonRemoveTruck.setBounds(pictureBoxWidth - 50, 80, 170, 30); ButtonRemoveTruck.setBounds(pictureBoxWidth, 60, 160, 20);
ButtonRefreshCollection.setBounds(pictureBoxWidth - 50, 120, 170, 30); ButtonRefreshCollection.setBounds(pictureBoxWidth, 90, 160, 20);
FormTruckGenerate.setBounds(pictureBoxWidth - 50, 160, 170, 30); FormTruckGenerate.setBounds(pictureBoxWidth, 120, 160, 20);
buttonAddSet.setBounds(pictureBoxWidth, 150, 160, 20);
textBoxSetName.setBounds(pictureBoxWidth, 180, 160, 20);
jListStorage.setBounds(pictureBoxWidth, 210, 160, 80);
buttonRemoveSet.setBounds(pictureBoxWidth, 300, 160, 20);
buttonGetRemoved.setBounds(pictureBoxWidth, 330, 160, 20);
Frame.add(canv); Frame.add(canv);
Frame.add(ButtonAddTruck); Frame.add(ButtonAddTruck);
Frame.add(ButtonRemoveTruck); Frame.add(ButtonRemoveTruck);
Frame.add(ButtonRefreshCollection); Frame.add(ButtonRefreshCollection);
Frame.add(TextBoxNumber); Frame.add(TextBoxNumber);
Frame.add(FormTruckGenerate); Frame.add(FormTruckGenerate);
Frame.add(buttonAddSet);
Frame.add(textBoxSetName);
Frame.add(jListStorage);
Frame.add(buttonRemoveSet);
Frame.add(buttonGetRemoved);
Frame.setVisible(true); Frame.setVisible(true);
} }
} }

View File

@ -1,63 +1,77 @@
package RoadTrain.Generics; package RoadTrain.Generics;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.NoSuchElementException;
public class SetGeneric<T extends Object> { public class SetGeneric<T extends Object> {
// Массив объектов, которые храним private ArrayList<T> _places;
private Object[] _places; public int Count() {
return _places.size();
// Количество объектов в массиве }
public int Count; private int _maxCount;
// Конструктор
public SetGeneric(int count) { public SetGeneric(int count) {
_places = new Object[count]; _maxCount = count;
Count = _places.length; _places = new ArrayList<T>(count);
} }
public int Insert(T train) {
// Добавление объекта в набор if (_places.size() >= _maxCount)
public int Insert(T truck) {
int i = 0;
for (; i < _places.length; i++) {
if (_places[i] == null)
break;
}
if (i == _places.length)
return -1; return -1;
for (; i > 0; i--) { _places.add(0, train);
_places[i] = _places[i - 1]; return 0;
}
_places[i] = truck;
return i;
} }
public boolean Insert(T train, int position) {
if (_places.size() >= _maxCount)
return false;
// Добавление объекта в набор на конкретную позицию if (position < 0 || position > _places.size())
public boolean Insert(T truck, int position) {
if (position < 0 || position >= _places.length)
return false; return false;
for (; position < _places.length; position++) {
if (_places[position] == null) if (position == _places.size())
break; _places.add(train);
} else
if (position == _places.length) _places.add(position, train);
return false;
for (; position > 0; position--) {
_places[position] = _places[position - 1];
}
_places[position] = truck;
return true; return true;
} }
// Удаление объекта из набора с конкретной позиции
public boolean Remove(int position) { public boolean Remove(int position) {
if (position < 0 || position >= _places.length) if (position < 0 || position >= _places.size())
return false; return false;
_places[position] = null; _places.remove(position);
return true; return true;
} }
// Получение объекта из набора по позиции
public T Get(int position) { public T Get(int position) {
if (position < 0 || position >= _places.length) if (position < 0 || position >= _places.size())
return null; return null;
return (T) _places[position]; return _places.get(position);
}
public Iterable<T> GetTrucks(final Integer maxTrains) {
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 < _places.size() && (maxTrains == null || count < maxTrains);
}
@Override
public T next() {
if (hasNext()) {
count++;
return _places.get(currentIndex++);
}
throw new NoSuchElementException();
}
@Override
public void remove() {
throw new UnsupportedOperationException();
}
};
}
};
} }
} }

View File

@ -71,8 +71,9 @@ public class TrucksGenericCollection<T extends DrawingTruck, U extends IMoveable
} }
private void DrawObjects(Graphics g) { private void DrawObjects(Graphics g) {
for (int i = 0; i < _collection.Count; i++) { int i = 0;
T t = _collection.Get(i); for (T t : _collection.GetTrucks(100))
{
if (t != null) { if (t != null) {
t.SetPosition((i % (_pictureWidth / _placeSizeWidth)) * _placeSizeWidth, (i / (_pictureWidth / _placeSizeWidth)) * _placeSizeHeight); t.SetPosition((i % (_pictureWidth / _placeSizeWidth)) * _placeSizeWidth, (i / (_pictureWidth / _placeSizeWidth)) * _placeSizeHeight);
if (t instanceof DrawingRoadTrain) if (t instanceof DrawingRoadTrain)
@ -80,6 +81,7 @@ public class TrucksGenericCollection<T extends DrawingTruck, U extends IMoveable
else else
t.DrawTransport((Graphics2D) g); t.DrawTransport((Graphics2D) g);
} }
i++;
} }
} }
} }

View File

@ -0,0 +1,45 @@
package RoadTrain.Generics;
import RoadTrain.DrawingObjects.*;
import RoadTrain.MovementStraregy.*;
import java.util.HashMap;
import java.util.List;
import java.util.stream.Collectors;
public class TrucksGenericStorage {
HashMap<String, TrucksGenericCollection<DrawingTruck, DrawingObjectTruck>> _truckStorages;
public List<String> Keys(){return _truckStorages.keySet().stream().collect(Collectors.toList());}
private int _pictureWidth;
private int _pictureHeight;
public TrucksGenericStorage(int pictureWidth, int pictureHeight)
{
_truckStorages = new HashMap<String, TrucksGenericCollection<DrawingTruck, DrawingObjectTruck>>();
_pictureWidth = pictureWidth;
_pictureHeight = pictureHeight;
}
public void AddSet(String name)
{
if (_truckStorages.containsKey(name))
return;
_truckStorages.put(name, new TrucksGenericCollection<DrawingTruck, DrawingObjectTruck>(_pictureWidth, _pictureHeight));
}
public void DelSet(String name)
{
if (!_truckStorages.containsKey(name))
return;
_truckStorages.remove(name);
}
public TrucksGenericCollection<DrawingTruck, DrawingObjectTruck> get(String ind)
{
if (_truckStorages.containsKey(ind))
return _truckStorages.get(ind);
return null;
}
public DrawingObjectTruck get(String ind1, int ind2){
if (!_truckStorages.containsKey(ind1))
return null;
return _truckStorages.get(ind1).GetU(ind2);
}
}

View File

@ -70,7 +70,6 @@ public class RoadTrainForm{
random.nextInt(2000) + 1000, random.nextInt(2000) + 1000,
color, this.canv.getWidth(), this.canv.getHeight(), random.nextInt(3)); color, this.canv.getWidth(), this.canv.getHeight(), random.nextInt(3));
_drawingTruck.SetPosition(random.nextInt(100), random.nextInt(90)); _drawingTruck.SetPosition(random.nextInt(100), random.nextInt(90));
canv._drawingTruck = _drawingTruck;
Draw(); Draw();
} }
); );
@ -94,7 +93,6 @@ public class RoadTrainForm{
color, color2, random.nextBoolean(), random.nextBoolean(), color, color2, random.nextBoolean(), random.nextBoolean(),
this.canv.getWidth(), this.canv.getHeight(), random.nextInt(3)); this.canv.getWidth(), this.canv.getHeight(), random.nextInt(3));
_drawingTruck.SetPosition(random.nextInt(100), random.nextInt(90)); _drawingTruck.SetPosition(random.nextInt(100), random.nextInt(90));
canv._drawingTruck = _drawingTruck;
Draw(); Draw();
} }
); );
@ -152,7 +150,6 @@ public class RoadTrainForm{
} }
}); });
frame.setSize(910, 500); frame.setSize(910, 500);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(null); frame.setLayout(null);
canv = new Canvas(); canv = new Canvas();
canv.setBounds(0, 0, 900, 500); canv.setBounds(0, 0, 900, 500);
@ -178,7 +175,6 @@ public class RoadTrainForm{
frame.setVisible(true); frame.setVisible(true);
} }
class Canvas extends JComponent{ class Canvas extends JComponent{
public DrawingTruck _drawingTruck;
public Canvas(){} public Canvas(){}
public void paintComponent(Graphics g){ public void paintComponent(Graphics g){