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; import java.util.logging.Logger; public class FormMapWithSetLocomotives extends JComponent { private BufferedImage bufferImg = null; /// Словарь для выпадающего списка 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() { 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())); Logger.getGlobal().info("Map " + textFieldNewMapName.getText() + " added"); ReloadMaps(); }); statusPanel.add(addMapButton); // ListBox для созданных карт listBoxMaps = new JList(mapsListModel); listBoxMaps.addListSelectionListener(e -> { if(listBoxMaps.getSelectedValue() == null) return; bufferImg = _mapsCollection.Get(listBoxMaps.getSelectedValue().toString()).ShowSet(); Logger.getGlobal().info("Map switched to " + listBoxMaps.getSelectedValue().toString()); 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()); Logger.getGlobal().info("Map " +listBoxMaps.getSelectedValue().toString() +" deleted"); 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) { try { 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(); Logger.getGlobal().info("Object " + locomotive + " added"); repaint(); } else { JOptionPane.showMessageDialog(formFrame, "Object cannot be added", "Error", JOptionPane.OK_CANCEL_OPTION); } } catch (StorageOverflowException ex) { JOptionPane.showMessageDialog(formFrame, "Storage overflow error: "+ ex.getMessage()); Logger.getGlobal().severe("Error " + ex.getMessage()); } catch (Exception ex) { JOptionPane.showMessageDialog(formFrame, "Unknown error: "+ ex.getMessage()); Logger.getGlobal().severe("Error " + ex.getMessage()); } } }); }); 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 -> { // логика удаления try{ 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(); Logger.getGlobal().info("Locomotive deleted at position " + position); repaint(); } else{ JOptionPane.showMessageDialog(formFrame, "Object cannot be removed", "Error", JOptionPane.OK_CANCEL_OPTION); }} catch (LocomotiveNotFoundException ex) { JOptionPane.showMessageDialog(formFrame, "Locomotive not found error: " + ex.getMessage()); Logger.getGlobal().severe("Error " + ex.getMessage()); } catch (Exception ex) { JOptionPane.showMessageDialog(formFrame, "Unknown error: "+ ex.getMessage()); Logger.getGlobal().severe("Error " + ex.getMessage()); } }); 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; } try { bufferImg = _mapsCollection.Get(listBoxMaps.getSelectedValue().toString()).ShowOnMap(); repaint(); } catch (Exception ex) { JOptionPane.showMessageDialog(null, "Unknown error: "+ ex.getMessage()); Logger.getGlobal().severe("Error " + ex.getMessage()); } }); 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 ) { try { _mapsCollection.SaveData(fileChooser.getSelectedFile().getAbsolutePath()); JOptionPane.showMessageDialog(null, "Save success"); Logger.getGlobal().info("Saved all to " + fileChooser.getSelectedFile().getAbsolutePath()); } catch (Exception ex) { JOptionPane.showMessageDialog(null, "Save error: " + ex.getMessage()); Logger.getGlobal().severe("Error " + ex.getMessage()); } } }); 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 ) { try { _mapsCollection.LoadData(fileChooser.getSelectedFile().getAbsolutePath()); JOptionPane.showMessageDialog(null, "Load success"); Logger.getGlobal().info("Loaded all from " + fileChooser.getSelectedFile().getAbsolutePath()); ReloadMaps(); repaint(); } catch (Exception ex) { JOptionPane.showMessageDialog(null, "Load error: " + ex.getMessage()); Logger.getGlobal().severe("Error " + ex.getMessage()); } } }); 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; try { _mapsCollection.SaveMap(listBoxMaps.getSelectedValue().toString(), fileChooser.getSelectedFile().getAbsolutePath()); JOptionPane.showMessageDialog(null, "Map saving success"); Logger.getGlobal().info("Saved map to " + fileChooser.getSelectedFile().getAbsolutePath()); repaint(); } catch (Exception ex) { JOptionPane.showMessageDialog(null, "Map saving error: " + ex.getMessage()); Logger.getGlobal().severe("Error " + ex.getMessage()); } } }); 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 ) { try { _mapsCollection.LoadMap(fileChooser.getSelectedFile().getAbsolutePath()); JOptionPane.showMessageDialog(null, "Load Map success"); Logger.getGlobal().info("Loaded map from " + fileChooser.getSelectedFile().getAbsolutePath()); ReloadMaps(); repaint(); } catch (Exception ex) { JOptionPane.showMessageDialog(null, "Load Map error: " + ex.getMessage()); Logger.getGlobal().severe("Error " + ex.getMessage()); } } }); 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(); } }