diff --git a/DrawningObjectLocomotive.java b/DrawningObjectLocomotive.java index 38617df..2695ed0 100644 --- a/DrawningObjectLocomotive.java +++ b/DrawningObjectLocomotive.java @@ -2,6 +2,9 @@ import java.awt.*; public class DrawningObjectLocomotive implements IDrawningObject { private DrawningLocomotive _locomotive = null; + public DrawningLocomotive GetDrawningLocomotive() { + return _locomotive; + } public DrawningObjectLocomotive(DrawningLocomotive locomotive) { diff --git a/FormLocomotive.java b/FormLocomotive.java index 8d7b5ee..53a92cc 100644 --- a/FormLocomotive.java +++ b/FormLocomotive.java @@ -8,6 +8,10 @@ public class FormLocomotive extends JComponent{ public DrawningLocomotive getSelectedLocomotive() { return SelectedLocomotive; } + public void SetLocomotive(DrawningObjectLocomotive locomotive){ + _locomotive = locomotive.GetDrawningLocomotive(); + repaint(); + } public FormLocomotive(JDialog caller) { Panel statusPanel = new Panel(); diff --git a/FormMapWithSetLocomotives.java b/FormMapWithSetLocomotives.java index 318e071..f091664 100644 --- a/FormMapWithSetLocomotives.java +++ b/FormMapWithSetLocomotives.java @@ -5,62 +5,116 @@ import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.image.BufferedImage; import java.text.ParseException; +import java.util.HashMap; public class FormMapWithSetLocomotives extends JComponent { private BufferedImage bufferImg = null; - /// Объект от класса карты с набором объектов - private MapWithSetLocomotivesGeneric _mapLocomotivesCollectionGeneric; + /// Словарь для выпадающего списка + private final HashMap _mapsDict = new HashMap<>() { + { + put("Simple Map", new SimpleMap()); + put("Spike Map", new SpikeMap()); + put("Rail Map", new RailMap()); + } + }; + /// Объект от коллекции карт + private final MapsCollection _mapsCollection; + + // Элементы на форме + JFrame formFrame; + Panel statusPanel; + TextField textFieldNewMapName; + JComboBox mapSelectComboBox; + DefaultListModel mapsListModel = new DefaultListModel<>(); + JScrollPane listScroller = new JScrollPane(); + JList listBoxMaps; + public FormMapWithSetLocomotives() { - JFrame formFrame = new JFrame("Form Map With SetLocomotives"); + formFrame = new JFrame("Form Map With SetLocomotives"); formFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); formFrame.setSize(750, 500); formFrame.setLocationRelativeTo(null); - Panel statusPanel = new Panel(); + statusPanel = new Panel(); statusPanel.setBackground(Color.WHITE); - statusPanel.setLayout(new GridLayout(0, 1, 20, 20)); + statusPanel.setLayout(new GridLayout(0, 1, 20, 5)); setLayout(new BorderLayout()); add(statusPanel, BorderLayout.EAST); + // Текстовое поле для ввода названия карты + textFieldNewMapName = new TextField(); + statusPanel.add(textFieldNewMapName); + // КомбоБокс с картами String[] maps = { "Simple Map", "Spike Map", "Rail Map" }; - JComboBox mapSelectComboBox = new JComboBox(maps); + mapSelectComboBox = new JComboBox(maps); mapSelectComboBox.setEditable(true); - mapSelectComboBox.addActionListener(e -> { - AbstractMap map = null; - String item = (String)mapSelectComboBox.getSelectedItem(); - switch (item) { - case "Simple Map": - map = new SimpleMap(); - break; - case "Spike Map": - map = new SpikeMap(); - break; - case "Rail Map": - map = new RailMap(); - break; - } - if (map != null) - { - _mapLocomotivesCollectionGeneric = new MapWithSetLocomotivesGeneric - (600, 500, map); - } - else - { - _mapLocomotivesCollectionGeneric = null; - } - }); statusPanel.add(mapSelectComboBox); + // Initialization + _mapsCollection = new MapsCollection(600, 500); + mapSelectComboBox.removeAllItems(); + for (var elem : _mapsDict.keySet()) + { + mapSelectComboBox.addItem(elem); + } + + // Кнопка добавления карты + JButton addMapButton = new JButton("Add Map"); + addMapButton.addActionListener(e -> { + // логика добавления + if (mapSelectComboBox.getSelectedIndex() == -1 || textFieldNewMapName.getText() == null) + { + JOptionPane.showMessageDialog(null, "Not all data is complete!"); + return; + } + if (!_mapsDict.containsKey(mapSelectComboBox.getSelectedItem().toString())) + { + JOptionPane.showMessageDialog(null, "No such map"); + return; + } + _mapsCollection.AddMap(textFieldNewMapName.getText(), _mapsDict.get(mapSelectComboBox.getSelectedItem().toString())); + ReloadMaps(); + }); + statusPanel.add(addMapButton); + + // ListBox для созданных карт + listBoxMaps = new JList(mapsListModel); + listBoxMaps.addListSelectionListener(e -> { + if(listBoxMaps.getSelectedValue() == null) return; + bufferImg = _mapsCollection.Get(listBoxMaps.getSelectedValue().toString()).ShowSet(); + repaint(); + }); + statusPanel.add(listBoxMaps); + + listScroller.setViewportView(listBoxMaps); + listBoxMaps.setLayoutOrientation(JList.VERTICAL); + statusPanel.add(listScroller); + + // Кнопка для удаления карты + JButton deleteMapButton = new JButton("Delete Map"); + deleteMapButton.addActionListener(e -> { + // логика удаления + if (listBoxMaps.getSelectedIndex() == -1) + { + return; + } + if(listBoxMaps.getSelectedValue().toString() == null) return; + _mapsCollection.DelMap(listBoxMaps.getSelectedValue().toString()); + ReloadMaps(); + repaint(); + }); + statusPanel.add(deleteMapButton); + // Кнопка добавления локомотива JButton addLocomotiveButton = new JButton("Add Locomotive"); addLocomotiveButton.addActionListener(e -> { // логика добавления - if (_mapLocomotivesCollectionGeneric == null) + if (listBoxMaps.getSelectedIndex() == -1) { return; } @@ -71,9 +125,9 @@ public class FormMapWithSetLocomotives extends JComponent { dialog.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE); dialog.setVisible(true); DrawningObjectLocomotive locomotive = new DrawningObjectLocomotive(formLocomotive.getSelectedLocomotive()); - if (_mapLocomotivesCollectionGeneric.Plus(locomotive) != -1) { + if (_mapsCollection.Get(listBoxMaps.getSelectedValue().toString()).Plus(locomotive)!= -1) { JOptionPane.showMessageDialog(formFrame, "Object added", "Success", JOptionPane.OK_CANCEL_OPTION); - bufferImg = _mapLocomotivesCollectionGeneric.ShowSet(); + bufferImg = _mapsCollection.Get(listBoxMaps.getSelectedValue().toString()).ShowSet(); repaint(); } else { @@ -104,9 +158,9 @@ public class FormMapWithSetLocomotives extends JComponent { return; } int position = Integer.parseInt(finalMaskedTextFieldPosition.getText()); - if (_mapLocomotivesCollectionGeneric.Minus(position) != null) { + if (_mapsCollection.Get(listBoxMaps.getSelectedValue().toString()).Minus(position) != null) { JOptionPane.showMessageDialog(formFrame, "Object removed", "Success", JOptionPane.OK_CANCEL_OPTION); - bufferImg = _mapLocomotivesCollectionGeneric.ShowSet(); + bufferImg = _mapsCollection.Get(listBoxMaps.getSelectedValue().toString()).ShowSet(); repaint(); } else{ @@ -118,11 +172,11 @@ public class FormMapWithSetLocomotives extends JComponent { JButton showStorageButton = new JButton("Show Storage"); showStorageButton.addActionListener(e -> { // логика просмотра - if (_mapLocomotivesCollectionGeneric == null) + if (listBoxMaps.getSelectedIndex() == -1) { return; } - bufferImg = _mapLocomotivesCollectionGeneric.ShowSet(); + bufferImg = _mapsCollection.Get(listBoxMaps.getSelectedValue().toString()).ShowSet(); repaint(); }); statusPanel.add(showStorageButton); @@ -130,18 +184,19 @@ public class FormMapWithSetLocomotives extends JComponent { JButton showOnMapButton = new JButton("Show On Map"); showOnMapButton.addActionListener(e -> { // логика просмотра - if (_mapLocomotivesCollectionGeneric == null) + if (listBoxMaps.getSelectedIndex() == -1) { return; } - bufferImg = _mapLocomotivesCollectionGeneric.ShowOnMap(); + bufferImg = _mapsCollection.Get(listBoxMaps.getSelectedValue().toString()).ShowOnMap(); + repaint(); }); statusPanel.add(showOnMapButton); ActionListener moveButtonListener = new ActionListener() { @Override public void actionPerformed(ActionEvent e) { - if (_mapLocomotivesCollectionGeneric == null) + if (listBoxMaps.getSelectedIndex() == -1) { return; } @@ -162,7 +217,7 @@ public class FormMapWithSetLocomotives extends JComponent { dir = Direction.Right; break; } - bufferImg = _mapLocomotivesCollectionGeneric.MoveObject(dir); + bufferImg = _mapsCollection.Get(listBoxMaps.getSelectedValue().toString()).MoveObject(dir); } }; @@ -190,10 +245,50 @@ public class FormMapWithSetLocomotives extends JComponent { }); statusPanel.add(showGalleryButton); + // Кнопка показа удаленных объектов + JButton showDeletedButton = new JButton("Show Deleted"); + showDeletedButton.addActionListener(e -> { + // По отдельной кнопке вызывать форму работы с объектом (из + //первой лабораторной), передавая туда элемент из коллекции + //удаленных, если там есть + DrawningObjectLocomotive locomotive = _mapsCollection.Get(listBoxMaps.getSelectedValue().toString()).getDeleted(); + if (locomotive == null) { + JOptionPane.showMessageDialog(null, "No deleted objects"); + } + if (locomotive != null) { + JDialog dialog = new JDialog(formFrame, "Deleted", true); + FormLocomotive formLocomotive = new FormLocomotive(dialog); + formLocomotive.SetLocomotive(locomotive); + dialog.setSize(800, 500); + dialog.setContentPane(formLocomotive); + dialog.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE); + dialog.setVisible(true); + } + }); + statusPanel.add(showDeletedButton); + formFrame.getContentPane().add(this); formFrame.setVisible(true); } + private void ReloadMaps(){ + int index = listBoxMaps.getSelectedIndex(); + listBoxMaps.removeAll(); + mapsListModel.removeAllElements(); + for (int i = 0; i < _mapsCollection.keys().size(); i++){ + mapsListModel.addElement(_mapsCollection.keys().get(i)); + } + if (mapsListModel.size() > 0 && (index == -1 || index >= mapsListModel.size())){ + listBoxMaps.setSelectedIndex(0); + } + else if (mapsListModel.size() > 0 && index > -1 && index < mapsListModel.size()) + { + listBoxMaps.setSelectedIndex(index); + } + listBoxMaps.setModel(mapsListModel); + statusPanel.repaint(); + } + @Override protected void paintComponent(Graphics g) { super.paintComponent(g); diff --git a/MapWithSetLocomotivesGeneric.java b/MapWithSetLocomotivesGeneric.java index d6bd589..a30b6c6 100644 --- a/MapWithSetLocomotivesGeneric.java +++ b/MapWithSetLocomotivesGeneric.java @@ -1,5 +1,6 @@ import java.awt.*; import java.awt.image.BufferedImage; +import java.util.LinkedList; public class MapWithSetLocomotivesGeneric @@ -12,9 +13,15 @@ public class MapWithSetLocomotivesGeneric private final int _placeSizeWidth = 210; /// Размер занимаемого объектом места (высота) private final int _placeSizeHeight = 90; + public final SetLocomotivesGeneric _setLocomotives; - /// Набор объектов - private final SetLocomotivesGeneric _setLocomotives; + // Список удаленных объектов + LinkedList deletedLocomotives = new LinkedList<>(); + + public DrawningObjectLocomotive getDeleted() { + if (deletedLocomotives.isEmpty()) return null; + return deletedLocomotives.removeFirst(); + } /// Карта private final U _map; /// Конструктор @@ -36,7 +43,10 @@ public class MapWithSetLocomotivesGeneric /// Удаление public T Minus(int position) { - return this._setLocomotives.Remove(position); + T temp = this._setLocomotives.Remove(position); + if (temp == null) return null; + deletedLocomotives.add((DrawningObjectLocomotive) temp); + return temp; } /// Вывод всего набора объектов public BufferedImage ShowSet() @@ -52,9 +62,8 @@ public class MapWithSetLocomotivesGeneric public BufferedImage ShowOnMap() { Shaking(); - for (int i = 0; i < _setLocomotives.Count(); i++) + for (var locomotive : _setLocomotives.GetLocomotives()) { - var locomotive = _setLocomotives.Get(i); if (locomotive != null) { return _map.CreateMap(_pictureWidth, _pictureHeight, locomotive); @@ -151,11 +160,11 @@ public class MapWithSetLocomotivesGeneric int curWidth = 0; int curHeight = 0; - for (int i = 0; i < _setLocomotives.Count(); i++) + for (var locomotive : _setLocomotives.GetLocomotives()) { // установка позиции - if (_setLocomotives.Get(i) != null) _setLocomotives.Get(i).SetObject(curWidth * _placeSizeWidth + 10, curHeight * _placeSizeHeight + 18, _pictureWidth, _pictureHeight); - if (_setLocomotives.Get(i) != null) _setLocomotives.Get(i).DrawningObject(g); + if (locomotive != null) locomotive.SetObject(curWidth * _placeSizeWidth + 10, curHeight * _placeSizeHeight + 18, _pictureWidth, _pictureHeight); + if (locomotive != null) locomotive.DrawningObject(g); if (curWidth < width) curWidth++; else { diff --git a/MapsCollection.java b/MapsCollection.java new file mode 100644 index 0000000..4aae1fa --- /dev/null +++ b/MapsCollection.java @@ -0,0 +1,47 @@ +import java.util.ArrayList; +import java.util.HashMap; + +public class MapsCollection { + /// Словарь (хранилище) с картами + final HashMap> _mapStorages; + + /// Возвращение списка названий карт + public ArrayList keys() { + return new ArrayList(_mapStorages.keySet()); + } + /// Ширина окна отрисовки + private final int _pictureWidth; + /// Высота окна отрисовки + private final int _pictureHeight; + /// Конструктор + public MapsCollection(int pictureWidth, int pictureHeight) + { + _mapStorages = new HashMap>(); + _pictureWidth = pictureWidth; + _pictureHeight = pictureHeight; + } + /// Добавление карты + public void AddMap(String name, AbstractMap map) + { + // Логика для добавления + if (!_mapStorages.containsKey(name)) _mapStorages.put(name, new MapWithSetLocomotivesGeneric(_pictureWidth, _pictureHeight, map)); + } + /// Удаление карты + public void DelMap(String name) + { + // Логика для удаления + if (_mapStorages.containsKey(name)) _mapStorages.remove(name); + } + /// Доступ к парковке + public MapWithSetLocomotivesGeneric Get(String ind) + { + // Логика получения объекта + if (_mapStorages.containsKey(ind)) return _mapStorages.get(ind); + return null; + } + // Доп.индексатор из задания + public DrawningObjectLocomotive Get (String name, int position) { + if (_mapStorages.containsKey(name)) return _mapStorages.get(name)._setLocomotives.Get(position); + else return null; + } +} diff --git a/SetLocomotivesGeneric.java b/SetLocomotivesGeneric.java index 7256512..72f1f94 100644 --- a/SetLocomotivesGeneric.java +++ b/SetLocomotivesGeneric.java @@ -1,13 +1,20 @@ +import java.util.ArrayList; + public class SetLocomotivesGeneric { - private final T[] _places; + /// Список хранимых объектов + private final ArrayList _places; public int Count() { - return _places.length; + return _places.size(); } + // Ограничение на количество + private final int _maxCount; + public SetLocomotivesGeneric(int count) { - _places = (T[]) new Object[count]; + _maxCount = count; + _places = new ArrayList<>(); } public int Insert (T locomotive) { @@ -15,47 +22,28 @@ public class SetLocomotivesGeneric } public int Insert (T locomotive, int position) { - if (position >= _places.length || position < 0) return -1; - if (_places[position] == null) { - _places[position] = locomotive; - return position; - } - - int emptyEl = -1; - for (int i = position + 1; i < Count(); i++) - { - if (_places[i] == null) - { - emptyEl = i; - break; - } - } - if (emptyEl == -1) - { - return -1; - } - for (int i = emptyEl; i > position; i--) - { - _places[i] = _places[i - 1]; - } - _places[position] = locomotive; + if (position >= _maxCount|| position < 0) return -1; + _places.add(position, locomotive); return position; } public T Remove (int position) { - if (position >= _places.length || position < 0) return null; - T result = _places[position]; - _places[position] = null; + if (position >= _maxCount || position < 0) return null; + T result = _places.get(position); + _places.remove(position); return result; } public T Get(int position) { - if (position >= _places.length || position < 0) + if (position >= _maxCount || position < 0) { return null; } - return _places[position]; + return _places.get(position); + } + public Iterable GetLocomotives() + { + return _places; } - }