Kargin D.E. Lab Work 4 #4

Closed
d.kargin wants to merge 3 commits from LabWork04 into LabWork03
3 changed files with 195 additions and 96 deletions
Showing only changes of commit 48e2dfaf6c - Show all commits

View File

@ -1,10 +1,14 @@
import javax.imageio.ImageIO;
import javax.swing.*;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import java.awt.*;
import java.awt.event.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
public class FormMapWithSetAirFighters extends JFrame {
private JLabel panelForDrawing;
@ -12,7 +16,14 @@ public class FormMapWithSetAirFighters extends JFrame {
private JButton buttonDown;
private JButton buttonLeft;
private JButton buttonRight;
private MapWithSetAirFightersGeneric<DrawningObjectAirFighter, AbstractMap> _mapAirFightersCollectionGeneric;
private JList<String> listStorage;
private DefaultListModel<String> listModel;
private final HashMap<String, AbstractMap> _mapDict = new HashMap<String, AbstractMap>() {{
put("Простая карта", new SimpleMap());
put("Карта шторма", new StormMap());
}};
/// Объект от коллекции карт
private MapsCollection _mapsCollection;
private ActionListener actionListenerDirection = new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
@ -27,57 +38,122 @@ public class FormMapWithSetAirFighters extends JFrame {
} else if (buttonRight.equals(tempButton)) {
dir = Direction.Right;
}
panelForDrawing.setIcon(new ImageIcon(_mapAirFightersCollectionGeneric.MoveObject(dir)));
panelForDrawing.setIcon(new ImageIcon(_mapsCollection.get(listStorage.getSelectedValue().toString()).MoveObject(dir)));
}
};
// Заполнение JL
private void ReloadMaps()
{
int index = listStorage.getSelectedIndex();
listModel.clear();
for (int i = 0; i < _mapsCollection.Keys().size(); i++)
{
listModel.addElement(_mapsCollection.Keys().get(i));
listStorage.setSelectedIndex(index);
}
if (listStorage.getModel().getSize() > 0 && (index == -1 || index >= listStorage.getModel().getSize()))
{
listStorage.setSelectedIndex(0);
}
else if (listStorage.getModel().getSize() > 0 && index > -1 && index < listStorage.getModel().getSize())
{
listStorage.setSelectedIndex(index);
}
}
private FormMapWithSetAirFighters(){
super("Хранилище объектов");
setLayout(null);
// Панелька для отрисовки
panelForDrawing = new JLabel();
panelForDrawing.setBounds(0, 0, 800, 700);
_mapsCollection = new MapsCollection(panelForDrawing.getWidth(), panelForDrawing.getHeight());
add(panelForDrawing);
// Панель инструментов
JPanel panelTools = new JPanel();
panelTools.setBounds(800, 0, 200, 700);
panelTools.setLayout(null);
// Панель инструментов для хранилища
JPanel panelToolsForMap = new JPanel();
panelToolsForMap.setBounds(800, 0, 200, 300);
panelToolsForMap.setLayout(null);
// JTextField для получение названия хранилища
JTextField nameStorage = new JTextField();
nameStorage.setBounds(0, 10, 160, 30);
panelToolsForMap.add(nameStorage);
// ComboBox выбора карты
String[] maps = {
"Простая карта",
"Карта шторма"
};
JComboBox mapComboBox = new JComboBox(maps);
mapComboBox.addActionListener(new ActionListener() {
JComboBox mapComboBox = new JComboBox();
for(String map : _mapDict.keySet()){
mapComboBox.addItem(map);
}
mapComboBox.setBounds(0, 50, 160, 30);
mapComboBox.setSelectedIndex(0);
panelToolsForMap.add(mapComboBox);
// Кнопка добавление хранилища
JButton buttonAddMap = new JButton("Добавить карту");
buttonAddMap.setBounds(0, 90, 160, 30);
buttonAddMap.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
JComboBox box = (JComboBox)e.getSource();
AbstractMap map = null;
switch ((String)box.getSelectedItem()){
case "Простая карта":
map = new SimpleMap();
break;
case "Карта шторма":
map = new StormMap();
break;
default:
map = new SimpleMap();
break;
if (mapComboBox.getSelectedIndex() == -1 || nameStorage.getText().isEmpty() || nameStorage.getText() == null)
{
JOptionPane.showMessageDialog(panelToolsForMap, "Не все данные заполнены");
return;
}
_mapAirFightersCollectionGeneric = new
MapWithSetAirFightersGeneric<DrawningObjectAirFighter, AbstractMap>(
panelForDrawing.getWidth(), panelForDrawing.getHeight(), map);
if (!_mapDict.keySet().contains(mapComboBox.getSelectedItem().toString()))
{
JOptionPane.showMessageDialog(panelToolsForMap,"Нет такой карты");
return;
}
_mapsCollection.AddMap(nameStorage.getText(),
_mapDict.get(mapComboBox.getSelectedItem().toString()));
ReloadMaps();
}
});
mapComboBox.setBounds(0, 10, 160, 30);
mapComboBox.setSelectedIndex(0);
panelTools.add(mapComboBox);
panelToolsForMap.add(buttonAddMap);
// JList отображения доступных хранилищ
listModel = new DefaultListModel<String>();
listStorage = new JList<String>(listModel);
JScrollPane scrollPane = new JScrollPane();
scrollPane.setViewportView(listStorage);
listStorage.setLayoutOrientation(JList.VERTICAL);
listStorage.addListSelectionListener(new ListSelectionListener() {
@Override
public void valueChanged(ListSelectionEvent e) {
if(listStorage.getSelectedValue() != null)
panelForDrawing.setIcon(new ImageIcon(_mapsCollection.get(listStorage.getSelectedValue().toString()).ShowSet()));
}
});
scrollPane.setBounds(0, 140, 160, 60);
panelToolsForMap.add(scrollPane);
// Кнопка удаления хранилища
JButton buttonRemoveMap = new JButton("Удалить карту");
buttonRemoveMap.setBounds(0, 210, 160, 30);
buttonRemoveMap.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
if (listStorage.getSelectedIndex() == -1)
{
return;
}
int confirm = JOptionPane.showOptionDialog(panelToolsForMap,
String.format("Удалить карту %s", listStorage.getSelectedValue()),
"Exit Confirmation", JOptionPane.YES_NO_OPTION,
JOptionPane.QUESTION_MESSAGE, null, null, null);
if (confirm == JOptionPane.YES_OPTION)
{
_mapsCollection.DelMap(listStorage.getSelectedValue() != null ? listStorage.getSelectedValue().toString() : null);
ReloadMaps();
}
}
});
panelToolsForMap.add(buttonRemoveMap);
// Панель инструментов
JPanel panelTools = new JPanel();
panelTools.setBounds(800, 300, 200, 400);
panelTools.setLayout(null);
// Кнопка добавления
JButton buttonAdd = new JButton("Добавить объект");
buttonAdd.setBounds(0, 50, 160, 30);
buttonAdd.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
if (_mapAirFightersCollectionGeneric == null)
if (listStorage.getSelectedIndex() == -1)
{
return;
}
@ -99,10 +175,10 @@ public class FormMapWithSetAirFighters extends JFrame {
return;
}
DrawningObjectAirFighter airFighter = new DrawningObjectAirFighter(form.GetSelectedAirFighter());
if (_mapAirFightersCollectionGeneric.Add(airFighter) == 0)
if (_mapsCollection.get(listStorage.getSelectedValue().toString()).Add(airFighter) == 0)
{
JOptionPane.showMessageDialog(panelTools, "Объект добавлен");
panelForDrawing.setIcon(new ImageIcon(_mapAirFightersCollectionGeneric.ShowSet()));
panelForDrawing.setIcon(new ImageIcon(_mapsCollection.get(listStorage.getSelectedValue().toString()).ShowSet()));
}
}
}
@ -125,13 +201,16 @@ public class FormMapWithSetAirFighters extends JFrame {
textFieldIndex.setBounds(0, 90, 160, 30);
panelTools.add(textFieldIndex);
// Кнопка удаления
// Кнопка добавления
JButton buttonRemove = new JButton("Удалить объект");
buttonRemove.setBounds(0, 130, 160, 30);
buttonRemove.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
try {
if (listStorage.getSelectedIndex() == -1)
{
return;
}
if (textFieldIndex.getText().isEmpty()) {
return;
}
@ -143,9 +222,9 @@ public class FormMapWithSetAirFighters extends JFrame {
return;
}
int pos = Integer.parseInt(textFieldIndex.getText());
if (_mapAirFightersCollectionGeneric.Remove(pos) != null) {
if (_mapsCollection.get(listStorage.getSelectedValue().toString()).Remove(pos) != null) {
JOptionPane.showMessageDialog(panelTools, "Объект удален");
panelForDrawing.setIcon(new ImageIcon(_mapAirFightersCollectionGeneric.ShowSet()));
panelForDrawing.setIcon(new ImageIcon(_mapsCollection.get(listStorage.getSelectedValue().toString()).ShowSet()));
} else {
JOptionPane.showMessageDialog(panelTools, "Не удалось удалить объект");
}
@ -161,11 +240,11 @@ public class FormMapWithSetAirFighters extends JFrame {
buttonShowStorage.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
if (_mapAirFightersCollectionGeneric == null)
if (listStorage.getSelectedIndex() == -1)
{
return;
}
panelForDrawing.setIcon(new ImageIcon(_mapAirFightersCollectionGeneric.ShowSet()));
panelForDrawing.setIcon(new ImageIcon(_mapsCollection.get(listStorage.getSelectedValue().toString()).ShowSet()));
}
});
panelTools.add(buttonShowStorage);
@ -175,11 +254,11 @@ public class FormMapWithSetAirFighters extends JFrame {
buttonShowOnMap.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
if (_mapAirFightersCollectionGeneric == null)
if (listStorage.getSelectedIndex() == -1)
{
return;
}
panelForDrawing.setIcon(new ImageIcon(_mapAirFightersCollectionGeneric.ShowOnMap()));
panelForDrawing.setIcon(new ImageIcon(_mapsCollection.get(listStorage.getSelectedValue().toString()).ShowOnMap()));
}
});
panelTools.add(buttonShowOnMap);
@ -252,9 +331,10 @@ public class FormMapWithSetAirFighters extends JFrame {
constraintsDirection.gridx = 2;
containerDirection.add(buttonRight, constraintsDirection);
}catch (IOException e){}
containerDirection.setBounds(20, 500, 110, 70);
containerDirection.setBounds(20, 250, 110, 70);
panelTools.add(containerDirection);
add(panelToolsForMap);
add(panelTools);
}
public static void main(String[] args) {

View File

@ -0,0 +1,44 @@
import java.util.ArrayList;
import java.util.HashMap;
public class MapsCollection {
// Словарь (хранилище) с картами
private final HashMap<String, MapWithSetAirFightersGeneric<DrawningObjectAirFighter, AbstractMap>> _mapStorages;
public ArrayList<String> 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))
{
return;
}
_mapStorages.put(name, new MapWithSetAirFightersGeneric<>(_pictureWidth,_pictureHeight,map));
}
// Удаление карты
public void DelMap(String name)
{
_mapStorages.remove(name);
}
// Доступ к хранилищу
public MapWithSetAirFightersGeneric<DrawningObjectAirFighter, AbstractMap> get(String ind){
if (_mapStorages.containsKey(ind))
{
return _mapStorages.get(ind);
}
return null;
}
}

View File

@ -1,28 +1,19 @@
public class SetAirFightersGeneric<T> {
// Массив объектов, которые храним
private T[] _places;
// Количество объектов в массиве
public int Count(){return _places.length;};
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
public class SetAirFightersGeneric<T> implements Iterable<T>{
// Список объектов, которые храним
private ArrayList<T> _places;
// Количество объектов в списке
public int Count(){return _places.size();};
/// Максимальная длина списка
private int _maxCount;
// Конструктор
public SetAirFightersGeneric(int count)
{
_places = (T[])new Object[count];
}
/// Проверка на наличие пустых мест
private boolean CheckNullPosition(int firstIndex)
{
if(firstIndex >= _places.length && firstIndex < 0)
{
return false;
}
for(int i = firstIndex; i < _places.length; i++)
{
if(_places[i] == null)
{
return true;
}
}
return false;
_places = new ArrayList<>();
_maxCount = count;
}
/// Добавление объекта в набор
public int Insert(T airFighter)
@ -32,48 +23,23 @@ public class SetAirFightersGeneric<T> {
/// Добавление объекта в набор на конкретную позицию
public int Insert(T airFighter, int position)
{
if(airFighter == null)
if (position < 0 && position > _maxCount)
{
return -1;
}
if (_places[position] == null)
{
_places[position] = airFighter;
}
else
{
if(CheckNullPosition(position + 1))
{
T tempMain = airFighter;
for (int i = position; i < _places.length; i++)
{
if (_places[i] == null)
{
_places[i] = tempMain;
break;
}
else
{
T temp2 = _places[i];
_places[i] = tempMain;
tempMain = temp2;
}
}
}
else
{
return -1;
}
_places.add(position, airFighter);
return position;
}
return position;
}
/// Удаление объекта из набора с конкретной позиции
public T Remove(int position)
{
if (position >= 0 && position < _places.length && _places[position] != null)
if (position >= 0 && position < _maxCount && _places.get(position) != null)
{
T temp = _places[position];
_places[position] = null;
T temp = _places.get(position);
_places.remove(position);
return temp;
}
else
@ -82,11 +48,20 @@ public class SetAirFightersGeneric<T> {
/// Получение объекта из набора по позиции
public T Get(int position)
{
if (_places[position] != null)
if (position >= 0 && position <= _maxCount && position < Count())
{
return _places[position];
return _places.get(position);
}
else
return null;
}
public void Set(int position, T value){
if (position < 0 && position > _maxCount)
return;
Insert(value, position);
}
@Override
public Iterator<T> iterator() {
return _places.iterator();
}
}