365 lines
15 KiB
Java
365 lines
15 KiB
Java
import javax.swing.*;
|
||
import javax.swing.text.MaskFormatter;
|
||
import java.awt.*;
|
||
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 final HashMap<String, AbstractMap> _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<String> mapsListModel = new DefaultListModel<>();
|
||
JScrollPane listScroller = new JScrollPane();
|
||
JList listBoxMaps;
|
||
|
||
public FormMapWithSetLocomotives() {
|
||
formFrame = new JFrame("Form Map With SetLocomotives");
|
||
formFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
|
||
formFrame.setSize(750, 500);
|
||
formFrame.setLocationRelativeTo(null);
|
||
|
||
statusPanel = new Panel();
|
||
statusPanel.setBackground(Color.WHITE);
|
||
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"
|
||
};
|
||
mapSelectComboBox = new JComboBox(maps);
|
||
mapSelectComboBox.setEditable(true);
|
||
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 -> {
|
||
FormLocomotiveConfig formLocomotiveConfig = new FormLocomotiveConfig();
|
||
formLocomotiveConfig.setVisible(true);
|
||
formLocomotiveConfig.AddListener(locomotive -> {
|
||
if (listBoxMaps.getSelectedIndex() == -1) {
|
||
return;
|
||
}
|
||
if (locomotive!=null) {
|
||
DrawningObjectLocomotive objectLocomotive = new DrawningObjectLocomotive(locomotive);
|
||
if (_mapsCollection.Get(listBoxMaps.getSelectedValue().toString()).Plus(objectLocomotive)!= -1){
|
||
JOptionPane.showMessageDialog(formFrame, "Object added", "Success", JOptionPane.OK_CANCEL_OPTION);
|
||
bufferImg = _mapsCollection.Get(listBoxMaps.getSelectedValue().toString()).ShowSet();
|
||
repaint();
|
||
}
|
||
else {
|
||
JOptionPane.showMessageDialog(formFrame, "Object cannot be added", "Error", JOptionPane.OK_CANCEL_OPTION);
|
||
}
|
||
}
|
||
});
|
||
});
|
||
statusPanel.add(addLocomotiveButton);
|
||
|
||
// Текстовое поле для ввода позиции с маской
|
||
JFormattedTextField maskedTextFieldPosition = null;
|
||
try {
|
||
MaskFormatter positionMask = new MaskFormatter("##");
|
||
maskedTextFieldPosition = new JFormattedTextField(positionMask);
|
||
statusPanel.add(maskedTextFieldPosition);
|
||
}
|
||
catch (ParseException e) {
|
||
e.printStackTrace();
|
||
}
|
||
//Кнопка удаления локомотива
|
||
JButton deleteLocomotiveButton = new JButton("Delete Locomotive");
|
||
JFormattedTextField finalMaskedTextFieldPosition = maskedTextFieldPosition;
|
||
deleteLocomotiveButton.addActionListener(e -> {
|
||
// логика удаления
|
||
if ((String)mapSelectComboBox.getSelectedItem() == null) {
|
||
return;
|
||
}
|
||
if (finalMaskedTextFieldPosition == null) {
|
||
return;
|
||
}
|
||
int position = Integer.parseInt(finalMaskedTextFieldPosition.getText());
|
||
if (_mapsCollection.Get(listBoxMaps.getSelectedValue().toString()).Minus(position) != null) {
|
||
JOptionPane.showMessageDialog(formFrame, "Object removed", "Success", JOptionPane.OK_CANCEL_OPTION);
|
||
bufferImg = _mapsCollection.Get(listBoxMaps.getSelectedValue().toString()).ShowSet();
|
||
repaint();
|
||
}
|
||
else{
|
||
JOptionPane.showMessageDialog(formFrame, "Object cannot be removed", "Error", JOptionPane.OK_CANCEL_OPTION);
|
||
}
|
||
});
|
||
statusPanel.add(deleteLocomotiveButton);
|
||
//Кнопка просмотра хранилища
|
||
JButton showStorageButton = new JButton("Show Storage");
|
||
showStorageButton.addActionListener(e -> {
|
||
// логика просмотра
|
||
if (listBoxMaps.getSelectedIndex() == -1)
|
||
{
|
||
return;
|
||
}
|
||
bufferImg = _mapsCollection.Get(listBoxMaps.getSelectedValue().toString()).ShowSet();
|
||
repaint();
|
||
});
|
||
statusPanel.add(showStorageButton);
|
||
//Кнопка просмотра карты
|
||
JButton showOnMapButton = new JButton("Show On Map");
|
||
showOnMapButton.addActionListener(e -> {
|
||
// логика просмотра
|
||
if (listBoxMaps.getSelectedIndex() == -1)
|
||
{
|
||
return;
|
||
}
|
||
bufferImg = _mapsCollection.Get(listBoxMaps.getSelectedValue().toString()).ShowOnMap();
|
||
repaint();
|
||
});
|
||
statusPanel.add(showOnMapButton);
|
||
|
||
ActionListener moveButtonListener = new ActionListener() {
|
||
@Override
|
||
public void actionPerformed(ActionEvent e) {
|
||
if (listBoxMaps.getSelectedIndex() == -1)
|
||
{
|
||
return;
|
||
}
|
||
String name = e.getActionCommand();
|
||
Direction dir = Direction.None;
|
||
switch (name)
|
||
{
|
||
case "Up":
|
||
dir = Direction.Up;
|
||
break;
|
||
case "Down":
|
||
dir = Direction.Down;
|
||
break;
|
||
case "Left":
|
||
dir = Direction.Left;
|
||
break;
|
||
case "Right":
|
||
dir = Direction.Right;
|
||
break;
|
||
}
|
||
bufferImg = _mapsCollection.Get(listBoxMaps.getSelectedValue().toString()).MoveObject(dir);
|
||
}
|
||
};
|
||
|
||
//Кнопки управления
|
||
JButton moveDownButton = new JButton("Down");
|
||
moveDownButton.addActionListener(moveButtonListener);
|
||
|
||
JButton moveUpButton = new JButton("Up");
|
||
moveUpButton.addActionListener(moveButtonListener);
|
||
|
||
JButton moveLeftButton = new JButton("Left");
|
||
moveLeftButton.addActionListener(moveButtonListener);
|
||
|
||
JButton moveRightButton = new JButton("Right");
|
||
moveRightButton.addActionListener(moveButtonListener);
|
||
|
||
statusPanel.add(moveUpButton);
|
||
statusPanel.add(moveDownButton);
|
||
statusPanel.add(moveLeftButton);
|
||
statusPanel.add(moveRightButton);
|
||
|
||
JButton showGalleryButton = new JButton("Show Gallery");
|
||
showGalleryButton.addActionListener(e -> {
|
||
new FormEntityWithExtraGallery();
|
||
});
|
||
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);
|
||
}
|
||
});
|
||
// Сохранения и загрузки
|
||
JFileChooser fileChooser = new JFileChooser();
|
||
// Сохранение всех хранилищ
|
||
JButton saveButton = new JButton("Save");
|
||
saveButton.addActionListener(e -> {
|
||
fileChooser.setDialogTitle("Saving");
|
||
int result = fileChooser.showSaveDialog(FormMapWithSetLocomotives.this);
|
||
if (result == JFileChooser.APPROVE_OPTION ) {
|
||
if (_mapsCollection.SaveData(fileChooser.getSelectedFile().getAbsolutePath())) {
|
||
JOptionPane.showMessageDialog(null, "Save success");
|
||
}
|
||
else JOptionPane.showMessageDialog(null, "Save failed");
|
||
}
|
||
|
||
});
|
||
statusPanel.add(saveButton);
|
||
// Загрузка всех хранилищ
|
||
JButton loadButton = new JButton("Load");
|
||
loadButton.addActionListener(e -> {
|
||
fileChooser.setDialogTitle("Loading");
|
||
int result = fileChooser.showSaveDialog(FormMapWithSetLocomotives.this);
|
||
if (result == JFileChooser.APPROVE_OPTION ) {
|
||
if (_mapsCollection.LoadData(fileChooser.getSelectedFile().getAbsolutePath())) {
|
||
JOptionPane.showMessageDialog(null, "Load success");
|
||
}
|
||
else JOptionPane.showMessageDialog(null, "Load failed");
|
||
}
|
||
ReloadMaps();
|
||
repaint();
|
||
});
|
||
statusPanel.add(loadButton);
|
||
|
||
// Сохранение выбранной карты
|
||
JButton saveMapButton = new JButton("Save Map");
|
||
saveMapButton.addActionListener(e -> {
|
||
fileChooser.setDialogTitle("Saving Map");
|
||
int result = fileChooser.showSaveDialog(FormMapWithSetLocomotives.this);
|
||
if (result == JFileChooser.APPROVE_OPTION ) {
|
||
if (listBoxMaps.getSelectedIndex() == -1)
|
||
{
|
||
return;
|
||
}
|
||
if(listBoxMaps.getSelectedValue().toString() == null) return;
|
||
if (_mapsCollection.SaveMap(listBoxMaps.getSelectedValue().toString(), fileChooser.getSelectedFile().getAbsolutePath())) {
|
||
JOptionPane.showMessageDialog(null, "Map saving success");
|
||
}
|
||
else JOptionPane.showMessageDialog(null, "Map saving fail");
|
||
repaint();
|
||
}
|
||
});
|
||
statusPanel.add(saveMapButton);
|
||
|
||
// Загрузка одной карты
|
||
JButton loadMapButton = new JButton("Load Map");
|
||
loadMapButton.addActionListener(e -> {
|
||
fileChooser.setDialogTitle("Loading");
|
||
int result = fileChooser.showSaveDialog(FormMapWithSetLocomotives.this);
|
||
if (result == JFileChooser.APPROVE_OPTION ) {
|
||
if (_mapsCollection.LoadMap(fileChooser.getSelectedFile().getAbsolutePath())) {
|
||
JOptionPane.showMessageDialog(null, "Load Map success");
|
||
}
|
||
else JOptionPane.showMessageDialog(null, "Load Map failed");
|
||
}
|
||
ReloadMaps();
|
||
repaint();
|
||
});
|
||
statusPanel.add(loadMapButton);
|
||
|
||
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);
|
||
Graphics2D g2 = (Graphics2D)g;
|
||
if (bufferImg != null) g2.drawImage(bufferImg, 0,0,600,500,null);
|
||
super.repaint();
|
||
}
|
||
|
||
}
|