package ProjectElectricLocomotive; import javax.swing.*; import javax.swing.event.ListSelectionEvent; import javax.swing.filechooser.FileNameExtensionFilter; import java.awt.*; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.util.Stack; import org.apache.logging.log4j.Logger; //готовая лаба 3 public class FormLocomotiveCollections { FormElectricLocomotive formElectricLocomotive; FormLocomotiveConfig formLocomotiveConfig; private JPanel MainPanel; private JPanel pictureBoxCollections; private JPanel Instruments; private JButton ButtonAddLocomotive; private JTextField textFieldNumber; private JButton ButtonRefreshCollection; private JButton ButtonRemoveLocomotive; private JButton ButtonCreateRandomLoco; private JTextField textBoxStorageName; private JButton ButtonAddObject; private JList listBoxStorage; private JButton ButtonRemoveObject; private JButton Button_OpenFormRemovedLocomotives; public DrawingLocomotive loco; final LocomotivesGenericStorage _storage; FrameElectricLocomotive _frameRemovedLocomotives; private Stack _stackRemoveObjects; FrameDopClassParameters frameDopClassParameters; public JPanel getPictureBoxCollections() { return MainPanel; } public FormLocomotiveCollections() { formElectricLocomotive = new FormElectricLocomotive(); formLocomotiveConfig = new FormLocomotiveConfig(); _storage = new LocomotivesGenericStorage(400, 300); _stackRemoveObjects = new Stack<>(); listBoxStorage.addListSelectionListener(this::listBoxObjectsSelectedIndexChanged); ButtonAddObject.addActionListener(e -> { String NameStorage = textBoxStorageName.getText(); if (NameStorage.equals("")) { JOptionPane.showMessageDialog(this.getPictureBoxCollections(), "Где данные? Напиши хоть что-нибудь", "Ошибка", JOptionPane.INFORMATION_MESSAGE); return; } _storage.AddSet(NameStorage); ReloadObjects(); Refresh(); }); ButtonRemoveObject.addActionListener(e -> { if (listBoxStorage.getSelectedIndex() == -1) { return; } JOptionPane.showMessageDialog(this.getPictureBoxCollections(), "Коллекция удалена", "Удаление", JOptionPane.INFORMATION_MESSAGE); _storage.DelSet((String) listBoxStorage.getSelectedValue()); //ТУТ СТРИНГ ОБРАТИ ВНИМАНИЕ КАК-НИБУДЬ ReloadObjects(); }); ButtonAddLocomotive.addActionListener(e -> { if (listBoxStorage.getSelectedIndex() == -1) return; var obj = _storage.get(listBoxStorage.getSelectedValue().toString()); // ТУТ ЕЩЕ РАЗ - ОБРАТИ ВНИМАНИЕ НА СТРИНГ if (obj == null) { return; } FrameLocomotiveConfig frameLocomotiveConfig = new FrameLocomotiveConfig(); frameLocomotiveConfig.setVisible(true); frameLocomotiveConfig._formLocomotiveConfig.buttonOk.addActionListener(e2 -> { frameLocomotiveConfig.dispose(); loco = frameLocomotiveConfig._formLocomotiveConfig._loco; try { if (loco != null) { if (obj.AddOverload(loco) != -1) { JOptionPane.showMessageDialog(getPictureBoxCollections(), "Объект добавлен"); Refresh(); } else { JOptionPane.showMessageDialog(getPictureBoxCollections(), "Не удалось добавить объект"); } } frameLocomotiveConfig._formLocomotiveConfig.buttonClose.addActionListener(e3 -> { frameLocomotiveConfig.dispose(); }); } catch (LocoStorageOverflowException ex) { JOptionPane.showMessageDialog(null, ex.getMessage()); } }); }); ButtonCreateRandomLoco.addActionListener(e -> { if (frameDopClassParameters != null) frameDopClassParameters.dispose(); frameDopClassParameters = new FrameDopClassParameters(); frameDopClassParameters.setVisible(true); }); ButtonRemoveLocomotive.addActionListener(e -> { if (listBoxStorage.getSelectedIndex() == -1) { return; } var obj = _storage.get(listBoxStorage.getSelectedValue().toString()); if (obj == null) { return; } int pos = Integer.parseInt(textFieldNumber.getText()); try { /*Object[] options = {"Да", "Нет"}; int n = JOptionPane.showOptionDialog(this.getPictureBoxCollections(), "Удалить объект?", "Все серьезно", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE, null, options, options[0] ); if (n == 1) { return; }*/ DrawingLocomotive removedPlane = obj.SubOverload(pos); if (removedPlane != null) { _stackRemoveObjects.push(removedPlane); Refresh(); JOptionPane.showMessageDialog(this.getPictureBoxCollections(), "Объект удален", "Успех", JOptionPane.INFORMATION_MESSAGE); } else { JOptionPane.showMessageDialog(this.getPictureBoxCollections(), "Не удалось удалить объект", "Ошибка", JOptionPane.ERROR_MESSAGE); } } catch(LocoNotFoundException ex){ JOptionPane.showMessageDialog(null, ex.getMessage()); } }); ButtonRefreshCollection.addActionListener(e -> { Refresh(); }); Button_OpenFormRemovedLocomotives.addActionListener(e -> { if (_stackRemoveObjects.empty()) { JOptionPane.showMessageDialog(this.getPictureBoxCollections(), "Вы ничего не удалили, кажется...", "ой", JOptionPane.INFORMATION_MESSAGE); return; } _frameRemovedLocomotives = new FrameElectricLocomotive(); _frameRemovedLocomotives._formElectricLocomotive._drawingLocomotive = _stackRemoveObjects.pop(); _frameRemovedLocomotives.setVisible(true); _frameRemovedLocomotives._formElectricLocomotive.Draw(); }); } public JMenuBar getMenuBar() { JMenuBar menuBar = new JMenuBar(); JMenu fileMenu = new JMenu("Файл"); JMenuItem openItem = new JMenuItem("Загрузить"); openItem.addActionListener( e -> { JFileChooser fileChooser = new JFileChooser(); fileChooser.setFileFilter(new FileNameExtensionFilter("Текстовые файлы (*.txt)", "txt")); fileChooser.setDialogTitle("Выберите файл для загрузки данных"); if (fileChooser.showOpenDialog(null) == JFileChooser.APPROVE_OPTION) { File selectedFile = fileChooser.getSelectedFile(); try { if (_storage.LoadData(selectedFile.getAbsolutePath())) { JOptionPane.showMessageDialog(null, "Загрузка прошла успешно", "Результат", JOptionPane.INFORMATION_MESSAGE); } else { JOptionPane.showMessageDialog(null, "Не загрузилось", "Результат", JOptionPane.ERROR_MESSAGE); } } catch (FileNotFoundException ex) { /*throw new RuntimeException(ex);*/ } } ReloadObjects(); } ); JMenuItem saveItem = new JMenuItem("Сохранить"); saveItem.addActionListener( e -> { JFileChooser fileChooser = new JFileChooser(); fileChooser.setDialogTitle("Выберите файл для сохранения данных"); fileChooser.setFileFilter(new FileNameExtensionFilter("Текстовые файлы (*.txt)", "txt")); if (fileChooser.showSaveDialog(null) == JFileChooser.APPROVE_OPTION) { File selectedFile = fileChooser.getSelectedFile(); if (_storage.SaveData(selectedFile.getAbsolutePath())) JOptionPane.showMessageDialog(null, "Сохранение прошло успешно", "Результат", JOptionPane.INFORMATION_MESSAGE); else JOptionPane.showMessageDialog(null, "Не сохранилось", "Результат", JOptionPane.ERROR_MESSAGE); } } ); JMenuItem openItemSingle = new JMenuItem("Загрузить коллекцию"); openItemSingle.addActionListener( e -> { JFileChooser fileChooser = new JFileChooser(); fileChooser.setFileFilter(new FileNameExtensionFilter("Текстовые файлы (*.txt)", "txt")); fileChooser.setDialogTitle("Выберите файл для загрузки данных"); if (fileChooser.showOpenDialog(null) == JFileChooser.APPROVE_OPTION) { File selectedFile = fileChooser.getSelectedFile(); try { if (_storage.LoadDataSingle(selectedFile.getAbsolutePath())) { JOptionPane.showMessageDialog(null, "Загрузка прошла успешно", "Результат", JOptionPane.INFORMATION_MESSAGE); } else { JOptionPane.showMessageDialog(null, "Не загрузилось", "Результат", JOptionPane.ERROR_MESSAGE); } } catch (IOException ex) { /*throw new RuntimeException(ex);*/ } } ReloadObjects(); } ); JMenuItem saveItemSingle = new JMenuItem("Сохранить коллекцию"); saveItemSingle.addActionListener( e -> { if (listBoxStorage.getSelectedValue() == null) { JOptionPane.showMessageDialog(null, "Коллекция не выбрана", "Ошибка", JOptionPane.ERROR_MESSAGE); return; } JFileChooser fileChooser = new JFileChooser(); fileChooser.setFileFilter(new FileNameExtensionFilter("Текстовые файлы (*.txt)", "txt")); fileChooser.setDialogTitle("Выберите файл для сохранения данных"); if (fileChooser.showSaveDialog(null) == JFileChooser.APPROVE_OPTION) { File selectedFile = fileChooser.getSelectedFile(); if (_storage.SaveDataSingle(selectedFile.getAbsolutePath(), (String) listBoxStorage.getSelectedValue())) JOptionPane.showMessageDialog(null, "Сохранение прошло успешно", "Результат", JOptionPane.INFORMATION_MESSAGE); else JOptionPane.showMessageDialog(null, "Не сохранилось", "Результат", JOptionPane.ERROR_MESSAGE); } } ); fileMenu.add(openItem); fileMenu.add(saveItem); fileMenu.add(openItemSingle); fileMenu.add(saveItemSingle); menuBar.add(fileMenu); return menuBar; } private void ReloadObjects() { int index = listBoxStorage.getSelectedIndex(); listBoxStorage.setListData(_storage.Keys().toArray()); if (listBoxStorage.getModel().getSize() > 0 && (index == -1 || index >= listBoxStorage.getModel().getSize())) { listBoxStorage.setSelectedIndex(0); } else if (listBoxStorage.getModel().getSize() > 0 && index > -1 && index < listBoxStorage.getModel().getSize()) { listBoxStorage.setSelectedIndex(index); } listBoxStorage.invalidate(); } private void listBoxObjectsSelectedIndexChanged(ListSelectionEvent e) { Refresh(); } public void Refresh() { if (listBoxStorage.getSelectedIndex() == -1) { return; } var obj = _storage.get(listBoxStorage.getSelectedValue().toString()); if (obj == null) { return; } Graphics g = pictureBoxCollections.getGraphics(); pictureBoxCollections.paint(g); obj.ShowLocomotives(g); } }