diff --git a/src/laba/Dock.java b/src/laba/Dock.java index f91854e..ef43a07 100644 --- a/src/laba/Dock.java +++ b/src/laba/Dock.java @@ -24,23 +24,6 @@ public class Dock { // Максимальное количество мест private int _maxCount; - // Геттеры и сеттеры для PictureWudth и PictureHeight. - public int getPictureWidth() { - return PictureWidth; - } - - public void setPictureWidth(int pictureWidth) { - PictureWidth = pictureWidth; - } - - public int getPictureHeight() { - return PictureHeight; - } - - public void setPictureHeight(int pictureHeight) { - PictureHeight = pictureHeight; - } - // Конструктор дока. public Dock(int size, int pictureWidth, int pictureHeight) { _maxCount = size; @@ -69,25 +52,25 @@ public int Add(T ship) { // Оператор "-": забрать корабль public T Del(int index) { - if (!CheckFreePlace(index)) - { - T ship = _places.get(index); - _places.remove(index); - return ship; - } - return null; } + if (!CheckFreePlace(index)) { + T ship = _places.get(index); + _places.remove(index); + return ship; + } + return null; + } // Проверить по номеру места, свободно ли оно private boolean CheckFreePlace(int index) { - return !_places.containsKey(index); + return !_places.containsKey(index); } // Отрисовка дока public void Draw(Graphics g) { DrawMarking(g); - for (T ship: _places.values()) { - ship.DrawShip(g); - } + for (T ship : _places.values()) { + ship.DrawShip(g); + } } // Отрисовка линий @@ -104,4 +87,20 @@ private void DrawMarking(Graphics g) { } } } + + public T getAt(int index) { + + if (_places.containsKey(index)) { + return _places.get(index); + } + return null; + } + + public void setAt(int index, T ship) { + if (CheckFreePlace(index)) { + ship.SetPosition(5 + index / 5 * _placeSizeWidth + 5, index % 5 * _placeSizeHeight + 80, + PictureWidth, PictureHeight); + _places.put(index, ship); + } + } } diff --git a/src/laba/FormDock.java b/src/laba/FormDock.java index 1b2ed65..95484ac 100644 --- a/src/laba/FormDock.java +++ b/src/laba/FormDock.java @@ -9,6 +9,8 @@ import javax.swing.DefaultListModel; import javax.swing.JButton; import javax.swing.JColorChooser; +import javax.swing.JDialog; +import javax.swing.JFileChooser; import javax.swing.JTextField; import java.awt.SystemColor; import javax.swing.JTextArea; @@ -21,6 +23,13 @@ import javax.swing.event.ListSelectionEvent; import javax.swing.event.ListSelectionListener; import javax.swing.JScrollPane; +import javax.swing.JMenuBar; +import javax.swing.JMenu; +import javax.swing.JMenuItem; +import java.awt.event.MouseAdapter; +import java.awt.event.MouseEvent; +import java.io.File; +import java.io.FileFilter; public class FormDock { @@ -36,6 +45,10 @@ public class FormDock { private final int countLevel = 5; private FormShipConfig select; private static JList list; + private JMenuBar menuBar; + private JMenu menu; + private JMenuItem menuItem_Save; + private JMenuItem menuItem_Load; /** * Launch the application. @@ -65,7 +78,7 @@ public void getShip() { if (select.res()) { IShip ship = select.ship; int temp = list.getSelectedIndex(); - if(temp == -1) { + if (temp == -1) { temp = 0; } int place = dock.getAt(temp).Add(ship); @@ -158,5 +171,73 @@ public void actionPerformed(ActionEvent e) { button_Take.setBounds(865, 311, 89, 23); frame.getContentPane().add(button_Take); + menuBar = new JMenuBar(); + frame.setJMenuBar(menuBar); + + menu = new JMenu("\u0424\u0430\u0439\u043B"); + menuBar.add(menu); + + menuItem_Save = new JMenuItem("\u0421\u043E\u0445\u0440\u0430\u043D\u0438\u0442\u044C"); + menuItem_Save.addMouseListener(new MouseAdapter() { + @Override + public void mousePressed(MouseEvent arg0) { + JFileChooser fc = new JFileChooser(); + fc.setFileFilter(new MyFilter()); + int returnVal = fc.showOpenDialog(frame); // Where frame is the parent component + + File file = null; + if (returnVal == JFileChooser.APPROVE_OPTION) { + file = fc.getSelectedFile(); + if (dock.SaveData(file.getPath())) { + JOptionPane.showMessageDialog(null, "Сохранение прошло успешно", "Результат", + JOptionPane.INFORMATION_MESSAGE); + } else { + JOptionPane.showMessageDialog(null, "Не сохранилось", "Результат", + JOptionPane.INFORMATION_MESSAGE); + } + + } + } + }); + menu.add(menuItem_Save); + + menuItem_Load = new JMenuItem("\u0417\u0430\u0433\u0440\u0443\u0437\u0438\u0442\u044C"); + menuItem_Load.addMouseListener(new MouseAdapter() { + @Override + public void mousePressed(MouseEvent e) { + JFileChooser fc = new JFileChooser(); + fc.setFileFilter(new MyFilter()); + int returnVal = fc.showOpenDialog(frame); // Where frame is the parent component + + File file = null; + if (returnVal == JFileChooser.APPROVE_OPTION) { + file = fc.getSelectedFile(); + if (dock.LoadData(file.getPath())) { + JOptionPane.showMessageDialog(null, "Загрузили", "Результат", JOptionPane.INFORMATION_MESSAGE); + } else { + JOptionPane.showMessageDialog(null, "Не загрузили", "Результат", + JOptionPane.INFORMATION_MESSAGE); + } + } + panel_Dock.repaint(); + } + }); + menu.add(menuItem_Load); + + } +} + +class MyFilter extends javax.swing.filechooser.FileFilter { + + @Override + public boolean accept(File arg0) { + if (arg0.getName().lastIndexOf('.') == -1) + return true; + return arg0.getName().substring(arg0.getName().lastIndexOf('.')).equals(".txt"); + } + @Override + public String getDescription() { + return null; } + } diff --git a/src/laba/IShip.java b/src/laba/IShip.java index f647e96..29a3586 100644 --- a/src/laba/IShip.java +++ b/src/laba/IShip.java @@ -16,4 +16,5 @@ public interface IShip { //Установление основного цвета void SetMainColor(Color color); + } diff --git a/src/laba/MultiLevelDock.java b/src/laba/MultiLevelDock.java index 0fe1f7c..dd99753 100644 --- a/src/laba/MultiLevelDock.java +++ b/src/laba/MultiLevelDock.java @@ -1,25 +1,160 @@ package laba; +import java.beans.Encoder; +import java.io.File; +import java.io.FileInputStream; +import java.io.FileNotFoundException; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.UnsupportedEncodingException; +import java.net.URLEncoder; import java.util.ArrayList; +import javax.swing.Spring; + +import org.omg.CORBA.Environment; + public class MultiLevelDock { - ArrayList> dockStages; + ArrayList> dockStages; + + private final int countPlaces = 20; + private int pictureWidth; + private int pictureHeight; + + public MultiLevelDock(int countStages, int pictureWidth, int pictureHeight) { + dockStages = new ArrayList>(); + this.pictureWidth = pictureWidth; + this.pictureHeight = pictureHeight; + for (int i = 0; i < countStages; ++i) { + dockStages.add(new Dock(countPlaces, pictureWidth, pictureHeight)); + } + } + + public Dock getAt(int index) { + if (index > -1 && index < dockStages.size()) { + return dockStages.get(index); + } + + return null; + } + + private void WriteToFile(String text, FileOutputStream stream) { + try { + byte[] info = text.getBytes(); + stream.write(info, 0, info.length); + } catch (UnsupportedEncodingException e) { + e.printStackTrace(); + } catch (IOException e) { + e.printStackTrace(); + } + } + + public boolean SaveData(String filename) { + File file = new File(filename); + if (file.exists()) { + file.delete(); + } + FileOutputStream fs; + try { + fs = new FileOutputStream(filename); + // Записываем количество уровней + WriteToFile("CountLeveles:" + dockStages.size() + "\r\n", fs); + for (Dock level : dockStages) { + // Начинаем уровень + WriteToFile("Level" + "\r\n", fs); + for (int i = 0; i < countPlaces; i++) { + IShip ship = level.getAt(i); + if (ship != null) { + // если место не пустое + // Записываем тип мшаины + if (ship instanceof Ship_Liner) { + WriteToFile(i + ":Ship_Liner:", fs); + }else if (ship instanceof Ship) { + WriteToFile(i + ":Ship:", fs); + } + + // Записываемые параметры + System.out.println(ship.toString() + "\r\n"); + WriteToFile(ship.toString() + "\r\n", fs); + + } + } + } + + return true; + } catch (FileNotFoundException e) { + e.printStackTrace(); + } + return false; + } + + public Boolean LoadData(String filename) { + try { + File file = new File(filename); + if (!file.exists()) { + return false; + } + String bufferTextFromFile = ""; + FileInputStream fn; + + fn = new FileInputStream(filename); + + int i = -1; + int size = 0; + while ((i = fn.read()) != -1) { + size++; + } + char[] b = new char[size]; + fn = new FileInputStream(filename); + int j = 0; + while ((i = fn.read()) != -1) { + b[j] = (char) i; + j++; + } - private final int countPlaces = 20; + bufferTextFromFile = new String(b); - public MultiLevelDock(int countStages, int pictureWidth, int pictureHeight) { - dockStages = new ArrayList>(); - for (int i = 0; i < countStages; ++i) - { - dockStages.add(new Dock(countPlaces, pictureWidth, pictureHeight)); - } - } + bufferTextFromFile = bufferTextFromFile.replace("\r", ""); + String[] strs = bufferTextFromFile.split("\n", 0); + if (strs[0].contains("CountLeveles")) { + // считываем количество уровней + int count = Integer.parseInt(strs[0].split(":", 0)[1]); + if (dockStages != null) { + dockStages.clear(); + } + dockStages = new ArrayList>(count); + } else { + // если нет такой записи, то это не те данные + return false; + } + int counter = -1; + IShip ship = null; + for (int k = 1; k < strs.length; ++k) { + // идем по считанным записям + if (strs[k].equals("Level")) { + // начинаем новый уровень + counter++; + dockStages.add(new Dock(countPlaces, pictureWidth, pictureHeight)); + continue; + } + if (strs[k] == null || strs[k].isEmpty()) { + continue; + } + if (strs[k].contains("Ship_Liner")) { + ship = new Ship_Liner(strs[k].split(":", 0)[2]); + } else if (strs[k].contains("Ship")) { + ship = new Ship(strs[k].split(":", 0)[2]); + } + dockStages.get(counter).setAt(Integer.parseInt(strs[k].split(":", 0)[0]), ship); + } - public Dock getAt(int index) { - if (index > -1 && index < dockStages.size()) { - return dockStages.get(index); - } + return true; + } catch (FileNotFoundException e) { + e.printStackTrace(); + } catch (IOException e) { + e.printStackTrace(); + } + return false; + } - return null; - } } diff --git a/src/laba/Ship.java b/src/laba/Ship.java index 66b20b7..1b07a2a 100644 --- a/src/laba/Ship.java +++ b/src/laba/Ship.java @@ -2,6 +2,7 @@ import java.awt.Color; import java.awt.Graphics; +import java.lang.reflect.Field; import javax.swing.JPanel; @@ -18,6 +19,16 @@ public Ship(int maxSpeed, float weight, Color mainColor) { MainColor = mainColor; } + // Перегрузка конструктора с предоставлением информации + public Ship(String info) { + String[] strs = info.split(";", 0); + if (strs.length == 3) { + MaxSpeed = Integer.parseInt(strs[0]); + Weight = Integer.parseInt(strs[1]); + MainColor = getColorByName(strs[2]); + } + } + // Изменение направления пермещения @Override public void MoveTransport(Direction direction) { @@ -65,4 +76,34 @@ public void DrawShip(Graphics g) { g.setColor(MainColor); g.drawRect((int) _startPosX + 10, (int) _startPosY - 35, 70, 10); } + + //преобразование информации в строку + public String toString() { + return MaxSpeed + ";" + (int)Weight + ";" + getColorName(MainColor); + } + + //получение имени цвета + protected String getColorName(Color c) { + Field[] fields = Color.class.getFields(); + for (Field f : fields ) { + try { + if (((Color)f.get(null)).equals(c)) { + return f.getName(); + } + } catch (Exception e) { + e.printStackTrace(); + } + } + return ""; + } + + //получение цвета по имени + protected Color getColorByName(String name) { + try { + return (Color)Color.class.getField(name.toUpperCase()).get(null); + } catch (IllegalArgumentException | IllegalAccessException | NoSuchFieldException | SecurityException e) { + e.printStackTrace(); + return null; + } + } } \ No newline at end of file diff --git a/src/laba/Ship_Liner.java b/src/laba/Ship_Liner.java index fe21454..5108993 100644 --- a/src/laba/Ship_Liner.java +++ b/src/laba/Ship_Liner.java @@ -31,6 +31,21 @@ public Ship_Liner(int maxSpeed, float weight, Color mainColor, Color dopColor, b Window = window; } + // Перегрузка конструктора с предоставлением информации + public Ship_Liner(String info) { + super(info); + String[] strs = info.split(";", 0); + if (strs.length == 7) { + MaxSpeed = Integer.parseInt(strs[0]); + Weight = Integer.parseInt(strs[1]); + MainColor = getColorByName(strs[2]); + DopColor = getColorByName(strs[3]); + Pipe = strs[4].equals("true"); + SmokeFromPipe = strs[5].equals("true"); + Window = strs[6].equals("true"); + } + } + // Отрисовка коробля @Override public void DrawShip(Graphics g) { @@ -74,4 +89,11 @@ public void DrawShip(Graphics g) { public void SetDopColor(Color color) { DopColor = color; } + + //преобразование информации в строку + public String toString() + { + return super.toString() + ";" + getColorName(DopColor) + ";" + Pipe + ";" + + SmokeFromPipe + ";" + Window; + } } diff --git a/src/laba/Window.java b/src/laba/Window.java index 6878aaa..5b3dca6 100644 --- a/src/laba/Window.java +++ b/src/laba/Window.java @@ -28,22 +28,6 @@ public class Window { public IShip ship; public DrawingHelper picturePanelShip; - /** - * Launch the application. - */ -// public static void main(String[] args) { -// EventQueue.invokeLater(new Runnable() { -// public void run() { -// try { -// FormDock window = new FormDock(); -// window.frame.setVisible(true); -// } catch (Exception e) { -// e.printStackTrace(); -// } -// } -// }); -// } - /** * Create the application. * @@ -85,7 +69,7 @@ public void actionPerformed(ActionEvent arg0) { frame.getContentPane().add(buttonCreateShip); BufferedImage buttonIconUp = ImageIO - .read(new File("D:\\All Kurai\\Универ\\2 курс\\Технологии программирования\\стрелка вверх.jpg")); + .read(new File("D:\\All Kurai\\Óíèâåð\\2 êóðñ\\Òåõíîëîãèè ïðîãðàììèðîâàíèÿ\\ñòðåëêà ââåðõ.jpg")); JButton buttonUp = new JButton(new ImageIcon(buttonIconUp)); buttonUp.addMouseListener(new MouseAdapter() { @Override @@ -98,7 +82,7 @@ public void mouseClicked(MouseEvent arg0) { frame.getContentPane().add(buttonUp); BufferedImage buttonIconLeft = ImageIO - .read(new File("D:\\All Kurai\\Универ\\2 курс\\Технологии программирования\\стрелка влево.jpg")); + .read(new File("D:\\All Kurai\\Óíèâåð\\2 êóðñ\\Òåõíîëîãèè ïðîãðàììèðîâàíèÿ\\ñòðåëêà âëåâî.jpg")); JButton buttonLeft = new JButton(new ImageIcon(buttonIconLeft)); buttonLeft.addMouseListener(new MouseAdapter() { @Override @@ -111,7 +95,7 @@ public void mouseClicked(MouseEvent e) { frame.getContentPane().add(buttonLeft); BufferedImage buttonIconRight = ImageIO - .read(new File("D:\\All Kurai\\Универ\\2 курс\\Технологии программирования\\стрелка вправо.jpg")); + .read(new File("D:\\All Kurai\\Óíèâåð\\2 êóðñ\\Òåõíîëîãèè ïðîãðàììèðîâàíèÿ\\ñòðåëêà âïðàâî.jpg")); JButton buttonRight = new JButton(new ImageIcon(buttonIconRight)); buttonRight.addMouseListener(new MouseAdapter() { @Override @@ -124,7 +108,7 @@ public void mouseClicked(MouseEvent e) { frame.getContentPane().add(buttonRight); BufferedImage buttonIconDown = ImageIO - .read(new File("D:\\All Kurai\\Универ\\2 курс\\Технологии программирования\\стрелка вниз.jpg")); + .read(new File("D:\\All Kurai\\Óíèâåð\\2 êóðñ\\Òåõíîëîãèè ïðîãðàììèðîâàíèÿ\\ñòðåëêà ГўГ­ГЁГ§.jpg")); JButton buttonDown = new JButton(new ImageIcon(buttonIconDown)); buttonDown.addMouseListener(new MouseAdapter() { @Override