Compare commits

...

11 Commits

Author SHA1 Message Date
41b14bae2b completed done whateva u wanna call it 2025-02-20 21:01:54 +04:00
3935381e31 completed 2025-02-15 17:46:26 +04:00
c8998395cc transitioned 2025-02-15 16:03:25 +04:00
1ce9de4971 completed 2025-02-14 01:01:17 +04:00
b48714c9cb completed 2025-02-11 21:50:49 +04:00
744b41ca05 some fixes again 2025-02-10 17:25:26 +04:00
2996acbea2 some fixes 2025-02-10 17:25:26 +04:00
d00844dfac LabWork02 is completed
# Conflicts:
#	Liner_Advanced/src/projectliner/DrawingLiner.java
#	Liner_Advanced/src/projectliner/FormLiner.java
2025-02-10 17:25:20 +04:00
fbf7485bd1 updated constructor 2025-02-10 11:01:08 +04:00
b9b074c809 some fixes again 2025-02-10 09:31:20 +04:00
6c478bb1a6 LabWork01 is completed 2025-02-05 19:36:28 +04:00
45 changed files with 3539 additions and 1 deletions

View File

@ -0,0 +1,12 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="MaterialThemeProjectNewConfig">
<option name="metadata">
<MTProjectMetadataState>
<option name="migrated" value="true" />
<option name="pristineConfig" value="false" />
<option name="userId" value="7281a457:1950862827a:-7ffe" />
</MTProjectMetadataState>
</option>
</component>
</project>

View File

@ -3,6 +3,7 @@
<component name="NewModuleRootManager" inherit-compiler-output="true"> <component name="NewModuleRootManager" inherit-compiler-output="true">
<exclude-output /> <exclude-output />
<content url="file://$MODULE_DIR$"> <content url="file://$MODULE_DIR$">
<sourceFolder url="file://$MODULE_DIR$/res" type="java-resource" />
<sourceFolder url="file://$MODULE_DIR$/src" isTestSource="false" /> <sourceFolder url="file://$MODULE_DIR$/src" isTestSource="false" />
</content> </content>
<orderEntry type="inheritedJdk" /> <orderEntry type="inheritedJdk" />

Binary file not shown.

After

Width:  |  Height:  |  Size: 387 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 332 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 294 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 372 B

View File

@ -1,5 +1,12 @@
import javax.swing.*;
public class Main { public class Main {
public static void main(String[] args) { public static void main(String[] args) {
System.out.println("Hello, World!"); SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
new projectliner.FormShipCollection().setVisible(true);
}
});
} }
} }

View File

@ -0,0 +1,22 @@
package projectliner.Drawings;
import javax.swing.*;
import java.awt.datatransfer.*;
public class AdditionalElementsTransferHandler extends TransferHandler {
private final IAdditionalElements additionalElements;
public AdditionalElementsTransferHandler(IAdditionalElements additionalElements) {
this.additionalElements = additionalElements;
}
@Override
protected Transferable createTransferable(JComponent c) {
return new AdditionalElementsTransferable(additionalElements);
}
@Override
public int getSourceActions(JComponent c) {
return COPY;
}
}

View File

@ -0,0 +1,31 @@
package projectliner.Drawings;
import java.awt.datatransfer.*;
import java.io.IOException;
public class AdditionalElementsTransferable implements Transferable {
public static final DataFlavor additionalElementsFlavor = new DataFlavor(IAdditionalElements.class, "IAdditionalElements");
private final IAdditionalElements additionalElements;
public AdditionalElementsTransferable(IAdditionalElements additionalElements) {
this.additionalElements = additionalElements;
}
@Override
public DataFlavor[] getTransferDataFlavors() {
return new DataFlavor[]{additionalElementsFlavor};
}
@Override
public boolean isDataFlavorSupported(DataFlavor flavor) {
return flavor.equals(additionalElementsFlavor);
}
@Override
public Object getTransferData(DataFlavor flavor) throws UnsupportedFlavorException, IOException {
if (!isDataFlavorSupported(flavor)) {
throw new UnsupportedFlavorException(flavor);
}
return additionalElements;
}
}

View File

@ -0,0 +1,59 @@
package projectliner.Drawings;
import java.awt.Color;
import java.awt.Graphics;
public class CircularDeckDrawing implements IAdditionalElements {
private DeckEnum deckEnum;
public CircularDeckDrawing() {
}
public void setNumericalValue(int value) {
for(DeckEnum deck : DeckEnum.values()) {
if (deck.getDeckNumber() == value) {
this.deckEnum = deck;
return;
}
}
throw new IllegalArgumentException("Invalid deck number: " + value);
}
public int getNumericalValue() {
return this.deckEnum.getDeckNumber();
}
public void drawAdditionalElement(int x, int y, Color borderColor, Color fillColor, Graphics g) {
switch (this.deckEnum) {
case UPPER:
this.drawUpperDeck(x, y, borderColor, fillColor, g);
case MIDDLE:
this.drawMiddleDeck(x, y, borderColor, fillColor, g);
case LOWER:
this.drawLowerDeck(x, y, borderColor, fillColor, g);
default:
}
}
private void drawLowerDeck(int x, int y, Color borderColor, Color fillColor, Graphics g) {
g.setColor(fillColor);
g.fillOval(x + 30, y + 15, 100, 20);
g.setColor(borderColor);
g.drawOval(x + 30, y + 15, 100, 20);
}
private void drawMiddleDeck(int x, int y, Color borderColor, Color fillColor, Graphics g) {
g.setColor(fillColor);
g.fillOval(x + 70, y + 10, 50, 20);
g.setColor(borderColor);
g.drawOval(x + 70, y + 10, 50, 20);
}
private void drawUpperDeck(int x, int y, Color borderColor, Color fillColor, Graphics g) {
g.setColor(fillColor);
g.fillOval(x + 85, y, 25, 20);
g.setColor(borderColor);
g.drawOval(x + 85, y, 25, 20);
}
}

View File

@ -0,0 +1,31 @@
package projectliner.Drawings;
import java.awt.*;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.Transferable;
import java.awt.datatransfer.UnsupportedFlavorException;
public class ColorTransferable implements Transferable {
public static DataFlavor colorFlavor = new DataFlavor(Color.class,
"A Color Object");
private Color color;
public ColorTransferable(Color color) {
this.color = color;
}
public DataFlavor[] getTransferDataFlavors() {
return new DataFlavor[]{colorFlavor};
}
public boolean isDataFlavorSupported(DataFlavor flavor) {
return flavor.equals(colorFlavor);
}
public Object getTransferData(DataFlavor flavor) throws UnsupportedFlavorException {
if (!isDataFlavorSupported(flavor)) {
throw new UnsupportedFlavorException(flavor);
}
return color;
}
}

View File

@ -0,0 +1,17 @@
package projectliner.Drawings;
public enum DeckEnum {
LOWER(1),
MIDDLE(2),
UPPER(3);
private final int deckNumber;
private DeckEnum(int deckNumber) {
this.deckNumber = deckNumber;
}
public int getDeckNumber() {
return this.deckNumber;
}
}

View File

@ -0,0 +1,13 @@
package projectliner.Drawings;
public enum DirectionType {
NONE,
UP,
DOWN,
LEFT,
RIGHT;
private DirectionType() {
}
}

View File

@ -0,0 +1,230 @@
package projectliner.Drawings;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Point;
import java.util.Arrays;
import projectliner.Entities.BaseLinerEntity;
public class DrawingBaseLiner {
private static final int DEFAULT_LINER_WIDTH = 140;
private static final int DEFAULT_LINER_HEIGHT = 40;
private static final int DECK_OFFSET_Y = 20;
protected BaseLinerEntity baseLiner;
protected Integer pictureWidth;
protected Integer pictureHeight;
protected Integer startPosX;
protected Integer startPosY;
private final int drawingLinerWidth;
private final int drawingLinerHeight;
private DrawingBaseLiner() {
this.drawingLinerWidth = DEFAULT_LINER_WIDTH;
this.drawingLinerHeight = DEFAULT_LINER_HEIGHT;
this.pictureWidth = null;
this.pictureHeight = null;
this.startPosX = null;
this.startPosY = null;
}
public DrawingBaseLiner(int speed, double weight, Color primaryColor, IAdditionalElements deck) {
this();
this.baseLiner = new BaseLinerEntity(speed, weight, primaryColor, deck);
}
public DrawingBaseLiner(BaseLinerEntity liner) {
this();
this.baseLiner = liner;
}
public DrawingBaseLiner(int drawingBaseLinerWidth, int drawingBaseLinerHeight) {
this.drawingLinerHeight = drawingBaseLinerHeight;
this.drawingLinerWidth = drawingBaseLinerWidth;
}
public DrawingBaseLiner(BaseLinerEntity liner, IAdditionalElements deck, int deckNum) {
this();
this.baseLiner = liner;
this.baseLiner.setDeck(deck);
this.baseLiner.getDeck().setNumericalValue(deckNum);
}
public boolean setPictureSize(int width, int height) {
if (this.drawingLinerWidth <= width && this.drawingLinerHeight <= height) {
this.pictureWidth = width;
this.pictureHeight = height;
return true;
} else {
return false;
}
}
public void setPosition(int x, int y) {
if (this.pictureHeight != null && this.pictureWidth != null) {
if (x < 0) {
x = 0;
} else if (x > this.pictureWidth - this.drawingLinerWidth) {
x = this.pictureWidth - this.drawingLinerWidth;
}
if (y < 0) {
y = 0;
} else if (y > this.pictureHeight - this.drawingLinerHeight) {
y = this.pictureHeight - this.drawingLinerHeight;
}
this.startPosX = x;
this.startPosY = y;
}
}
public boolean moveTransport(DirectionType direction) {
if (!isValidForMovement()) {
return false;
}
int step = (int) baseLiner.getStep();
switch (direction) {
case LEFT:
if ((double)this.startPosX - this.baseLiner.getStep() > (double)0.0F) {
this.startPosX = this.startPosX - step;
}
break;
case UP:
if ((double)this.startPosY - this.baseLiner.getStep() > (double)0.0F) {
this.startPosY = this.startPosY - step;
}
break;
case RIGHT:
if ((double)this.startPosX + this.baseLiner.getStep() < (double)(this.pictureWidth - this.drawingLinerWidth)) {
this.startPosX = this.startPosX + step;
}
break;
case DOWN:
if ((double)this.startPosY + this.baseLiner.getStep() < (double)(this.pictureHeight - this.drawingLinerHeight)) {
this.startPosY = this.startPosY + step;
}
break;
default:
return false;
}
return true;
}
private boolean isValidForMovement() {
return baseLiner != null && startPosX != null &&
startPosY != null && pictureWidth != null &&
pictureHeight != null;
}
public void setDeck(IAdditionalElements deck, int deckNum) {
this.baseLiner.setDeck(deck);
this.baseLiner.getDeck().setNumericalValue(deckNum);
}
private void initializeDefaultDeck() {
IAdditionalElements defaultDeck = new SquareDeckDrawing();
defaultDeck.setNumericalValue(1);
baseLiner.setDeck(defaultDeck);
}
public void drawTransport(Graphics g) {
if (!isValidForDrawing()) {
return;
}
Graphics2D g2d = (Graphics2D) g;
drawLinerBase(g2d);
drawDeck(g2d);
}
private boolean isValidForDrawing() {
return baseLiner != null && startPosX != null && startPosY != null;
}
public void drawLinerBase(Graphics g) {
Graphics2D g2d = (Graphics2D) g;
Point[] hullPoints = createHullPoints();
drawHull(g2d, hullPoints);
drawHullBorder(g2d, hullPoints);
}
private Point[] createHullPoints() {
return new Point[]{
new Point(startPosX + 20, startPosY + 40),
new Point(startPosX + 120, startPosY + 40),
new Point(startPosX + 140, startPosY + 10),
new Point(startPosX, startPosY + 10)
};
}
private void drawHull(Graphics2D g2d, Point[] points) {
g2d.setColor(baseLiner.getPrimaryColor());
g2d.fillPolygon(
extractXPoints(points),
extractYPoints(points),
points.length
);
}
private void drawHullBorder(Graphics2D g2d, Point[] points) {
g2d.setColor(Color.BLACK);
g2d.drawPolygon(
extractXPoints(points),
extractYPoints(points),
points.length
);
}
private int[] extractXPoints(Point[] points) {
return Arrays.stream(points).mapToInt(p -> p.x).toArray();
}
private int[] extractYPoints(Point[] points) {
return Arrays.stream(points).mapToInt(p -> p.y).toArray();
}
private void drawDeck(Graphics2D g2d) {
if (baseLiner.getDeck() == null) {
initializeDefaultDeck();
}
baseLiner.getDeck().drawAdditionalElement(
startPosX,
startPosY - DECK_OFFSET_Y,
Color.BLACK,
Color.WHITE,
g2d
);
}
public BaseLinerEntity getBaseLiner() {
return this.baseLiner;
}
public Integer getPosX() {
return this.startPosX;
}
public Integer getPosY() {
return this.startPosY;
}
public int getWidth() {
return this.drawingLinerWidth;
}
public int getHeight() {
return this.drawingLinerHeight;
}
public int getPictureWidth() {
return this.pictureWidth;
}
public int getPictureHeight() {
return this.pictureHeight;
}
}

View File

@ -0,0 +1,76 @@
package projectliner.Drawings;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import projectliner.Entities.BaseLinerEntity;
import projectliner.Entities.LinerEntity;
import projectliner.Entities.LinerEntityType;
import javax.swing.*;
public class DrawingLiner extends DrawingBaseLiner {
private static final int DEFAULT_WIDTH = 140;
private static final int DEFAULT_HEIGHT = 60;
public DrawingLiner(int speed, double weight,
Color primaryColor, Color secondaryColor,
IAdditionalElements deck,
LinerEntityType type, int capacity,
int maxPassengers, boolean hasExtraDeck, boolean hasPool) {
super(DEFAULT_WIDTH, DEFAULT_HEIGHT);
this.baseLiner = new LinerEntity(speed, weight, primaryColor,
secondaryColor, deck, type, capacity, maxPassengers, hasExtraDeck, hasPool);
}
public DrawingLiner(BaseLinerEntity liner, IAdditionalElements deck, int deckNum) {
super(140, 60);
this.baseLiner = liner;
this.baseLiner.setDeck(deck);
this.baseLiner.getDeck().setNumericalValue(deckNum);
}
public DrawingLiner(BaseLinerEntity liner) {
super(140, 60);
this.baseLiner = liner;
}
public BufferedImage drawTransport() {
BufferedImage image =
new BufferedImage(this.pictureWidth, this.pictureHeight, BufferedImage.TYPE_INT_ARGB);
Graphics g = image.getGraphics();
drawTransport(g);
return image;
}
public void drawTransport(Graphics g) {
if (this.baseLiner != null && this.startPosX != null && this.startPosY != null) {
int x = this.startPosX;
int y = this.startPosY;
Graphics2D g2d = (Graphics2D)g;
if (this.baseLiner instanceof LinerEntity linerEntity) {
this.startPosY = this.startPosY + 20;
super.drawLinerBase(g);
this.startPosY = this.startPosY - 20;
Color deckColor = linerEntity.getSecondaryColor();
Color borderColor = Color.BLACK;
if (!linerEntity.hasExtraDeck()) {
this.baseLiner.getDeck().setNumericalValue(1);
}
this.baseLiner.getDeck().drawAdditionalElement(x, y, borderColor, deckColor, g);
if (linerEntity.hasPool()) {
g2d.setColor(Color.CYAN);
g2d.fillOval(x + 35, y + 15, 30, 10);
g2d.setColor(Color.BLACK);
g2d.drawOval(x + 35, y + 15, 30, 10);
}
} else {
super.drawTransport(g);
}
}
}
}

View File

@ -0,0 +1,62 @@
package projectliner.Drawings;
import projectliner.Entities.BaseLinerEntity;
import projectliner.Entities.LinerEntity;
public class ExtensionDrawingLiner {
public static final String DELIMITER_FOR_OBJECT = ":";
private static final int MIN_DATA_LENGTH = 6;
private ExtensionDrawingLiner() {
// Private constructor to prevent instantiation
throw new UnsupportedOperationException("Utility class should not be instantiated");
}
public static DrawingBaseLiner createDrawingLiner(String info) {
if (info == null || info.isEmpty()) {
throw new IllegalArgumentException("Input string cannot be null or empty");
}
String[] str = info.split(DELIMITER_FOR_OBJECT);
if (str.length < MIN_DATA_LENGTH) {
throw new IllegalArgumentException("Invalid input format");
}
return createAppropriateDrawing(str);
}
private static DrawingBaseLiner createAppropriateDrawing(String[] data) {
DrawingBaseLiner result = tryCreateLinerDrawing(data);
if (result != null) {
return result;
}
result = tryCreateBaseLinerDrawing(data);
if (result != null) {
return result;
}
throw new IllegalArgumentException("Could not create drawing from provided data");
}
private static DrawingBaseLiner tryCreateLinerDrawing(String[] data) {
BaseLinerEntity liner = LinerEntity.createLinerEntityFromStr(data);
return liner != null ? new DrawingLiner(liner) : null;
}
private static DrawingBaseLiner tryCreateBaseLinerDrawing(String[] data) {
BaseLinerEntity liner = BaseLinerEntity.createBaseLinerEntityFromStr(data);
return liner != null ? new DrawingBaseLiner(liner) : null;
}
public static String getDataForSave(DrawingBaseLiner liner) {
String[] strings = liner.getBaseLiner().getStringRepresentation();
if (strings == null) {
return "";
}
return String.join(DELIMITER_FOR_OBJECT, strings);
}
}

View File

@ -0,0 +1,12 @@
package projectliner.Drawings;
import java.awt.Color;
import java.awt.Graphics;
public interface IAdditionalElements {
void setNumericalValue(int var1);
int getNumericalValue();
void drawAdditionalElement(int var1, int var2, Color var3, Color var4, Graphics var5);
}

View File

@ -0,0 +1,7 @@
package projectliner.Drawings;
import projectliner.Drawings.DrawingBaseLiner;
public interface ILinerDelegate {
void setLiner(DrawingBaseLiner liner);
}

View File

@ -0,0 +1,18 @@
package projectliner.Drawings;
import javax.swing.*;
import java.awt.datatransfer.StringSelection;
import java.awt.datatransfer.Transferable;
public class LabelTransferHandler extends TransferHandler {
@Override
protected Transferable createTransferable(JComponent c) {
JLabel label = (JLabel) c;
return new StringSelection(label.getText()); // Передаем текст метки
}
@Override
public int getSourceActions(JComponent c) {
return COPY;
}
}

View File

@ -0,0 +1,60 @@
package projectliner.Drawings;
import java.awt.Color;
import java.awt.Graphics;
public class SquareDeckDrawing implements IAdditionalElements {
private DeckEnum deckEnum;
public SquareDeckDrawing() {
}
public void setNumericalValue(int value) {
for(DeckEnum deck : DeckEnum.values()) {
if (deck.getDeckNumber() == value) {
this.deckEnum = deck;
return;
}
}
throw new IllegalArgumentException("Invalid deck number: " + value);
}
public int getNumericalValue() {
return this.deckEnum.getDeckNumber();
}
public void drawAdditionalElement(int x, int y, Color borderColor, Color fillColor, Graphics g) {
switch (this.deckEnum) {
case UPPER:
this.drawUpperDeck(x, y, borderColor, fillColor, g);
case MIDDLE:
this.drawMiddleDeck(x, y, borderColor, fillColor, g);
case LOWER:
this.drawLowerDeck(x, y, borderColor, fillColor, g);
default:
}
}
private void drawLowerDeck(int x, int y, Color borderColor, Color fillColor, Graphics g) {
g.setColor(fillColor);
g.fillRect(x + 30, y + 20, 100, 10);
g.setColor(borderColor);
g.drawRect(x + 30, y + 20, 100, 10);
}
private void drawMiddleDeck(int x, int y, Color borderColor, Color fillColor, Graphics g) {
g.setColor(fillColor);
g.fillRect(x + 70, y + 10, 50, 10);
g.setColor(borderColor);
g.drawRect(x + 70, y + 10, 50, 10);
}
private void drawUpperDeck(int x, int y, Color borderColor, Color fillColor, Graphics g) {
g.setColor(fillColor);
g.fillRect(x + 85, y, 25, 10);
g.setColor(borderColor);
g.drawRect(x + 85, y, 25, 10);
}
}

View File

@ -0,0 +1,66 @@
package projectliner.Drawings;
import java.awt.Color;
import java.awt.Graphics;
public class TriangularDeckDrawing implements IAdditionalElements {
private DeckEnum deckEnum;
public TriangularDeckDrawing() {
}
public void setNumericalValue(int value) {
for(DeckEnum deck : DeckEnum.values()) {
if (deck.getDeckNumber() == value) {
this.deckEnum = deck;
return;
}
}
throw new IllegalArgumentException("Invalid deck number: " + value);
}
public int getNumericalValue() {
return this.deckEnum.getDeckNumber();
}
public void drawAdditionalElement(int x, int y, Color borderColor, Color fillColor, Graphics g) {
switch (this.deckEnum) {
case UPPER:
this.drawUpperDeck(x, y, borderColor, fillColor, g);
case MIDDLE:
this.drawMiddleDeck(x, y, borderColor, fillColor, g);
case LOWER:
this.drawLowerDeck(x, y, borderColor, fillColor, g);
default:
}
}
private void drawLowerDeck(int x, int y, Color borderColor, Color fillColor, Graphics g) {
int[] xPoints = new int[]{x + 130, x + 130, x};
int[] yPoints = new int[]{y + 15, y + 30, y + 25};
g.setColor(fillColor);
g.fillPolygon(xPoints, yPoints, 3);
g.setColor(borderColor);
g.drawPolygon(xPoints, yPoints, 3);
}
private void drawMiddleDeck(int x, int y, Color borderColor, Color fillColor, Graphics g) {
int[] xPoints = new int[]{x + 120, x + 120, x + 60};
int[] yPoints = new int[]{y + 10, y + 20, y + 15};
g.setColor(fillColor);
g.fillPolygon(xPoints, yPoints, 3);
g.setColor(borderColor);
g.drawPolygon(xPoints, yPoints, 3);
}
private void drawUpperDeck(int x, int y, Color borderColor, Color fillColor, Graphics g) {
int[] xPoints = new int[]{x + 110, x + 110, x + 80};
int[] yPoints = new int[]{y + 5, y + 15, y + 10};
g.setColor(fillColor);
g.fillPolygon(xPoints, yPoints, 3);
g.setColor(borderColor);
g.drawPolygon(xPoints, yPoints, 3);
}
}

View File

@ -0,0 +1,131 @@
package projectliner.Entities;
import projectliner.Drawings.CircularDeckDrawing;
import projectliner.Drawings.IAdditionalElements;
import projectliner.Drawings.SquareDeckDrawing;
import projectliner.Drawings.TriangularDeckDrawing;
import java.awt.Color;
public class BaseLinerEntity {
private int speed;
private double weight;
private Color primaryColor;
private IAdditionalElements deck;
public BaseLinerEntity(int speed, double weight,
Color primaryColor, IAdditionalElements deck) {
this.speed = speed;
this.weight = weight;
this.primaryColor = primaryColor;
this.deck = deck;
}
public int getSpeed() {
return this.speed;
}
public double getWeight() {
return this.weight;
}
public Color getPrimaryColor() {
return this.primaryColor;
}
public double getStep() {
if (this.weight == 0) {
return 0.0;
}
return (double) this.speed / (this.weight / (double) 100.0F);
}
public void setSpeed(int speed) {
this.speed = speed;
}
public void setWeight(double weight) {
this.weight = weight;
}
public void setPrimaryColor(Color primaryColor) {
this.primaryColor = primaryColor;
}
public void setDeck(IAdditionalElements deck) {
this.deck = deck;
}
public IAdditionalElements getDeck() {
return this.deck;
}
public String[] getStringRepresentation() {
return new String[]{
this.getClass().getSimpleName(),
Integer.toString(this.speed),
Double.toString(this.weight),
Integer.toHexString(this.primaryColor.getRGB()),
this.deck.getClass().getSimpleName(),
Integer.toString(this.deck.getNumericalValue())
};
}
public static BaseLinerEntity createBaseLinerEntityFromStr(String[] str) {
if (!isValidInput(str)) {
return null;
}
try {
int speed = Integer.parseInt(str[1]);
double weight = Double.parseDouble(str[2]);
Color color = decodeColor(str[3]);
IAdditionalElements deck = createDeck(str[4], str[5]);
return new BaseLinerEntity(speed, weight, color, deck);
} catch (IllegalArgumentException e) {
return null;
}
}
private static boolean isValidInput(String[] str) {
return str != null && str.length == 6;
}
protected static IAdditionalElements createDeck(String deckType, String deckNumStr) {
IAdditionalElements deck = switch (deckType) {
case "SquareDeckDrawing" -> new SquareDeckDrawing();
case "CircularDeckDrawing" -> new CircularDeckDrawing();
case "TriangularDeckDrawing" -> new TriangularDeckDrawing();
default -> null;
};
if (deck == null) {
throw new IllegalArgumentException("Invalid deck type");
}
int deckNum = Integer.parseInt(deckNumStr);
deck.setNumericalValue(deckNum);
return deck;
}
public static Color decodeColor(String colorStr) {
if (colorStr == null || (colorStr.length() != 8 && colorStr.length() != 6)) {
throw new IllegalArgumentException("Invalid color string format");
}
try {
if (colorStr.length() == 8) {
// ARGB format
int alpha = Integer.parseInt(colorStr.substring(0, 2), 16);
int rgb = Integer.parseInt(colorStr.substring(2), 16);
return new Color((rgb >> 16) & 0xFF, (rgb >> 8) & 0xFF, rgb & 0xFF, alpha);
} else {
// RGB format
return Color.decode("#" + colorStr);
}
} catch (NumberFormatException e) {
throw new IllegalArgumentException("Invalid color value", e);
}
}
}

View File

@ -0,0 +1,131 @@
package projectliner.Entities;
import projectliner.Drawings.CircularDeckDrawing;
import projectliner.Drawings.IAdditionalElements;
import projectliner.Drawings.SquareDeckDrawing;
import projectliner.Drawings.TriangularDeckDrawing;
import java.awt.Color;
public class LinerEntity extends BaseLinerEntity {
private Color secondaryColor;
private LinerEntityType type;
private int capacity;
private int maxPassengers;
private boolean hasExtraDeck;
private boolean hasPool;
public LinerEntity(int speed, double weight,
Color primaryColor, Color secondaryColor,
IAdditionalElements deck,
LinerEntityType type, int capacity, int maxPassengers,
boolean hasExtraDeck, boolean hasPool) {
super(speed, weight, primaryColor, deck);
this.secondaryColor = secondaryColor;
this.type = type;
this.capacity = capacity;
this.maxPassengers = maxPassengers;
this.hasExtraDeck = hasExtraDeck;
this.hasPool = hasPool;
}
public Color getSecondaryColor() {
return this.secondaryColor;
}
public LinerEntityType getType() {
return this.type;
}
public int getCapacity() {
return this.capacity;
}
public int getMaxPassengers() {
return this.maxPassengers;
}
public boolean hasExtraDeck() {
return this.hasExtraDeck;
}
public boolean hasPool() {
return this.hasPool;
}
public void setCapacity(int capacity) {
this.capacity = capacity;
}
public void setMaxPassengers(int maxPassengers) {
this.maxPassengers = maxPassengers;
}
public void setExtraDeck(boolean extraDeck) {
this.hasExtraDeck = extraDeck;
}
public void setPool(boolean pool) {
this.hasPool = pool;
}
public void setSecondaryColor(Color secondaryColor) {
this.secondaryColor = secondaryColor;
}
public void setType(LinerEntityType type) {
this.type = type;
}
@Override
public String[] getStringRepresentation() {
String[] baseRepresentation = super.getStringRepresentation();
baseRepresentation[0] = this.getClass().getSimpleName();
String[] derivedRepresentation = new String[] {
Integer.toHexString(this.secondaryColor.getRGB()),
this.type.toString(),
Integer.toString(this.capacity),
Integer.toString(this.maxPassengers),
Boolean.toString(this.hasExtraDeck),
Boolean.toString(this.hasPool)
};
String[] fullRepresentation =
new String[baseRepresentation.length + derivedRepresentation.length];
System.arraycopy(baseRepresentation, 0, fullRepresentation,
0, baseRepresentation.length);
System.arraycopy(derivedRepresentation, 0, fullRepresentation,
baseRepresentation.length, derivedRepresentation.length);
return fullRepresentation;
}
public static LinerEntity createLinerEntityFromStr(String[] str) {
if (!isValidInput(str)) {
return null;
}
try {
int speed = Integer.parseInt(str[1]);
double weight = Double.parseDouble(str[2]);
Color primaryColor = decodeColor(str[3]);
IAdditionalElements deck = createDeck(str[4], str[5]);
Color secondaryColor = decodeColor(str[6]);
LinerEntityType type = LinerEntityType.valueOf(str[7]);
int capacity = Integer.parseInt(str[8]);
int maxPassengers = Integer.parseInt(str[9]);
boolean hasExtraDeck = Boolean.parseBoolean(str[10]);
boolean hasPool = Boolean.parseBoolean(str[11]);
return new LinerEntity(speed, weight, primaryColor, secondaryColor, deck,
type, capacity, maxPassengers, hasExtraDeck, hasPool);
} catch (IllegalArgumentException e) {
return null;
}
}
private static boolean isValidInput(String[] str) {
return str != null && str.length == 12;
}
}

View File

@ -0,0 +1,8 @@
package projectliner.Entities;
public enum LinerEntityType {
PASSENGER,
CARGO,
MILITARY,
MIXED
}

View File

@ -0,0 +1,195 @@
package projectliner;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.image.BufferedImage;
import java.net.URL;
import java.util.Random;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLayeredPane;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.Timer;
import projectliner.Drawings.DirectionType;
import projectliner.Drawings.DrawingBaseLiner;
import projectliner.Drawings.DrawingLiner;
import projectliner.Entities.LinerEntityType;
import projectliner.MovementStrategy.AbstractStrategy;
import projectliner.MovementStrategy.MoveToBorder;
import projectliner.MovementStrategy.MoveToCenter;
import projectliner.MovementStrategy.MoveableLiner;
import projectliner.MovementStrategy.StrategyStatus;
public class FormLiner extends JFrame {
private DrawingBaseLiner drawingLiner;
private JPanel pictureBoxLiner;
private Timer moveTimer;
private DirectionType currentDirection;
private JComboBox<String> comboBoxStrategy;
private AbstractStrategy strategy;
public FormLiner() {
this.initializeComponent();
this.strategy = null;
this.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
}
private void initializeComponent() {
JLayeredPane layeredPane = new JLayeredPane();
layeredPane.setPreferredSize(new Dimension(900, 500));
this.add(layeredPane, "Center");
this.pictureBoxLiner = new JPanel() {
protected void paintComponent(Graphics g) {
super.paintComponent(g);
if (FormLiner.this.drawingLiner != null) {
FormLiner.this.drawingLiner.drawTransport(g);
}
}
};
this.pictureBoxLiner.setBounds(0, 0, 900, 500);
layeredPane.add(this.pictureBoxLiner, JLayeredPane.DEFAULT_LAYER);
String[] options = new String[]{"", "To Center", "To Border"};
this.comboBoxStrategy = new JComboBox(options);
this.comboBoxStrategy.setBounds(800, 10, 100, 30);
this.comboBoxStrategy.setEnabled(false);
this.comboBoxStrategy.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String selected = (String)FormLiner.this.comboBoxStrategy.getSelectedItem();
System.out.println(selected);
}
});
layeredPane.add(this.comboBoxStrategy, JLayeredPane.PALETTE_LAYER);
JButton buttonStrategyStep = new JButton("Step");
buttonStrategyStep.setBounds(830, 50, 70, 30);
buttonStrategyStep.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
FormLiner.this.buttonStrategyStep_Click(e);
}
});
layeredPane.add(buttonStrategyStep, JLayeredPane.PALETTE_LAYER);
URL upIconURL = this.getClass().getClassLoader().getResource("icons8-arrow-up-60.png");
URL downIconURL = this.getClass().getClassLoader().getResource("icons8-arrow-down-60.png");
URL leftIconURL = this.getClass().getClassLoader().getResource("icons8-arrow-left-60.png");
URL rightIconURL = this.getClass().getClassLoader().getResource("icons8-arrow-right-60.png");
ImageIcon upIcon = new ImageIcon(upIconURL);
ImageIcon downIcon = new ImageIcon(downIconURL);
ImageIcon leftIcon = new ImageIcon(leftIconURL);
ImageIcon rightIcon = new ImageIcon(rightIconURL);
JButton buttonMoveUp = new JButton(upIcon);
buttonMoveUp.setBounds(660, 440, 60, 60);
buttonMoveUp.setName("buttonMoveUp");
this.addMoveButtonListeners(buttonMoveUp, DirectionType.UP);
layeredPane.add(buttonMoveUp, JLayeredPane.PALETTE_LAYER);
JButton buttonMoveDown = new JButton(downIcon);
buttonMoveDown.setBounds(720, 440, 60, 60);
buttonMoveDown.setName("buttonMoveDown");
this.addMoveButtonListeners(buttonMoveDown, DirectionType.DOWN);
layeredPane.add(buttonMoveDown, JLayeredPane.PALETTE_LAYER);
JButton buttonMoveLeft = new JButton(leftIcon);
buttonMoveLeft.setBounds(780, 440, 60, 60);
buttonMoveLeft.setName("buttonMoveLeft");
this.addMoveButtonListeners(buttonMoveLeft, DirectionType.LEFT);
layeredPane.add(buttonMoveLeft, JLayeredPane.PALETTE_LAYER);
JButton buttonMoveRight = new JButton(rightIcon);
buttonMoveRight.setBounds(840, 440, 60, 60);
buttonMoveRight.setName("buttonMoveRight");
this.addMoveButtonListeners(buttonMoveRight, DirectionType.RIGHT);
layeredPane.add(buttonMoveRight, JLayeredPane.PALETTE_LAYER);
this.moveTimer = new Timer(100, new ActionListener() {
public void actionPerformed(ActionEvent e) {
FormLiner.this.moveTransport(FormLiner.this.currentDirection);
}
});
this.pack();
this.setDefaultCloseOperation(3);
this.setVisible(true);
}
private void addMoveButtonListeners(JButton button, final DirectionType direction) {
button.addMouseListener(new MouseAdapter() {
public void mousePressed(MouseEvent e) {
FormLiner.this.currentDirection = direction;
FormLiner.this.moveTimer.start();
}
public void mouseReleased(MouseEvent e) {
FormLiner.this.moveTimer.stop();
}
});
}
private void draw() {
if (this.drawingLiner != null) {
BufferedImage bitmap = new BufferedImage(this.pictureBoxLiner.getWidth(),
this.pictureBoxLiner.getHeight(), 2);
Graphics graphics = bitmap.getGraphics();
graphics.setColor(this.pictureBoxLiner.getBackground());
graphics.fillRect(0, 0, bitmap.getWidth(), bitmap.getHeight());
this.drawingLiner.drawTransport(graphics);
this.pictureBoxLiner.repaint();
}
}
private void moveTransport(DirectionType direction) {
if (this.drawingLiner != null) {
boolean var10000;
switch (direction) {
case UP -> var10000 = this.drawingLiner.moveTransport(DirectionType.UP);
case DOWN -> var10000 = this.drawingLiner.moveTransport(DirectionType.DOWN);
case LEFT -> var10000 = this.drawingLiner.moveTransport(DirectionType.LEFT);
case RIGHT -> var10000 = this.drawingLiner.moveTransport(DirectionType.RIGHT);
case NONE -> var10000 = false;
default -> throw new MatchException((String)null, (Throwable)null);
}
boolean result = var10000;
if (result) {
this.draw();
}
}
}
private void buttonStrategyStep_Click(ActionEvent e) {
if (this.drawingLiner != null) {
if (this.comboBoxStrategy.isEnabled() &&
this.comboBoxStrategy.getSelectedIndex() == 1) {
this.strategy = new MoveToCenter();
} else if (this.comboBoxStrategy.isEnabled() &&
this.comboBoxStrategy.getSelectedIndex() == 2) {
this.strategy = new MoveToBorder();
}
this.strategy.setData(new MoveableLiner(this.drawingLiner), 900, 500);
this.comboBoxStrategy.setSelectedIndex(0);
this.comboBoxStrategy.setEnabled(false);
this.strategy.makeStep();
this.draw();
if (this.strategy.getStatus() == StrategyStatus.FINISHED) {
this.comboBoxStrategy.setEnabled(true);
this.strategy = null;
}
}
}
public void setLiner(DrawingBaseLiner liner) {
this.drawingLiner = liner;
drawingLiner.setPosition(0, 0);
drawingLiner.setPictureSize(pictureBoxLiner.getWidth(), pictureBoxLiner.getHeight());
comboBoxStrategy.setEnabled(true);
strategy = null;
draw();
}
}

View File

@ -0,0 +1,548 @@
package projectliner;
import projectliner.Drawings.*;
import projectliner.Entities.LinerEntity;
import projectliner.Entities.LinerEntityType;
import javax.swing.*;
import javax.swing.border.EmptyBorder;
import javax.swing.border.LineBorder;
import java.awt.*;
import java.awt.event.*;
import java.awt.dnd.*;
import java.awt.datatransfer.*;
import java.awt.image.BufferedImage;
public class FormLinerConfig extends JFrame {
private DrawingBaseLiner liner;
private ILinerDelegate linerDelegate;
private IAdditionalElements deck;
private ColorTransferable colorTransferable;
private JButton buttonCancel;
private JButton buttonAdd;
private JPanel panelRed, panelGreen, panelBlue, panelYellow,
panelWhite, panelGray, panelBlack, panelPurple;
private JLabel labelPrimaryColor, labelSecondaryColor;
private JComboBox<String> comboBoxLinerType;
private JCheckBox checkBoxExtraDeck, checkBoxPool;
private JSpinner numericUpDownSpeed, numericUpDownWeight,
numericUpDownCapacity, numericUpDownMaxPassengers,
numericUpDownDeckNum;
private JLabel pictureBoxLiner;
public FormLinerConfig() {
initComponents();
buttonCancel.addActionListener(e -> dispose());
addMouseListenersToPanels();
}
public void setLinerDelegate(ILinerDelegate linerDelegate) {
this.linerDelegate = linerDelegate;
}
private void drawObject() {
BufferedImage bmp = new BufferedImage(pictureBoxLiner.getWidth(),
pictureBoxLiner.getHeight(), BufferedImage.TYPE_INT_ARGB);
Graphics2D gr = bmp.createGraphics();
if (liner != null) {
if (liner instanceof DrawingLiner drawingLiner) {
drawingLiner.setPictureSize(pictureBoxLiner.getWidth(), pictureBoxLiner.getHeight());
drawingLiner.setPosition(15, 15);
drawingLiner.drawTransport(gr);
} else {
liner.setPictureSize(pictureBoxLiner.getWidth(), pictureBoxLiner.getHeight());
liner.setPosition(15, 15);
liner.drawTransport(gr);
}
}
pictureBoxLiner.setIcon(new ImageIcon(bmp));
pictureBoxLiner.revalidate();
pictureBoxLiner.repaint();
}
private void addMouseListenersToPanels() {
panelRed.addMouseListener(new MouseAdapter() {
public void mousePressed(MouseEvent e) {
panelMouseDown(panelRed);
}
});
panelGreen.addMouseListener(new MouseAdapter() {
public void mousePressed(MouseEvent e) {
panelMouseDown(panelGreen);
}
});
panelBlue.addMouseListener(new MouseAdapter() {
public void mousePressed(MouseEvent e) {
panelMouseDown(panelBlue);
}
});
panelYellow.addMouseListener(new MouseAdapter() {
public void mousePressed(MouseEvent e) {
panelMouseDown(panelYellow);
}
});
panelWhite.addMouseListener(new MouseAdapter() {
public void mousePressed(MouseEvent e) {
panelMouseDown(panelWhite);
}
});
panelGray.addMouseListener(new MouseAdapter() {
public void mousePressed(MouseEvent e) {
panelMouseDown(panelGray);
}
});
panelBlack.addMouseListener(new MouseAdapter() {
public void mousePressed(MouseEvent e) {
panelMouseDown(panelBlack);
}
});
panelPurple.addMouseListener(new MouseAdapter() {
public void mousePressed(MouseEvent e) {
panelMouseDown(panelPurple);
}
});
}
private void labelObjectMouseDown(MouseEvent e) {
JLabel label = (JLabel) e.getSource();
TransferHandler handler = label.getTransferHandler();
if (handler != null) {
handler.exportAsDrag(label, e, TransferHandler.COPY);
}
}
private void panelObjectDragEnter(DropTargetDragEvent e) {
if (e.isDataFlavorSupported(DataFlavor.stringFlavor) || e.isDataFlavorSupported(AdditionalElementsTransferable.additionalElementsFlavor)) {
e.acceptDrag(DnDConstants.ACTION_COPY);
} else {
e.rejectDrag();
}
}
private void panelObjectDragDrop(DropTargetDropEvent e) {
try {
e.acceptDrop(DnDConstants.ACTION_COPY);
String data = (String) e.getTransferable().getTransferData(DataFlavor.stringFlavor);
IAdditionalElements deck = new SquareDeckDrawing();
deck.setNumericalValue(1);
switch (data) {
case "Basic Object":
liner = new DrawingBaseLiner((int) numericUpDownSpeed.getValue(),
((Integer) numericUpDownWeight.getValue()).doubleValue() , Color.WHITE, deck);
break;
case "Advanced Object":
deck.setNumericalValue((int) numericUpDownDeckNum.getValue());
liner = new DrawingLiner((int) numericUpDownSpeed.getValue(), ((Integer) numericUpDownWeight.getValue()).doubleValue(),
Color.WHITE, Color.BLACK, deck, LinerEntityType.values()[comboBoxLinerType.getSelectedIndex()],
(int) numericUpDownCapacity.getValue(), (int) numericUpDownMaxPassengers.getValue(),
checkBoxExtraDeck.isSelected(), checkBoxPool.isSelected());
break;
}
drawObject();
e.dropComplete(true);
} catch (Exception ex) {
ex.printStackTrace();
e.dropComplete(false);
}
}
private void panelObjectDropAdditionalElements(DropTargetDropEvent e) {
try {
e.acceptDrop(DnDConstants.ACTION_COPY);
IAdditionalElements deck = (IAdditionalElements) e.getTransferable().getTransferData(AdditionalElementsTransferable.additionalElementsFlavor);
if (deck != null) {
liner.setDeck(deck, (int) numericUpDownDeckNum.getValue());
drawObject();
e.dropComplete(true);
} else {
e.dropComplete(false);
}
} catch (Exception ex) {
ex.printStackTrace();
e.dropComplete(false);
}
}
private void panelMouseDown(JPanel panel) {
Color color = panel.getBackground();
Transferable transferable = new ColorTransferable(color);
DragSource ds = new DragSource();
ds.createDefaultDragGestureRecognizer(panel, DnDConstants.ACTION_COPY, new DragGestureListener() {
public void dragGestureRecognized(DragGestureEvent dge) {
ds.startDrag(dge, DragSource.DefaultCopyDrop, transferable, new DragSourceAdapter() {});
}
});
}
private void labelColorDragEnter(DropTargetDragEvent e) {
if (e.isDataFlavorSupported(ColorTransferable.colorFlavor)) {
e.acceptDrag(DnDConstants.ACTION_COPY);
} else {
e.rejectDrag();
}
}
private void labelColorDragDrop(DropTargetDropEvent e) {
try {
e.acceptDrop(DnDConstants.ACTION_COPY);
Color color = (Color) e.getTransferable().getTransferData(ColorTransferable.colorFlavor);
if (e.getDropTargetContext().getComponent() == labelPrimaryColor) {
liner.getBaseLiner().setPrimaryColor(color);
} else if (e.getDropTargetContext().getComponent() == labelSecondaryColor) {
if (liner instanceof DrawingLiner drawingLiner) {
if (drawingLiner.getBaseLiner() instanceof LinerEntity linerEntity) {
linerEntity.setSecondaryColor(color);
}
}
}
drawObject();
e.dropComplete(true);
} catch (Exception ex) {
ex.printStackTrace();
e.dropComplete(false);
}
}
private void initComponents() {
setTitle("FormLinerConfig");
setSize(800, 300);
setLayout(new BorderLayout());
numericUpDownSpeed = new JSpinner(new SpinnerNumberModel(100,
0, 1000, 1));
numericUpDownSpeed.setMaximumSize(new Dimension(100, 20));
numericUpDownWeight = new JSpinner(new SpinnerNumberModel(100,
0, 1000, 1));
numericUpDownWeight.setMaximumSize(new Dimension(100, 20));
numericUpDownCapacity = new JSpinner(new SpinnerNumberModel(100,
0, 1000, 1));
numericUpDownCapacity.setMaximumSize(new Dimension(100, 20));
numericUpDownMaxPassengers = new JSpinner(new SpinnerNumberModel(100,
0, 1000, 1));
numericUpDownMaxPassengers.setMaximumSize(new Dimension(100, 20));
numericUpDownDeckNum = new JSpinner(new SpinnerNumberModel(1,
1, 3, 1));
numericUpDownDeckNum.setMaximumSize(new Dimension(100, 20));
comboBoxLinerType = new JComboBox<>(new String[]{"Passenger", "Cargo", "Military", "Mixed"});
comboBoxLinerType.setMaximumSize(new Dimension(100, 20));
checkBoxExtraDeck = new JCheckBox("Extra Deck feature");
checkBoxPool = new JCheckBox("Pool feature");
JPanel panelParameters = new JPanel();
panelParameters.setLayout(new BoxLayout(panelParameters, BoxLayout.Y_AXIS));
panelParameters.setMaximumSize(new Dimension(500, 260));
panelParameters.setBorder(new EmptyBorder(10, 10, 10, 10));
JLabel labelParameters = new JLabel("Parameters");
labelParameters.setAlignmentX(Component.CENTER_ALIGNMENT);
JPanel panelParametersLabels = new JPanel();
panelParametersLabels.setLayout(new BoxLayout(panelParametersLabels, BoxLayout.Y_AXIS));
panelParametersLabels.setMaximumSize(new Dimension(200, 200));
panelParametersLabels.add(new JLabel("Type of Liner"));
panelParametersLabels.add(Box.createVerticalStrut(10));
panelParametersLabels.add(new JLabel("Speed"));
panelParametersLabels.add(Box.createVerticalStrut(10));
panelParametersLabels.add(new JLabel("Weight"));
panelParametersLabels.add(Box.createVerticalStrut(10));
panelParametersLabels.add(new JLabel("Capacity"));
panelParametersLabels.add(Box.createVerticalStrut(10));
panelParametersLabels.add(new JLabel("Max Passengers"));
panelParametersLabels.add(Box.createVerticalStrut(10));
panelParametersLabels.add(new JLabel("Deck Number"));
JPanel panelParametersValues = new JPanel();
panelParametersValues.setLayout(new BoxLayout(panelParametersValues, BoxLayout.Y_AXIS));
panelParametersValues.setMaximumSize(new Dimension(200, 200));
panelParametersValues.add(comboBoxLinerType);
panelParametersValues.add(Box.createVerticalStrut(5));
panelParametersValues.add(numericUpDownSpeed);
panelParametersValues.add(Box.createVerticalStrut(5));
panelParametersValues.add(numericUpDownWeight);
panelParametersValues.add(Box.createVerticalStrut(5));
panelParametersValues.add(numericUpDownCapacity);
panelParametersValues.add(Box.createVerticalStrut(5));
panelParametersValues.add(numericUpDownMaxPassengers);
panelParametersValues.add(Box.createVerticalStrut(5));
panelParametersValues.add(numericUpDownDeckNum);
JPanel panelCheckBoxes = new JPanel();
panelCheckBoxes.setLayout(new BoxLayout(panelCheckBoxes, BoxLayout.X_AXIS));
panelCheckBoxes.setMaximumSize(new Dimension(300, 40));
panelCheckBoxes.add(checkBoxExtraDeck);
panelCheckBoxes.add(checkBoxPool);
JPanel panelAllParameters = new JPanel();
panelAllParameters.setLayout(new BoxLayout(panelAllParameters, BoxLayout.X_AXIS));
panelAllParameters.add(panelParametersLabels);
panelAllParameters.add(Box.createHorizontalStrut(10));
panelAllParameters.add(panelParametersValues);
panelParameters.add(labelParameters);
panelParameters.add(Box.createVerticalStrut(10));
panelParameters.add(panelAllParameters);
panelParameters.add(Box.createVerticalStrut(10));
panelParameters.add(panelCheckBoxes);
add(panelParameters, BorderLayout.WEST);
JPanel middlePanel = new JPanel();
middlePanel.setLayout(new BoxLayout(middlePanel, BoxLayout.Y_AXIS));
middlePanel.setMaximumSize(new Dimension(200, 200));
middlePanel.setBorder(new EmptyBorder(10, 10, 10, 10));
JLabel labelColors = new JLabel("Colors");
labelColors.setAlignmentX(Component.CENTER_ALIGNMENT);
JPanel panelColorsUp = new JPanel();
panelColorsUp.setLayout(new BoxLayout(panelColorsUp, BoxLayout.X_AXIS));
JPanel panelColorsDown = new JPanel();
panelColorsDown.setLayout(new BoxLayout(panelColorsDown, BoxLayout.X_AXIS));
panelRed = createColorPanel(Color.RED);
panelGreen = createColorPanel(Color.GREEN);
panelBlue = createColorPanel(Color.BLUE);
panelYellow = createColorPanel(Color.YELLOW);
panelWhite = createColorPanel(Color.WHITE);
panelGray = createColorPanel(Color.GRAY);
panelBlack = createColorPanel(Color.BLACK);
panelPurple = createColorPanel(Color.MAGENTA);
panelColorsUp.add(panelRed);
panelColorsUp.add(Box.createHorizontalStrut(10));
panelColorsUp.add(panelGreen);
panelColorsUp.add(Box.createHorizontalStrut(10));
panelColorsUp.add(panelBlue);
panelColorsUp.add(Box.createHorizontalStrut(10));
panelColorsUp.add(panelYellow);
panelColorsDown.add(panelWhite);
panelColorsDown.add(Box.createHorizontalStrut(10));
panelColorsDown.add(panelGray);
panelColorsDown.add(Box.createHorizontalStrut(10));
panelColorsDown.add(panelBlack);
panelColorsDown.add(Box.createHorizontalStrut(10));
panelColorsDown.add(panelPurple);
JLabel labelBasicObject = new JLabel("Basic Object");
labelBasicObject.setHorizontalAlignment(SwingConstants.CENTER);
labelBasicObject.setMaximumSize(new Dimension(200, 40));
labelBasicObject.setBorder(new LineBorder(Color.BLACK));
labelBasicObject.setTransferHandler(new LabelTransferHandler());
labelBasicObject.addMouseListener(new MouseAdapter() {
public void mousePressed(MouseEvent e) {
labelObjectMouseDown(e);
}
});
JLabel labelAdvancedObject = new JLabel("Advanced Object");
labelAdvancedObject.setHorizontalAlignment(SwingConstants.CENTER);
labelAdvancedObject.setMaximumSize(new Dimension(200, 40));
labelAdvancedObject.setBorder(new LineBorder(Color.BLACK));
labelAdvancedObject.setTransferHandler(new LabelTransferHandler());
labelAdvancedObject.addMouseListener(new MouseAdapter() {
public void mousePressed(MouseEvent e) {
labelObjectMouseDown(e);
}
});
JLabel labelSquareDeck = new JLabel("Square Deck");
labelSquareDeck.setHorizontalAlignment(SwingConstants.CENTER);
labelSquareDeck.setMaximumSize(new Dimension(200, 20));
labelSquareDeck.setBorder(new LineBorder(Color.BLACK));
labelSquareDeck.setTransferHandler(new AdditionalElementsTransferHandler(new SquareDeckDrawing()));
labelSquareDeck.addMouseListener(new MouseAdapter() {
public void mousePressed(MouseEvent e) {
labelObjectMouseDown(e);
}
});
JLabel labelCircularDeck = new JLabel("Circular Deck");
labelCircularDeck.setHorizontalAlignment(SwingConstants.CENTER);
labelCircularDeck.setMaximumSize(new Dimension(200, 20));
labelCircularDeck.setBorder(new LineBorder(Color.BLACK));
labelCircularDeck.setTransferHandler(new AdditionalElementsTransferHandler(new CircularDeckDrawing()));
labelCircularDeck.addMouseListener(new MouseAdapter() {
public void mousePressed(MouseEvent e) {
labelObjectMouseDown(e);
}
});
JLabel labelTriangularDeck = new JLabel("Triangular Deck");
labelTriangularDeck.setHorizontalAlignment(SwingConstants.CENTER);
labelTriangularDeck.setMaximumSize(new Dimension(200, 20));
labelTriangularDeck.setBorder(new LineBorder(Color.BLACK));
labelTriangularDeck.setTransferHandler(new AdditionalElementsTransferHandler(new TriangularDeckDrawing()));
labelTriangularDeck.addMouseListener(new MouseAdapter() {
public void mousePressed(MouseEvent e) {
labelObjectMouseDown(e);
}
});
JPanel additionalElements = new JPanel();
additionalElements.setLayout(new BoxLayout(additionalElements, BoxLayout.X_AXIS));
additionalElements.add(labelSquareDeck);
additionalElements.add(Box.createHorizontalStrut(10));
additionalElements.add(labelCircularDeck);
additionalElements.add(Box.createHorizontalStrut(10));
additionalElements.add(labelTriangularDeck);
JPanel objectEntities = new JPanel();
objectEntities.setLayout(new BoxLayout(objectEntities, BoxLayout.X_AXIS));
objectEntities.add(labelBasicObject);
objectEntities.add(Box.createHorizontalStrut(10));
objectEntities.add(labelAdvancedObject);
middlePanel.add(labelColors);
middlePanel.add(Box.createVerticalStrut(10));
middlePanel.add(panelColorsUp);
middlePanel.add(Box.createVerticalStrut(10));
middlePanel.add(panelColorsDown);
middlePanel.add(Box.createVerticalStrut(10));
middlePanel.add(objectEntities);
middlePanel.add(Box.createVerticalStrut(10));
middlePanel.add(additionalElements);
add(middlePanel, BorderLayout.CENTER);
JPanel panelObject = new JPanel();
panelObject.setLayout(new BoxLayout(panelObject, BoxLayout.Y_AXIS));
panelObject.setMaximumSize(new Dimension(200, 300));
panelObject.setBorder(new EmptyBorder(10, 10, 10, 10));
labelPrimaryColor = new JLabel("Primary Color");
labelPrimaryColor.setMaximumSize(new Dimension(200, 40));
labelPrimaryColor.setHorizontalAlignment(SwingConstants.CENTER);
labelPrimaryColor.setBorder(new LineBorder(Color.BLACK));
labelPrimaryColor.setTransferHandler(new TransferHandler("background"));
labelSecondaryColor = new JLabel("Secondary Color");
labelSecondaryColor.setMaximumSize(new Dimension(200, 40));
labelSecondaryColor.setHorizontalAlignment(SwingConstants.CENTER);
labelSecondaryColor.setBorder(new LineBorder(Color.BLACK));
labelSecondaryColor.setTransferHandler(new TransferHandler("background"));
JPanel colorLabels = new JPanel();
colorLabels.setLayout(new BoxLayout(colorLabels, BoxLayout.X_AXIS));
colorLabels.add(labelPrimaryColor);
colorLabels.add(Box.createHorizontalStrut(10));
colorLabels.add(labelSecondaryColor);
pictureBoxLiner = new JLabel();
pictureBoxLiner.setMaximumSize(new Dimension(200, 150));
pictureBoxLiner.setPreferredSize(new Dimension(200, 150));
pictureBoxLiner.setMinimumSize(new Dimension(200, 150));
pictureBoxLiner.setAlignmentX(Component.CENTER_ALIGNMENT);
JPanel panelButtons = new JPanel();
panelButtons.setLayout(new BoxLayout(panelButtons, BoxLayout.X_AXIS));
buttonAdd = new JButton("Add");
buttonAdd.addActionListener(e -> buttonAddClick());
buttonCancel = new JButton("Cancel");
panelButtons.add(buttonAdd);
panelButtons.add(Box.createHorizontalStrut(10));
panelButtons.add(buttonCancel);
panelObject.add(colorLabels);
panelObject.add(Box.createVerticalStrut(10));
panelObject.add(pictureBoxLiner);
panelObject.add(Box.createVerticalStrut(10));
panelObject.add(panelButtons);
new DropTarget(panelObject, new DropTargetAdapter() {
public void dragEnter(DropTargetDragEvent e) {
panelObjectDragEnter(e);
}
public void dragOver(DropTargetDragEvent e) {
panelObjectDragEnter(e);
}
public void drop(DropTargetDropEvent e) {
try {
if (e.isDataFlavorSupported(DataFlavor.stringFlavor)) {
panelObjectDragDrop(e);
} else if (e.isDataFlavorSupported(AdditionalElementsTransferable.additionalElementsFlavor)) {
panelObjectDropAdditionalElements(e);
} else {
e.rejectDrop();
}
} catch (Exception ex) {
ex.printStackTrace();
e.dropComplete(false);
}
}
});
new DropTarget(labelPrimaryColor, new DropTargetAdapter() {
public void dragEnter(DropTargetDragEvent e) {
labelColorDragEnter(e);
}
public void dragOver(DropTargetDragEvent e) {
labelColorDragEnter(e);
}
public void drop(DropTargetDropEvent e) {
labelColorDragDrop(e);
}
});
new DropTarget(labelSecondaryColor, new DropTargetAdapter() {
public void dragEnter(DropTargetDragEvent e) {
labelColorDragEnter(e);
}
public void dragOver(DropTargetDragEvent e) {
labelColorDragEnter(e);
}
public void drop(DropTargetDropEvent e) {
labelColorDragDrop(e);
}
});
numericUpDownSpeed.addChangeListener(e -> updateLinerParameters());
numericUpDownWeight.addChangeListener(e -> updateLinerParameters());
numericUpDownCapacity.addChangeListener(e -> updateLinerParameters());
numericUpDownMaxPassengers.addChangeListener(e -> updateLinerParameters());
numericUpDownDeckNum.addChangeListener(e -> updateLinerParameters());
comboBoxLinerType.addItemListener(e -> updateLinerParameters());
checkBoxExtraDeck.addItemListener(e -> updateLinerParameters());
checkBoxPool.addItemListener(e -> updateLinerParameters());
add(panelObject, BorderLayout.EAST);
}
private void updateLinerParameters() {
if (liner != null) {
liner.getBaseLiner().setSpeed((int) numericUpDownSpeed.getValue());
liner.getBaseLiner().setWeight(((Integer) numericUpDownWeight.getValue()).doubleValue());
if (liner instanceof DrawingLiner drawingLiner) {
if (drawingLiner.getBaseLiner() instanceof LinerEntity linerEntity) {
linerEntity.setType(LinerEntityType.values()[comboBoxLinerType.getSelectedIndex()]);
linerEntity.setCapacity((int) numericUpDownCapacity.getValue());
linerEntity.setMaxPassengers((int) numericUpDownMaxPassengers.getValue());
linerEntity.setExtraDeck(checkBoxExtraDeck.isSelected());
linerEntity.setPool(checkBoxPool.isSelected());
}
drawingLiner.getBaseLiner().getDeck().setNumericalValue((int) numericUpDownDeckNum.getValue());
}
drawObject();
}
}
private JPanel createColorPanel(Color color) {
JPanel panel = new JPanel();
panel.setBackground(color);
panel.setMaximumSize(new Dimension(50, 50));
return panel;
}
private void buttonAddClick() {
if (liner != null && linerDelegate != null) {
linerDelegate.setLiner(liner);
dispose();
}
}
}

View File

@ -0,0 +1,132 @@
package projectliner;
import projectliner.Drawings.*;
import projectliner.Entities.BaseLinerEntity;
import projectliner.Entities.LinerEntity;
import projectliner.Entities.LinerEntityType;
import projectliner.GenericObjectsCollection.GenericLinerModelsCollection;
import javax.swing.*;
import javax.swing.border.LineBorder;
import java.awt.*;
import java.util.Random;
public class FormLinerGenerator extends JFrame {
private GenericLinerModelsCollection<BaseLinerEntity, IAdditionalElements> collection;
private JTextArea textAreaShips;
private JTextArea textAreaForms;
private JLabel pictureBox;
private FormShipCollection parent;
private DrawingLiner drawing;
public FormLinerGenerator(FormShipCollection parent) {
setTitle("Liner Generator");
setSize(800, 600);
setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
setLayout(new BorderLayout());
this.parent = parent;
collection = new GenericLinerModelsCollection<>();
textAreaShips = new JTextArea(10, 30);
textAreaForms = new JTextArea(10, 30);
pictureBox = new JLabel();
pictureBox.setPreferredSize(new Dimension(800, 400));
pictureBox.setBorder(new LineBorder(Color.BLACK));
JPanel panelLists = new JPanel(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.fill = GridBagConstraints.BOTH;
gbc.insets = new Insets(5, 5, 5, 5);
JLabel labelShips = new JLabel("Entities");
gbc.gridx = 0;
gbc.gridy = 0;
panelLists.add(labelShips, gbc);
JLabel labelForms = new JLabel("Additional Elements");
gbc.gridx = 1;
gbc.gridy = 0;
panelLists.add(labelForms, gbc);
gbc.gridx = 0;
gbc.gridy = 1;
gbc.weightx = 0.5;
gbc.weighty = 1.0;
panelLists.add(new JScrollPane(textAreaShips), gbc);
gbc.gridx = 1;
gbc.gridy = 1;
panelLists.add(new JScrollPane(textAreaForms), gbc);
JButton buttonGenerate = new JButton("Generate Drawing");
buttonGenerate.addActionListener(e -> generateDrawing());
buttonGenerate.setPreferredSize(new Dimension(150, 50));
JButton buttonSend = new JButton("Send to Collection");
buttonSend.addActionListener(e -> sendToCollection());
buttonSend.setPreferredSize(new Dimension(150, 50));
add(panelLists, BorderLayout.NORTH);
add(buttonGenerate, BorderLayout.SOUTH);
add(buttonSend, BorderLayout.WEST);
add(pictureBox, BorderLayout.CENTER);
pack();
generateRandomObjects();
}
private void generateRandomObjects() {
Random rnd = new Random();
for (int i = 0; i < 3; i++) {
int linerType = rnd.nextInt(2);
switch (linerType) {
case 0 -> generateRandomLiner();
case 1 -> generateRandomShip();
}
IAdditionalElements form;
switch (rnd.nextInt(3)) {
case 0 -> form = new TriangularDeckDrawing();
case 1 -> form = new CircularDeckDrawing();
default -> form = new SquareDeckDrawing();
}
collection.addForm(form);
}
textAreaShips.setText(collection.getShipInfo());
textAreaForms.setText(collection.getFormInfo());
}
private void generateRandomShip() {
Random rnd = new Random();
BaseLinerEntity ship = new LinerEntity(rnd.nextInt(200) + 100, rnd.nextInt(2000) + 1000,
new Color(rnd.nextInt(255), rnd.nextInt(255), rnd.nextInt(255)),
new Color(rnd.nextInt(255), rnd.nextInt(255), rnd.nextInt(255)),
new SquareDeckDrawing(),
LinerEntityType.values()[rnd.nextInt(LinerEntityType.values().length)],
rnd.nextInt(9000) + 1000, rnd.nextInt(90) + 10,
rnd.nextBoolean(), rnd.nextBoolean());
collection.addShip(ship);
}
private void generateRandomLiner() {
Random rnd = new Random();
BaseLinerEntity liner = new BaseLinerEntity(rnd.nextInt(100), rnd.nextDouble(),
new Color(rnd.nextInt(255), rnd.nextInt(255), rnd.nextInt(255)), new SquareDeckDrawing());
collection.addShip(liner);
}
private void generateDrawing() {
this.drawing = collection.createRandomShip();
drawing.setPictureSize(pictureBox.getWidth(), pictureBox.getHeight());
drawing.setPosition((pictureBox.getWidth() - drawing.getWidth()) / 2,
(pictureBox.getHeight() - drawing.getHeight()) / 2);
pictureBox.setIcon(new ImageIcon(drawing.drawTransport()));
pictureBox.revalidate();
pictureBox.repaint();
}
private void sendToCollection() {
parent.addGeneratedShip(this.drawing);
}
}

View File

@ -0,0 +1,562 @@
package projectliner;
import projectliner.GenericObjectsCollection.*;
import projectliner.Drawings.*;
import javax.swing.*;
import javax.swing.border.EmptyBorder;
import javax.swing.filechooser.FileNameExtensionFilter;
import javax.swing.text.MaskFormatter;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.io.File;
import java.text.ParseException;
public class FormShipCollection extends JFrame {
private AbstractCompany company = null;
private JComboBox<String> comboBoxCompanySelector;
private JButton buttonAddLiner;
private JButton buttonRemoveShip;
private JButton buttonSubmitForTesting;
private JButton buttonRefresh;
private JButton buttonCreateRandomShip;
private JTextField textFieldPosition;
private JLabel pictureBox;
private final CollectionStorage<DrawingBaseLiner> collectionStorage;
private JPanel collectionStorages;
private JPanel controlPanel;
private JButton buttonAddCollection;
private JButton buttonRemoveCollection;
private JButton buttonCreateCompany;
private JTextField textBoxCollectionName;
private JRadioButton radioButtonList;
private JRadioButton radioButtonArray;
private JList<String> listBoxCollections;
private JButton buttonShowRemovedObjects;
private JFileChooser fileChooser;
private JMenuBar menuBar;
private JMenu fileMenu;
private JMenuItem saveStorageMenuItem;
private JMenuItem loadStorageMenuItem;
private JMenuItem saveCollectionMenuItem;
private JMenuItem loadCollectionMenuItem;
public FormShipCollection() {
setTitle("FormShipCollection");
setSize(1300, 800);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new BorderLayout());
// Create menu bar
fileChooser = new JFileChooser();
fileChooser.setFileFilter(new FileNameExtensionFilter("Text files", "txt"));
fileChooser.setAcceptAllFileFilterUsed(false);
menuBar = new JMenuBar();
fileMenu = new JMenu("File");
saveStorageMenuItem = new JMenuItem("Save Storage");
loadStorageMenuItem = new JMenuItem("Load Storage");
saveCollectionMenuItem = new JMenuItem("Save Collection");
loadCollectionMenuItem = new JMenuItem("Load Collection");
setupKeyboardShortcuts();
saveStorageMenuItem.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
saveMenuItemActionPerformed(e);
}
});
loadStorageMenuItem.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
loadMenuItemActionPerformed(e);
}
});
saveCollectionMenuItem.addActionListener(e -> saveCollectionMenuItemActionPerformed(e));
loadCollectionMenuItem.addActionListener(e -> loadCollectionMenuItemActionPerformed(e));
fileMenu.add(saveStorageMenuItem);
fileMenu.add(loadStorageMenuItem);
fileMenu.add(saveCollectionMenuItem);
fileMenu.add(loadCollectionMenuItem);
menuBar.add(fileMenu);
setJMenuBar(menuBar);
collectionStorage = new CollectionStorage<>();
comboBoxCompanySelector = new JComboBox<>(new String[]{"", "Landing Stage"});
comboBoxCompanySelector.setMaximumSize(new Dimension(Integer.MAX_VALUE, 36));
comboBoxCompanySelector.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
controlPanel.setEnabled(false);
for (Component component : controlPanel.getComponents()) {
component.setEnabled(false);
}
}
});
buttonAddLiner = new JButton("Add Liner");
buttonAddLiner.setMaximumSize(new Dimension(Integer.MAX_VALUE, 36));
buttonAddLiner.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
addLiner();
}
});
buttonCreateRandomShip = new JButton("Create Random Ship");
buttonCreateRandomShip.setMaximumSize(new Dimension(Integer.MAX_VALUE, 36));
buttonCreateRandomShip.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
shipConstructor();
}
});
buttonRemoveShip = new JButton("Remove Ship");
buttonRemoveShip.setMaximumSize(new Dimension(Integer.MAX_VALUE, 36));
buttonRemoveShip.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
removeShip();
}
});
buttonSubmitForTesting = new JButton("Submit for Testing");
buttonSubmitForTesting.setMaximumSize(new Dimension(Integer.MAX_VALUE, 36));
buttonSubmitForTesting.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
submitForTesting();
}
});
buttonRefresh = new JButton("Refresh");
buttonRefresh.setMaximumSize(new Dimension(Integer.MAX_VALUE, 36));
buttonRefresh.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
refresh();
}
});
buttonAddCollection = new JButton("Add Collection");
buttonAddCollection.setMaximumSize(new Dimension(Integer.MAX_VALUE, 36));
buttonAddCollection.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
addCollection();
}
});
buttonRemoveCollection = new JButton("Remove Collection");
buttonRemoveCollection.setMaximumSize(new Dimension(Integer.MAX_VALUE, 36));
buttonRemoveCollection.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
removeCollection();
}
});
buttonCreateCompany = new JButton("Create Company");
buttonCreateCompany.setMaximumSize(new Dimension(Integer.MAX_VALUE, 36));
buttonCreateCompany.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
createCompany();
}
});
buttonShowRemovedObjects = new JButton("Show Removed Objects");
buttonShowRemovedObjects.setMaximumSize(new Dimension(Integer.MAX_VALUE, 36));
buttonShowRemovedObjects.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
sendToFormFromRemovedCollection();
}
});
JLabel labelCollectionName = new JLabel("Collection Name:");
JLabel labelPosition = new JLabel("Position:");
textBoxCollectionName = new JTextField(10);
textBoxCollectionName.setMaximumSize(new Dimension(Integer.MAX_VALUE, 20));
radioButtonList = new JRadioButton("List");
radioButtonArray = new JRadioButton("Array");
ButtonGroup radioGroup = new ButtonGroup();
radioGroup.add(radioButtonList);
radioGroup.add(radioButtonArray);
listBoxCollections = new JList<>();
listBoxCollections.setMaximumSize(new Dimension(Integer.MAX_VALUE, 150));
listBoxCollections.setListData(new String[]{});
collectionStorages = new JPanel();
collectionStorages.setLayout(new BoxLayout(collectionStorages, BoxLayout.Y_AXIS));
collectionStorages.setMaximumSize(new Dimension(200, 500));
collectionStorages.setBorder(new EmptyBorder(10, 10, 10, 10));
labelCollectionName.setAlignmentX(Component.CENTER_ALIGNMENT);
textBoxCollectionName.setAlignmentX(Component.CENTER_ALIGNMENT);
radioButtonList.setAlignmentX(Component.CENTER_ALIGNMENT);
radioButtonArray.setAlignmentX(Component.CENTER_ALIGNMENT);
buttonAddCollection.setAlignmentX(Component.CENTER_ALIGNMENT);
listBoxCollections.setAlignmentX(Component.CENTER_ALIGNMENT);
buttonRemoveCollection.setAlignmentX(Component.CENTER_ALIGNMENT);
comboBoxCompanySelector.setAlignmentX(Component.CENTER_ALIGNMENT);
buttonCreateCompany.setAlignmentX(Component.CENTER_ALIGNMENT);
collectionStorages.add(labelCollectionName);
collectionStorages.add(Box.createVerticalStrut(10));
collectionStorages.add(textBoxCollectionName);
collectionStorages.add(radioButtonList);
collectionStorages.add(radioButtonArray);
collectionStorages.add(Box.createVerticalStrut(10));
collectionStorages.add(buttonAddCollection);
collectionStorages.add(Box.createVerticalStrut(10));
collectionStorages.add(listBoxCollections);
collectionStorages.add(Box.createVerticalStrut(10));
collectionStorages.add(buttonRemoveCollection);
collectionStorages.add(Box.createVerticalStrut(30));
collectionStorages.add(comboBoxCompanySelector);
collectionStorages.add(Box.createVerticalStrut(10));
collectionStorages.add(buttonCreateCompany);
collectionStorages.setEnabled(false);
try {
MaskFormatter maskFormatter = new MaskFormatter("##");
maskFormatter.setPlaceholderCharacter('_');
textFieldPosition = new JFormattedTextField(maskFormatter);
textFieldPosition.setMaximumSize(new Dimension(50,
textFieldPosition.getPreferredSize().height));
} catch (ParseException e) {
e.printStackTrace();
}
pictureBox = new JLabel();
pictureBox.setPreferredSize(new Dimension(600, 400));
pictureBox.setBorder(BorderFactory.createLineBorder(Color.BLACK));
buttonAddLiner.setAlignmentX(Component.CENTER_ALIGNMENT);
buttonCreateRandomShip.setAlignmentX(Component.CENTER_ALIGNMENT);
labelPosition.setAlignmentX(Component.CENTER_ALIGNMENT);
buttonRemoveShip.setAlignmentX(Component.CENTER_ALIGNMENT);
textFieldPosition.setAlignmentX(Component.CENTER_ALIGNMENT);
buttonSubmitForTesting.setAlignmentX(Component.CENTER_ALIGNMENT);
buttonShowRemovedObjects.setAlignmentX(Component.CENTER_ALIGNMENT);
buttonRefresh.setAlignmentX(Component.CENTER_ALIGNMENT);
controlPanel = new JPanel();
controlPanel.setBorder(new EmptyBorder(10, 10, 10, 10));
controlPanel.setMaximumSize(new Dimension(200, 500));
controlPanel.setLayout(new BoxLayout(controlPanel, BoxLayout.Y_AXIS));
controlPanel.add(buttonAddLiner);
controlPanel.add(Box.createVerticalStrut(10));
controlPanel.add(buttonCreateRandomShip);
controlPanel.add(Box.createVerticalStrut(10));
controlPanel.add(buttonRemoveShip);
controlPanel.add(Box.createVerticalStrut(10));
controlPanel.add(labelPosition);
controlPanel.add(Box.createVerticalStrut(5));
controlPanel.add(textFieldPosition);
controlPanel.add(Box.createVerticalStrut(10));
controlPanel.add(buttonSubmitForTesting);
controlPanel.add(Box.createVerticalStrut(10));
controlPanel.add(buttonShowRemovedObjects);
controlPanel.add(Box.createVerticalStrut(10));
controlPanel.add(buttonRefresh);
JPanel rightPanel = new JPanel();
rightPanel.setLayout(new BoxLayout(rightPanel, BoxLayout.Y_AXIS));
rightPanel.add(collectionStorages);
rightPanel.add(controlPanel);
add(rightPanel, BorderLayout.EAST);
add(pictureBox, BorderLayout.CENTER);
}
private void setupKeyboardShortcuts() {
// Save shortcut (Ctrl + S)
saveStorageMenuItem.setAccelerator(KeyStroke.getKeyStroke(
KeyEvent.VK_S, Toolkit.getDefaultToolkit().getMenuShortcutKeyMaskEx()));
// Load shortcut (Ctrl + L)
loadStorageMenuItem.setAccelerator(KeyStroke.getKeyStroke(
KeyEvent.VK_L, Toolkit.getDefaultToolkit().getMenuShortcutKeyMaskEx()));
}
private void saveMenuItemActionPerformed(ActionEvent e) {
if (fileChooser.showSaveDialog(this) == JFileChooser.APPROVE_OPTION) {
File file = fileChooser.getSelectedFile();
if (collectionStorage.saveData(file.getAbsolutePath())) {
JOptionPane.showMessageDialog(this, "Data saved successfully", "Success", JOptionPane.INFORMATION_MESSAGE);
} else {
JOptionPane.showMessageDialog(this, "Data wasn't saved", "Error", JOptionPane.ERROR_MESSAGE);
}
}
}
private void loadMenuItemActionPerformed(ActionEvent e) {
if (fileChooser.showOpenDialog(this) == JFileChooser.APPROVE_OPTION) {
File file = fileChooser.getSelectedFile();
if (collectionStorage.loadData(file.getAbsolutePath())) {
JOptionPane.showMessageDialog(this, "Data loaded successfully", "Success", JOptionPane.INFORMATION_MESSAGE);
refreshListBoxItems();
} else {
JOptionPane.showMessageDialog(this, "Data wasn't loaded", "Error", JOptionPane.ERROR_MESSAGE);
}
}
}
private void saveCollectionMenuItemActionPerformed(ActionEvent e) {
if (listBoxCollections.getSelectedIndex() < 0 ||
listBoxCollections.getSelectedValue() == null) {
JOptionPane.showMessageDialog(this,
"Please select a collection to save",
"No Collection Selected",
JOptionPane.WARNING_MESSAGE);
return;
}
if (fileChooser.showSaveDialog(this) == JFileChooser.APPROVE_OPTION) {
File file = fileChooser.getSelectedFile();
if (!file.getName().toLowerCase().endsWith(".txt")) {
file = new File(file.getAbsolutePath() + ".txt");
}
String selectedCollection = listBoxCollections.getSelectedValue();
if (collectionStorage.saveCollection(selectedCollection, file.getAbsolutePath())) {
JOptionPane.showMessageDialog(this,
"Collection saved successfully",
"Success",
JOptionPane.INFORMATION_MESSAGE);
} else {
JOptionPane.showMessageDialog(this,
"Collection wasn't saved",
"Error",
JOptionPane.ERROR_MESSAGE);
}
}
}
private void loadCollectionMenuItemActionPerformed(ActionEvent e) {
if (fileChooser.showOpenDialog(this) == JFileChooser.APPROVE_OPTION) {
File file = fileChooser.getSelectedFile();
if (collectionStorage.loadAndAddCollection(file.getAbsolutePath())) {
JOptionPane.showMessageDialog(this,
"Collection loaded successfully",
"Success",
JOptionPane.INFORMATION_MESSAGE);
refreshListBoxItems();
} else {
JOptionPane.showMessageDialog(this,
"Collection wasn't loaded",
"Error",
JOptionPane.ERROR_MESSAGE);
}
}
}
private void createCompany() {
if (listBoxCollections.getSelectedIndex() < 0 || listBoxCollections.getSelectedValue() == null) {
JOptionPane.showMessageDialog(this, "Collection is not selected");
return;
}
IGenericObjectsCollection<DrawingBaseLiner> collection =
collectionStorage.getCollection(listBoxCollections.getSelectedValue());
if (collection == null) {
JOptionPane.showMessageDialog(this, "Collection is not found");
return;
}
switch (comboBoxCompanySelector.getSelectedItem().toString()) {
case "Landing Stage":
company = new LandingStage(pictureBox.getWidth(), pictureBox.getHeight(), collection);
break;
}
controlPanel.setEnabled(true);
for (Component component : controlPanel.getComponents()) {
component.setEnabled(true);
}
refreshListBoxItems();
}
private void sendToFormFromRemovedCollection() {
IGenericObjectsCollection<DrawingBaseLiner> removedCollection
= collectionStorage.getCollection("Removed");
if (removedCollection == null || removedCollection.getCount() == 0) {
JOptionPane.showMessageDialog(this,
"No objects in the Removed collection");
return;
}
String input = JOptionPane.showInputDialog(this,
"There are " + removedCollection.getCount() +
" objects in the Removed collection.\n" +
"Enter the number of the object to send to the form:",
"Select Object",
JOptionPane.QUESTION_MESSAGE);
if (input == null || input.isEmpty()) {
return;
}
int index;
try {
index = Integer.parseInt(input);
} catch (NumberFormatException e) {
JOptionPane.showMessageDialog(this,
"Invalid number entered", "Error", JOptionPane.ERROR_MESSAGE);
return;
}
if (index < 0 || index >= removedCollection.getCount()) {
JOptionPane.showMessageDialog(this,
"Invalid index", "Error", JOptionPane.ERROR_MESSAGE);
return;
}
DrawingBaseLiner liner = removedCollection.get(index);
if (liner != null) {
FormLiner form = new FormLiner();
form.setLiner(liner);
form.setVisible(true);
} else {
JOptionPane.showMessageDialog(this,
"No object found at the specified index", "Error",
JOptionPane.ERROR_MESSAGE);
}
}
private void removeCollection() {
if (listBoxCollections.getSelectedIndex() < 0 ||
listBoxCollections.getSelectedValue() == null) {
JOptionPane.showMessageDialog(this,
"Collection is not selected", "Error",
JOptionPane.ERROR_MESSAGE);
return;
}
String collectionName = listBoxCollections.getSelectedValue();
if (JOptionPane.showConfirmDialog(this,
"Are you sure you want to remove the collection '" + collectionName + "'?",
"Confirm Removal", JOptionPane.YES_NO_OPTION,
JOptionPane.QUESTION_MESSAGE) == JOptionPane.YES_OPTION) {
collectionStorage.delCollection(collectionName);
refreshListBoxItems();
JOptionPane.showMessageDialog(this,
"Collection removed successfully", "Success",
JOptionPane.OK_OPTION);
}
}
private void addCollection() {
if (textBoxCollectionName.getText().isEmpty() ||
(!radioButtonList.isSelected() && !radioButtonArray.isSelected())) {
JOptionPane.showMessageDialog(this,
"Please fill all fields", "Error",
JOptionPane.ERROR_MESSAGE);
return;
}
CollectionType collectionType = CollectionType.NONE;
if (radioButtonArray.isSelected()) {
collectionType = CollectionType.ARRAY;
} else if (radioButtonList.isSelected()) {
collectionType = CollectionType.LIST;
}
collectionStorage.addCollection(textBoxCollectionName.getText(), collectionType);
refreshListBoxItems();
}
private void refreshListBoxItems() {
DefaultListModel<String> listModel = new DefaultListModel<>();
for (String colName : collectionStorage.getKeys()) {
if (colName != null && !colName.isEmpty()) {
listModel.addElement(colName);
}
}
listBoxCollections.setModel(listModel);
}
private void addLiner() {
FormLinerConfig form = new FormLinerConfig();
form.setLinerDelegate(this::createObject);
form.setVisible(true);
}
private void createObject(DrawingBaseLiner liner) {
if (company == null) {
return;
}
if (AbstractCompany.add(company, liner)) {
JOptionPane.showMessageDialog(this, "Object was added");
pictureBox.setIcon(new ImageIcon(company.show()));
} else {
JOptionPane.showMessageDialog(this, "Couldn't add object");
}
}
private void removeShip() {
if (textFieldPosition.getText().isEmpty() || company == null) {
return;
}
if (collectionStorage.getCollection("Removed") == null) {
collectionStorage.addCollection("Removed", CollectionType.LINKED_LIST);
}
int pos = Integer.parseInt(textFieldPosition.getText());
if (JOptionPane.showConfirmDialog(this,
"Remove object?", "Removing...",
JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE) == JOptionPane.YES_OPTION) {
IGenericObjectsCollection<DrawingBaseLiner> removedCollection
= collectionStorage.getCollection("Removed");
DrawingBaseLiner removedObject = collectionStorage.getObject(listBoxCollections.getSelectedValue(), pos);
if (removedObject != null) {
removedCollection.insert(removedObject);
}
if (AbstractCompany.remove(company, pos)) {
JOptionPane.showMessageDialog(this, "Object was removed");
pictureBox.setIcon(new ImageIcon(company.show()));
} else {
JOptionPane.showMessageDialog(this, "Couldn't remove object");
}
}
}
private void submitForTesting() {
if (company == null) {
return;
}
DrawingBaseLiner liner = null;
int counter = 100;
while (liner == null && counter > 0) {
liner = company.getRandomObject();
counter--;
}
if (liner == null) {
return;
}
FormLiner form = new FormLiner();
form.setLiner(liner);
form.setVisible(true);
}
private void refresh() {
if (company == null) {
return;
}
pictureBox.setIcon(new ImageIcon(company.show()));
}
private void shipConstructor() {
FormLinerGenerator form = new FormLinerGenerator(FormShipCollection.this);
form.setVisible(true);
}
public void addGeneratedShip(DrawingLiner liner) {
AbstractCompany.add(company, liner);
}
}

View File

@ -0,0 +1,58 @@
package projectliner.GenericObjectsCollection;
import projectliner.Drawings.*;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.util.Random;
public abstract class AbstractCompany {
protected final int placeSizeWidth = 210;
protected final int placeSizeHeight = 80;
protected final int pictureWidth;
protected final int pictureHeight;
protected IGenericObjectsCollection<DrawingBaseLiner> collection = null;
private int getMaxCount() {
return pictureWidth * pictureHeight / (placeSizeWidth * placeSizeHeight);
}
public AbstractCompany(int picWidth, int picHeight, IGenericObjectsCollection<DrawingBaseLiner> collection) {
this.pictureWidth = picWidth;
this.pictureHeight = picHeight;
this.collection = collection;
this.collection.setMaxCount(getMaxCount());
}
public static boolean add(AbstractCompany company, DrawingBaseLiner liner) {
return company.collection != null && company.collection.insert(liner);
}
public static boolean remove(AbstractCompany company, int position) {
return company.collection != null && company.collection.remove(position);
}
public DrawingBaseLiner getRandomObject() {
Random rnd = new Random();
return collection != null ? collection.get(rnd.nextInt(getMaxCount())) : null;
}
public BufferedImage show() {
BufferedImage bitmap = new BufferedImage(pictureWidth, pictureHeight, 2);
Graphics graphics = bitmap.getGraphics();
drawBackground(graphics);
setObjectsPosition();
if (collection != null) {
for (int i = 0; i < collection.getCount(); ++i) {
DrawingBaseLiner obj = collection.get(i);
if (obj != null) {
obj.drawTransport(graphics);
}
}
}
return bitmap;
}
protected abstract void drawBackground(Graphics g);
protected abstract void setObjectsPosition();
}

View File

@ -0,0 +1,270 @@
package projectliner.GenericObjectsCollection;
import projectliner.Drawings.DrawingBaseLiner;
import projectliner.Drawings.ExtensionDrawingLiner;
import java.io.*;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.*;
public class CollectionStorage<T extends DrawingBaseLiner> {
private static final String COLLECTION_STORAGE_KEY = "CollectionStorage";
private static final String COLLECTION_KEY = "Collection";
private static final String KEY_VALUE_SEPARATOR = "|";
private static final String ITEMS_SEPARATOR = ";";
private static final String LINE_SEPARATOR = System.lineSeparator();
private final Map<String, IGenericObjectsCollection<T>> storages;
private final String collectionKey = "CollectionStorage";
private final String separatorForKeyValue = "|";
private final String separatorItems = ";";
public CollectionStorage() {
this.storages = new HashMap<>();
}
public List<String> getKeys() {
return new ArrayList<>(storages.keySet());
}
public void addCollection(String name, CollectionType collectionType) {
if (name == null || name.isEmpty() || storages.containsKey(name)) {
return;
}
switch (collectionType) {
case ARRAY:
storages.put(name, new GenericObjectsCollection<>());
break;
case LIST:
storages.put(name, new ListGenericObjects<>());
break;
case LINKED_LIST:
storages.put(name, new LinkedListGenericObjects<>());
}
}
public void delCollection(String name) {
if (name == null || name.isEmpty() || !storages.containsKey(name)) {
return;
}
storages.remove(name);
}
public IGenericObjectsCollection<T> getCollection(String name) {
return storages.get(name);
}
public T getObject(String name, int position) {
IGenericObjectsCollection<T> collection = storages.get(name);
return collection != null ? collection.get(position) : null;
}
public boolean saveData(String filename) {
if (storages.isEmpty()) {
return false;
}
try {
Path path = Paths.get(filename);
if (Files.exists(path)) {
Files.delete(path);
}
String data = buildStorageData();
writeDataToFile(filename, data);
return true;
} catch (IOException e) {
e.printStackTrace();
return false;
}
}
public boolean saveCollection(String collectionName, String filename) {
IGenericObjectsCollection<T> collection = storages.get(collectionName);
if (collection == null || collection.getCount() == 0) {
return false;
}
try {
Path path = Paths.get(filename);
if (Files.exists(path)) {
Files.delete(path);
}
String data = COLLECTION_KEY + LINE_SEPARATOR +
buildCollectionEntry(collectionName, collection);
writeDataToFile(filename, data);
return true;
} catch (IOException e) {
e.printStackTrace();
return false;
}
}
private String buildStorageData() {
StringBuilder sb = new StringBuilder(COLLECTION_STORAGE_KEY);
for (Map.Entry<String, IGenericObjectsCollection<T>> entry : storages.entrySet()) {
if (entry.getValue().getCount() == 0) {
continue;
}
sb.append(LINE_SEPARATOR)
.append(buildCollectionEntry(entry.getKey(), entry.getValue()));
}
return sb.toString();
}
private String buildCollectionEntry(String key, IGenericObjectsCollection<T> collection) {
StringBuilder sb = new StringBuilder();
sb.append(key)
.append(KEY_VALUE_SEPARATOR)
.append(collection.getCollectionType())
.append(KEY_VALUE_SEPARATOR)
.append(collection.getMaxCount())
.append(KEY_VALUE_SEPARATOR)
.append(buildItemsString(collection));
return sb.toString();
}
private String buildItemsString(IGenericObjectsCollection<T> collection) {
StringBuilder sb = new StringBuilder();
for (T item : collection.getItems()) {
String data = ExtensionDrawingLiner.getDataForSave(item);
if (data != null && !data.isEmpty()) {
sb.append(data).append(ITEMS_SEPARATOR);
}
}
return sb.toString();
}
private void writeDataToFile(String filename, String data) throws IOException {
Path path = Paths.get(filename);
Files.writeString(path, data, StandardCharsets.UTF_8);
}
public boolean loadData(String filename) {
try {
String content = readFileContent(filename);
return parseAndLoadContent(content);
} catch (IOException e) {
e.printStackTrace();
return false;
}
}
public boolean loadAndAddCollection(String filename) {
try {
String content = readFileContent(filename);
return parseAndAddCollection(content);
} catch (IOException e) {
e.printStackTrace();
return false;
}
}
private boolean parseAndAddCollection(String content) {
String[] lines = content.split("[\\n\\r]+");
if (!isValidSingleCollectionFileContent(lines)) {
return false;
}
return processCollectionEntries(lines);
}
private boolean isValidSingleCollectionFileContent(String[] lines) {
return lines.length == 2 && COLLECTION_KEY.equals(lines[0]);
}
private String readFileContent(String filename) throws IOException {
Path path = Paths.get(filename);
return Files.readString(path, StandardCharsets.UTF_8);
}
private boolean parseAndLoadContent(String content) {
String[] lines = content.split("[\\n\\r]+");
if (!isValidFileContent(lines)) {
return false;
}
storages.clear();
return processCollectionEntries(lines);
}
private boolean isValidFileContent(String[] lines) {
return lines != null && lines.length > 0 && COLLECTION_STORAGE_KEY.equals(lines[0]);
}
private boolean processCollectionEntries(String[] lines) {
for (int i = 1; i < lines.length; i++) {
String[] record = lines[i].split("\\" + KEY_VALUE_SEPARATOR);
if (!processCollectionRecord(record)) {
return false;
}
}
return true;
}
private boolean processCollectionRecord(String[] record) {
if (record.length != 4) {
return true; // Skip invalid records
}
try {
String name = record[0];
if (storages.containsKey(name)) {
storages.remove(name);
}
CollectionType type = CollectionType.valueOf(record[1]);
int maxCount = Integer.parseInt(record[2]);
String[] items = record[3].split("\\" + ITEMS_SEPARATOR);
return createAndPopulateCollection(name, type, maxCount, items);
} catch (IllegalArgumentException e) {
return false;
}
}
private boolean createAndPopulateCollection(String name, CollectionType type,
int maxCount, String[] items) {
IGenericObjectsCollection<T> collection = createCollection(type);
if (collection == null) {
return false;
}
collection.setMaxCount(maxCount);
if (!populateCollection(collection, items)) {
return false;
}
storages.put(name, collection);
return true;
}
private boolean populateCollection(IGenericObjectsCollection<T> collection,
String[] items) {
for (String item : items) {
if (item.isEmpty()) {
continue;
}
T liner = (T) ExtensionDrawingLiner.createDrawingLiner(item);
if (liner != null && !collection.insert(liner)) {
return false;
}
}
return true;
}
private IGenericObjectsCollection<T> createCollection(CollectionType collectionType) {
return switch (collectionType) {
case ARRAY -> new GenericObjectsCollection<>();
case LIST -> new ListGenericObjects<>();
case LINKED_LIST -> new LinkedListGenericObjects<>();
case NONE -> null;
};
}
}

View File

@ -0,0 +1,8 @@
package projectliner.GenericObjectsCollection;
public enum CollectionType {
NONE,
ARRAY,
LIST,
LINKED_LIST
}

View File

@ -0,0 +1,78 @@
package projectliner.GenericObjectsCollection;
import projectliner.Drawings.*;
import projectliner.Entities.BaseLinerEntity;
import projectliner.Entities.LinerEntity;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
public class GenericLinerModelsCollection <T extends BaseLinerEntity,
E extends IAdditionalElements> {
private List<T> collectionShips;
private List<E> collectionForms;
public GenericLinerModelsCollection() {
collectionShips = new ArrayList<>();
collectionForms = new ArrayList<>();
}
public void addShip(T ship) {
collectionShips.add(ship);
}
public void addForm(E form) {
collectionForms.add(form);
}
public DrawingLiner createRandomShip() {
Random rnd = new Random();
int shipIndex = rnd.nextInt(collectionShips.size());
int formIndex = rnd.nextInt(collectionForms.size());
T selectedShip = collectionShips.get(shipIndex);
E selectedForm = collectionForms.get(formIndex);
return new DrawingLiner(selectedShip, selectedForm, rnd.nextInt(2) + 1);
}
public String getShipInfo() {
StringBuilder shipInfo = new StringBuilder();
for (T ship : collectionShips) {
if (ship instanceof LinerEntity liner) {
shipInfo.append("Ship: ").append("\n");
shipInfo.append("Speed: ").append(liner.getSpeed()).append(",\n");
shipInfo.append("Weight: ").append(liner.getWeight()).append(",\n");
shipInfo.append("Primary color: ").append(liner.getPrimaryColor()).append(",\n");
shipInfo.append("Secondary color: ").append(liner.getSecondaryColor()).append(",\n");
shipInfo.append("Type: ").append(liner.getType()).append(",\n");
shipInfo.append("Capacity: ").append(liner.getCapacity()).append(",\n");
shipInfo.append("Max passengers: ").append(liner.getMaxPassengers()).append(",\n");
shipInfo.append("Has extra deck: ").append(liner.hasExtraDeck()).append(",\n");
shipInfo.append("Has pool: ").append(liner.hasPool()).append(",\n");
} else {
shipInfo.append("Liner: ").append("\n");
shipInfo.append("Speed: ").append(ship.getSpeed()).append(",\n");
shipInfo.append("Weight: ").append(ship.getWeight()).append(",\n");
shipInfo.append("Primary color: ").append(ship.getPrimaryColor()).append(",\n");
}
shipInfo.append("\n\n");
}
return shipInfo.toString();
}
public String getFormInfo() {
StringBuilder formInfo = new StringBuilder();
for (E deck : collectionForms) {
if (deck instanceof TriangularDeckDrawing) {
formInfo.append("Triangular deck").append("\n");
} else if (deck instanceof CircularDeckDrawing) {
formInfo.append("Circular deck").append("\n");
} else if (deck instanceof SquareDeckDrawing) {
formInfo.append("Square deck").append("\n");
}
}
return formInfo.toString();
}
}

View File

@ -0,0 +1,126 @@
package projectliner.GenericObjectsCollection;
import java.util.Arrays;
import java.util.Iterator;
import java.util.NoSuchElementException;
public class GenericObjectsCollection<T> implements IGenericObjectsCollection<T> {
private T[] collection;
@SuppressWarnings("unchecked")
public GenericObjectsCollection() {
collection = (T[]) new Object[0];
}
@Override
public int getCount() {
return collection.length;
}
@Override
public int getMaxCount() {
return collection.length;
}
@Override
public void setMaxCount(int maxCount) {
if (maxCount > 0) {
if (collection.length > 0) {
collection = Arrays.copyOf(collection, maxCount);
} else {
collection = (T[]) new Object[maxCount];
}
}
}
@Override
public T get(int position) {
if (position < 0 || position >= collection.length) {
return null;
}
return collection[position];
}
@Override
public CollectionType getCollectionType() {
return CollectionType.ARRAY;
}
@Override
public Iterable<T> getItems() {
return new Iterable<T>() {
@Override
public Iterator<T> iterator() {
return new Iterator<T>() {
private int currentIndex = 0;
@Override
public boolean hasNext() {
while (currentIndex < collection.length && collection[currentIndex] == null) {
currentIndex++;
}
return currentIndex < collection.length;
}
@Override
public T next() {
if (!hasNext()) {
throw new NoSuchElementException();
}
return collection[currentIndex++];
}
};
}
};
}
@Override
public boolean insert(T obj) {
for (int i = 0; i < collection.length; ++i) {
if (collection[i] == null) {
collection[i] = obj;
return true;
}
}
return false;
}
@Override
public boolean insert(T obj, int position) {
if (position < 0 || position >= collection.length) {
return false;
}
if (collection[position] == null) {
collection[position] = obj;
return true;
} else {
int originalPosition = position;
while (position < collection.length) {
if (collection[position] == null) {
collection[position] = obj;
return true;
}
position++;
}
position = originalPosition;
while (position >= 0) {
if (collection[position] == null) {
collection[position] = obj;
return true;
}
position--;
}
}
return false;
}
@Override
public boolean remove(int position) {
if (position < 0 || position >= collection.length || collection[position] == null) {
return false;
}
collection[position] = null;
return true;
}
}

View File

@ -0,0 +1,15 @@
package projectliner.GenericObjectsCollection;
import java.util.Iterator;
public interface IGenericObjectsCollection<T> {
int getCount();
int getMaxCount();
void setMaxCount(int maxCount);
boolean insert(T obj);
boolean insert(T obj, int position);
boolean remove(int position);
T get(int position);
CollectionType getCollectionType();
Iterable<T> getItems();
}

View File

@ -0,0 +1,78 @@
package projectliner.GenericObjectsCollection;
import projectliner.Drawings.*;
import projectliner.GenericObjectsCollection.*;
import java.awt.*;
import java.awt.Point;
public class LandingStage extends AbstractCompany {
public LandingStage(int picWidth, int picHeight,
IGenericObjectsCollection<DrawingBaseLiner> collection) {
super(picWidth, picHeight, collection);
}
@Override
protected void drawBackground(Graphics g) {
int spacing = 20;
int horizontalCount = pictureWidth / placeSizeWidth;
int verticalCount = pictureHeight / placeSizeHeight;
Graphics2D g2d = (Graphics2D) g;
g2d.setStroke(new BasicStroke(3));
g2d.setColor(Color.BLACK);
for (int i = 0; i < horizontalCount; i++) {
for (int j = 0; j < verticalCount; j++) {
int x = i * placeSizeWidth;
int y = j * placeSizeHeight;
Point[] parkingPlace = {
new Point(x + placeSizeWidth - spacing, y),
new Point(x, y),
new Point(x, y + placeSizeHeight),
new Point(x + placeSizeWidth - spacing, y + placeSizeHeight),
new Point(x, y + placeSizeHeight),
new Point(x, y),
};
g2d.drawPolygon(new int[]{parkingPlace[0].x, parkingPlace[1].x,
parkingPlace[2].x,parkingPlace [3].x,
parkingPlace[4].x, parkingPlace[5].x},
new int[]{parkingPlace [0].y, parkingPlace [1].y,
parkingPlace[2].y, parkingPlace[3].y,
parkingPlace[4].y, parkingPlace[5].y}, 6);
}
}
}
@Override
protected void setObjectsPosition() {
if (collection == null) {
return;
}
int spacing = 10;
int horizontalCount = pictureWidth / placeSizeWidth;
int verticalCount = pictureHeight / placeSizeHeight;
int index = 0;
for (int i = 0; i < horizontalCount; i++) {
for (int j = verticalCount - 1; j >= 0; j--) {
if (index >= collection.getCount()) {
return;
}
DrawingBaseLiner obj = collection.get(index);
if (obj != null) {
obj.setPictureSize(pictureWidth, pictureHeight);
int x = i * placeSizeWidth;
int y = j * placeSizeHeight;
obj.setPosition(x + spacing, y + spacing);
}
index++;
}
}
}
}

View File

@ -0,0 +1,104 @@
package projectliner.GenericObjectsCollection;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.NoSuchElementException;
public class LinkedListGenericObjects<T> implements IGenericObjectsCollection<T> {
private final LinkedList<T> collection;
private int maxCount;
public LinkedListGenericObjects() {
this.collection = new LinkedList<>();
}
@Override
public int getCount() {
return collection.size();
}
@Override
public int getMaxCount() {
return maxCount;
}
@Override
public void setMaxCount(int maxCount) {
if (maxCount > 0) {
this.maxCount = maxCount;
}
}
@Override
public boolean insert(T obj) {
collection.add(obj);
return false;
}
@Override
public boolean insert(T obj, int position) {
if (position < 0 || position >= maxCount) {
return false;
}
if (position >= collection.size()) {
collection.addAll(new LinkedList<>(collection.subList(collection.size(), position)));
}
if (collection.get(position) == null) {
collection.set(position, obj);
return true;
}
return false;
}
@Override
public boolean remove(int position) {
if (position < 0 || position >= collection.size()) {
return false;
}
collection.remove(position);
return true;
}
@Override
public T get(int position) {
if (position < 0 || position >= collection.size()) {
return null;
}
return collection.get(position);
}
@Override
public CollectionType getCollectionType() {
return CollectionType.LIST;
}
@Override
public Iterable<T> getItems() {
return new Iterable<T>() {
@Override
public Iterator<T> iterator() {
return new Iterator<T>() {
private int currentIndex = 0;
@Override
public boolean hasNext() {
while (currentIndex < collection.size() && collection.get(currentIndex) == null) {
currentIndex++;
}
return currentIndex < collection.size();
}
@Override
public T next() {
if (!hasNext()) {
throw new NoSuchElementException();
}
return collection.get(currentIndex++);
}
};
}
};
}
}

View File

@ -0,0 +1,105 @@
package projectliner.GenericObjectsCollection;
import java.util.*;
public class ListGenericObjects<T> implements IGenericObjectsCollection<T> {
private final List<T> collection;
private int maxCount;
public ListGenericObjects() {
this.collection = new ArrayList<>();
}
@Override
public int getCount() {
return collection.size();
}
@Override
public int getMaxCount() {
return maxCount;
}
@Override
public void setMaxCount(int maxCount) {
if (maxCount > 0) {
this.maxCount = maxCount;
}
}
@Override
public T get(int position) {
if (position < 0 || position >= collection.size()) {
return null;
}
return collection.get(position);
}
@Override
public CollectionType getCollectionType() {
return CollectionType.LIST;
}
@Override
public Iterable<T> getItems() {
return new Iterable<T>() {
@Override
public Iterator<T> iterator() {
return new Iterator<T>() {
private int currentIndex = 0;
@Override
public boolean hasNext() {
while (currentIndex < collection.size() && collection.get(currentIndex) == null) {
currentIndex++;
}
return currentIndex < collection.size();
}
@Override
public T next() {
if (!hasNext()) {
throw new NoSuchElementException();
}
return collection.get(currentIndex++);
}
};
}
};
}
@Override
public boolean insert(T obj) {
if (collection.size() < maxCount) {
collection.add(obj);
return true;
}
return false;
}
@Override
public boolean insert(T obj, int position) {
if (position < 0 || position >= maxCount) {
return false;
}
if (position >= collection.size()) {
collection.addAll(Collections.nCopies(position - collection.size() + 1, null));
}
if (collection.get(position) == null) {
collection.set(position, obj);
return true;
}
return false;
}
@Override
public boolean remove(int position) {
if (position < 0 || position >= collection.size() || collection.get(position) == null) {
return false;
}
collection.remove(position);
return true;
}
}

View File

@ -0,0 +1,78 @@
package projectliner.MovementStrategy;
public abstract class AbstractStrategy {
private IMoveableObject moveableObject;
private StrategyStatus state;
protected int fieldWidth;
protected int fieldHeight;
public AbstractStrategy() {
this.state = StrategyStatus.NOT_INIT;
}
public StrategyStatus getStatus() {
return this.state;
}
public void setData(IMoveableObject moveableObject, int width, int height) {
if (moveableObject == null) {
this.state = StrategyStatus.NOT_INIT;
} else {
this.state = StrategyStatus.IN_PROGRESS;
this.moveableObject = moveableObject;
this.fieldWidth = width;
this.fieldHeight = height;
}
}
public void makeStep() {
if (this.state == StrategyStatus.IN_PROGRESS) {
if (this.isTargetDestination()) {
this.state = StrategyStatus.FINISHED;
} else {
this.moveToTarget();
}
}
}
protected boolean moveLeft() {
return this.moveTo(MovementDirection.LEFT);
}
protected boolean moveRight() {
return this.moveTo(MovementDirection.RIGHT);
}
protected boolean moveUp() {
return this.moveTo(MovementDirection.UP);
}
protected boolean moveDown() {
return this.moveTo(MovementDirection.DOWN);
}
protected ObjectParameters getObjectParameters() {
return this.moveableObject != null ? this.moveableObject.getObjectPosition() : null;
}
protected Integer getStep() {
if (this.state != StrategyStatus.IN_PROGRESS) {
return null;
} else {
return this.moveableObject != null ? this.moveableObject.getStep() : null;
}
}
protected abstract void moveToTarget();
protected abstract boolean isTargetDestination();
private boolean moveTo(MovementDirection movementDirection) {
if (this.state != StrategyStatus.IN_PROGRESS) {
return false;
} else {
return this.moveableObject != null && this.moveableObject.tryMoveObject(movementDirection);
}
}
}

View File

@ -0,0 +1,9 @@
package projectliner.MovementStrategy;
public interface IMoveableObject {
ObjectParameters getObjectPosition();
int getStep();
boolean tryMoveObject(MovementDirection var1);
}

View File

@ -0,0 +1,30 @@
package projectliner.MovementStrategy;
public class MoveToBorder extends AbstractStrategy {
public MoveToBorder() {
}
protected void moveToTarget() {
ObjectParameters objParams = this.getObjectParameters();
if (objParams != null) {
if (objParams.getRightBorder() + this.getStep() < this.fieldWidth && objParams.getDownBorder() + this.getStep() < this.fieldHeight) {
this.moveRight();
this.moveDown();
} else if (objParams.getRightBorder() + this.getStep() < this.fieldWidth) {
this.moveRight();
} else if (objParams.getDownBorder() + this.getStep() < this.fieldHeight) {
this.moveDown();
}
}
}
protected boolean isTargetDestination() {
ObjectParameters objParams = this.getObjectParameters();
if (objParams == null) {
return false;
} else {
return objParams.getRightBorder() + this.getStep() >= this.fieldWidth && objParams.getDownBorder() + this.getStep() >= this.fieldHeight;
}
}
}

View File

@ -0,0 +1,37 @@
package projectliner.MovementStrategy;
public class MoveToCenter extends AbstractStrategy {
public MoveToCenter() {
}
protected void moveToTarget() {
ObjectParameters objParams = this.getObjectParameters();
if (objParams != null) {
if (objParams.getObjectMiddleHorizontal() < this.fieldWidth / 2) {
if (objParams.getObjectMiddleVertical() < this.fieldHeight / 2) {
this.moveRight();
this.moveDown();
} else {
this.moveRight();
this.moveUp();
}
} else if (objParams.getObjectMiddleVertical() < this.fieldHeight / 2) {
this.moveLeft();
this.moveDown();
} else {
this.moveLeft();
this.moveUp();
}
}
}
protected boolean isTargetDestination() {
ObjectParameters objParams = this.getObjectParameters();
if (objParams == null) {
return false;
} else {
return objParams.getObjectMiddleHorizontal() - this.getStep() <= this.fieldWidth / 2 && objParams.getObjectMiddleHorizontal() + this.getStep() >= this.fieldWidth / 2 && objParams.getObjectMiddleVertical() - this.getStep() <= this.fieldHeight / 2 && objParams.getObjectMiddleVertical() + this.getStep() >= this.fieldHeight / 2;
}
}
}

View File

@ -0,0 +1,44 @@
package projectliner.MovementStrategy;
import projectliner.Drawings.DirectionType;
import projectliner.Drawings.DrawingBaseLiner;
public class MoveableLiner implements IMoveableObject {
private final DrawingBaseLiner liner;
public MoveableLiner(DrawingBaseLiner liner) {
this.liner = liner;
}
public ObjectParameters getObjectPosition() {
return this.liner != null && this.liner.getBaseLiner() != null && this.liner.getPosX() != null && this.liner.getPosY() != null ? new ObjectParameters(this.liner.getPosX(), this.liner.getPosY(), this.liner.getWidth(), this.liner.getHeight()) : null;
}
public int getStep() {
return (int)(this.liner != null && this.liner.getBaseLiner() != null ? this.liner.getBaseLiner().getStep() : (double)0.0F);
}
public boolean tryMoveObject(MovementDirection direction) {
return this.liner != null && this.liner.getBaseLiner() != null ? this.liner.moveTransport(getDirectionType(direction)) : false;
}
private static DirectionType getDirectionType(MovementDirection direction) {
switch (direction) {
case LEFT -> {
return DirectionType.LEFT;
}
case RIGHT -> {
return DirectionType.RIGHT;
}
case UP -> {
return DirectionType.UP;
}
case DOWN -> {
return DirectionType.DOWN;
}
default -> {
return DirectionType.NONE;
}
}
}
}

View File

@ -0,0 +1,18 @@
package projectliner.MovementStrategy;
public enum MovementDirection {
UP(1),
DOWN(2),
LEFT(3),
RIGHT(4);
private final int value;
private MovementDirection(int value) {
this.value = value;
}
public int getValue() {
return this.value;
}
}

View File

@ -0,0 +1,39 @@
package projectliner.MovementStrategy;
public class ObjectParameters {
private final int x;
private final int y;
private final int width;
private final int height;
public ObjectParameters(int x, int y, int width, int height) {
this.x = x;
this.y = y;
this.width = width;
this.height = height;
}
public int getRightBorder() {
return this.x + this.width;
}
public int getLeftBorder() {
return this.x;
}
public int getTopBorder() {
return this.y;
}
public int getDownBorder() {
return this.y + this.height;
}
public int getObjectMiddleHorizontal() {
return this.x + this.width / 2;
}
public int getObjectMiddleVertical() {
return this.y + this.height / 2;
}
}

View File

@ -0,0 +1,10 @@
package projectliner.MovementStrategy;
public enum StrategyStatus {
NOT_INIT,
IN_PROGRESS,
FINISHED;
private StrategyStatus() {
}
}