legacy project initial commit

This commit is contained in:
2024-07-21 20:41:51 +07:00
commit d4afde065d
109 changed files with 1739 additions and 0 deletions

6
.classpath Normal file
View File

@ -0,0 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<classpath>
<classpathentry kind="src" path="src"/>
<classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER/org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType/jdk-17.0.7.7-hotspot"/>
<classpathentry kind="output" path="bin"/>
</classpath>

17
.project Normal file
View File

@ -0,0 +1,17 @@
<?xml version="1.0" encoding="UTF-8"?>
<projectDescription>
<name>HitboxDrawboxEditor</name>
<comment></comment>
<projects>
</projects>
<buildSpec>
<buildCommand>
<name>org.eclipse.jdt.core.javabuilder</name>
<arguments>
</arguments>
</buildCommand>
</buildSpec>
<natures>
<nature>org.eclipse.jdt.core.javanature</nature>
</natures>
</projectDescription>

View File

@ -0,0 +1,2 @@
eclipse.preferences.version=1
encoding/<project>=UTF-8

View File

@ -0,0 +1,14 @@
eclipse.preferences.version=1
org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled
org.eclipse.jdt.core.compiler.codegen.targetPlatform=15
org.eclipse.jdt.core.compiler.codegen.unusedLocal=preserve
org.eclipse.jdt.core.compiler.compliance=15
org.eclipse.jdt.core.compiler.debug.lineNumber=generate
org.eclipse.jdt.core.compiler.debug.localVariable=generate
org.eclipse.jdt.core.compiler.debug.sourceFile=generate
org.eclipse.jdt.core.compiler.problem.assertIdentifier=error
org.eclipse.jdt.core.compiler.problem.enablePreviewFeatures=disabled
org.eclipse.jdt.core.compiler.problem.enumIdentifier=error
org.eclipse.jdt.core.compiler.problem.reportPreviewFeatures=warning
org.eclipse.jdt.core.compiler.release=enabled
org.eclipse.jdt.core.compiler.source=15

BIN
bin/gui/CustomIcon.class Normal file

Binary file not shown.

BIN
bin/gui/DrawboxEditor.class Normal file

Binary file not shown.

BIN
bin/gui/Editable.class Normal file

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

BIN
bin/gui/ListGUI.class Normal file

Binary file not shown.

BIN
bin/gui/MainGUI.class Normal file

Binary file not shown.

Binary file not shown.

BIN
bin/launch/Launcher.class Normal file

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

BIN
bin/model/Drawbox.class Normal file

Binary file not shown.

BIN
bin/model/Entity.class Normal file

Binary file not shown.

BIN
bin/model/Formatter.class Normal file

Binary file not shown.

Binary file not shown.

Binary file not shown.

BIN
bin/model/Hitbox.class Normal file

Binary file not shown.

BIN
bin/model/Point.class Normal file

Binary file not shown.

Binary file not shown.

BIN
res/TopHome.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.1 MiB

BIN
res/add.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 828 B

BIN
res/addbutton.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.6 KiB

BIN
res/circle.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.1 KiB

BIN
res/deletebutton.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.2 KiB

BIN
res/destroy.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.3 KiB

BIN
res/download.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.3 KiB

BIN
res/formless.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 780 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 53 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 21 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 44 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 55 KiB

BIN
res/image/256х184 seat.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 18 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 45 KiB

BIN
res/image/256х209 box.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 33 KiB

BIN
res/image/256х232 hay.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 28 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 29 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 46 KiB

BIN
res/image/256х362 tree.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 42 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 43 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 58 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 46 KiB

BIN
res/image/256х616 flag.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 61 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 45 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 42 KiB

BIN
res/image/256х679 well.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 68 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 37 KiB

BIN
res/image/CoffeeToffee.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 6.2 KiB

BIN
res/image/Stone.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 177 KiB

BIN
res/image/TopHome.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.1 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 60 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 22 KiB

BIN
res/image/bagApples.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 367 KiB

BIN
res/image/bulletinBoard.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.1 MiB

BIN
res/image/chair.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 244 KiB

BIN
res/image/coffee toffee.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 377 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 300 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 175 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 117 KiB

BIN
res/image/merchant4.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 581 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 117 KiB

BIN
res/image/misato.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 39 KiB

BIN
res/image/spell2.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 16 KiB

BIN
res/image/spell3.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 63 KiB

BIN
res/image/starlight.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 24 KiB

BIN
res/image/tavern.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.8 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 131 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 124 KiB

BIN
res/image/wood.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.8 MiB

BIN
res/misato.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 39 KiB

BIN
res/naga.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 630 KiB

23
res/objecttypes.xml Normal file
View File

@ -0,0 +1,23 @@
<?xml version="1.0" encoding="UTF-8"?>
<objecttypes>
<objecttype name="misato" color="#a0a0a4">
<property name="class" type="string" default="Solid"/>
<property name="drawbox" type="string" default="2 1 254 1 254 338 2 336"/>
<property name="hitbox" type="string" default="Circle 4 6 24"/>
</objecttype>
<objecttype name="starlight" color="#a0a0a4">
<property name="class" type="string" default="Solid"/>
<property name="drawbox" type="string" default="2 1 253 1 254 468 2 490"/>
<property name="hitbox" type="string" default="Rectangle 0 0 76 119"/>
</objecttype>
<objecttype name="tavern" color="#a0a0a4">
<property name="class" type="string" default="Solid"/>
<property name="drawbox" type="string" default="3 2 252 1 253 605 6 608"/>
<property name="hitbox" type="string" default="Rectangle 0 0 96 98"/>
</objecttype>
<objecttype name="TopHome" color="#a0a0a4">
<property name="class" type="string" default="Solid"/>
<property name="drawbox" type="string" default="3 2 252 1 253 605 6 608"/>
<property name="hitbox" type="string" default="Rectangle 0 0 96 98"/>
</objecttype>
</objecttypes>

BIN
res/square.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 755 B

BIN
res/starlight.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 24 KiB

BIN
res/tavern.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.8 MiB

BIN
res/test.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 364 KiB

BIN
res/xml.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 867 B

65
src/gui/CustomIcon.java Normal file
View File

@ -0,0 +1,65 @@
package gui;
import java.awt.Color;
import java.awt.Component;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.image.BufferedImage;
import javax.swing.Icon;
public class CustomIcon implements Icon {
private BufferedImage image;
private int width, heigth;
public CustomIcon(Image image, int width, int height) {
this.image = toBufferedImage(image);
this.width = width;
this.heigth = height;
}
private final Color color = new Color(1f, 0.82f, 0.45f, 0.4f);
@Override
public void paintIcon(Component c, Graphics g, int x, int y) {
Graphics2D g2d = (Graphics2D) g.create();
int imageWidth = image.getWidth(),
imageHeigth = image.getHeight();
// setting image position to center
int resultX = x + (width-imageWidth)/2,
resultY = y + (heigth-imageHeigth)/2;
//g2d.drawRect(x, y, width, heigth);
g2d.setColor(color);
g2d.fillOval(x, y, width, heigth);
g2d.drawImage(image, resultX, resultY, null);
}
private BufferedImage toBufferedImage(Image img)
{
if (img instanceof BufferedImage)
{
return (BufferedImage) img;
}
// Create a buffered image with transparency
BufferedImage bimage = new BufferedImage(img.getWidth(null), img.getHeight(null), BufferedImage.TYPE_INT_ARGB);
// Draw the image on to the buffered image
Graphics2D bGr = bimage.createGraphics();
bGr.drawImage(img, 0, 0, null);
bGr.dispose();
return bimage;
}
@Override
public int getIconWidth() {
return width;
}
@Override
public int getIconHeight() {
return heigth;
}
}

118
src/gui/DrawboxEditor.java Normal file
View File

@ -0,0 +1,118 @@
package gui;
import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.event.ActionEvent;
import java.awt.event.MouseEvent;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JTabbedPane;
import model.Drawbox;
import model.Point;
public class DrawboxEditor extends Editable {
private List<Point> drawboxPoints;
private List<Point> basePoints;
Logger logger = Logger.getLogger("gui.DrawboxRectangleEditor");
Point currentPoint = new Point(0, 0);
DrawboxEditor(ListGUI listGUI) {
super(listGUI);
logger.setLevel(Level.CONFIG);
}
@Override
public void drawing(Graphics2D g) {
Drawbox drawbox = entity.getDrawbox();
drawboxPoints = drawbox.getDrawboxlistPoints();
basePoints = drawbox.getbaseListPoints();
logger.finest("drawbox point size: "+ drawboxPoints.size());
for(Point p: drawboxPoints)
logger.finest("DrawBoxPoint: ["+ p.x + ":"+p.y+"]");
for(Point p: basePoints)
logger.finest("BasePoint: ["+ p.x + ":"+p.y+"]");
if(drawboxPoints.size() >= 1 && drawboxPoints.size() < 4) {
Point lastPoint = drawboxPoints.get(drawboxPoints.size()-1);
g.drawLine((int)lastPoint.x, (int)lastPoint.y, (int)currentPoint.x, (int)currentPoint.y);
for(int i = 0; i < drawboxPoints.size()-1;i++) {
int x1 = (int)drawboxPoints.get(i).x;
int y1 = (int)drawboxPoints.get(i).y;
int x2 = (int)drawboxPoints.get(i+1).x;
int y2 = (int)drawboxPoints.get(i+1).y;
g.drawLine(x1, y1, x2, y2);
}
} else {
for(int i = 0; i < drawboxPoints.size();i++) {
int x1 = (int)drawboxPoints.get(i % drawboxPoints.size()).x;
int y1 = (int)drawboxPoints.get(i % drawboxPoints.size()).y;
int x2 = (int)drawboxPoints.get((i+1) % drawboxPoints.size()).x;
int y2 = (int)drawboxPoints.get((i+1) % drawboxPoints.size()).y;
g.drawLine(x1, y1, x2, y2);
}
// ОТРИСОВКА ОСНОВАНИЯ
g.setColor(Color.BLUE);
for(int i = 0; i < basePoints.size()-1;i++) {
int x1 = (int)basePoints.get(i).x;
int y1 = (int)basePoints.get(i).y;
int x2 = (int)basePoints.get(i+1).x;
int y2 = (int)basePoints.get(i+1).y;
g.drawLine(x1, y1+3, x2, y2+3);
}
}
}
@Override
public void saveDataInEntity() { }
@Override
public void mousePressed(MouseEvent e) {
if(drawboxPoints.size() < 4) {
Point p = new Point(e.getX(), e.getY());
drawboxPoints.add(p);
if(drawboxPoints.size() == 4) {
Point baseStart = drawboxPoints.get(0),
baseEnd = drawboxPoints.get(1);
for(Point pseudo: drawboxPoints) { // если не будет цикла в цикле - не выйдет сравнить всех со всеми
for(Point vertex: drawboxPoints) { // что приведёт к артефактам построения основания
if(vertex != baseStart && vertex != baseEnd) {
if(vertex.y >= baseStart.y) baseStart = vertex;
else if(vertex.y >= baseEnd.y) baseEnd = vertex;
}
}
}
basePoints.add(baseStart);
basePoints.add(baseEnd);
}
}
}
@Override
public void mouseMoved(MouseEvent e) {
currentPoint.x = e.getX();
currentPoint.y = e.getY();
repaint();
}
@Override
public void actionPerformed(ActionEvent e) {
JTabbedPane parent = (JTabbedPane) getParent();
if(parent.getSelectedComponent() == this){
if(entity != null) {
entity.getDrawbox().getDrawboxlistPoints().clear();
entity.getDrawbox().getbaseListPoints().clear();
repaint();
}
}
}
}

111
src/gui/Editable.java Normal file
View File

@ -0,0 +1,111 @@
package gui;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
import java.awt.image.BufferedImage;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import model.Entity;
import repository.Project;
public abstract class Editable extends JPanel implements MouseListener, MouseMotionListener, ListSelectionListener, ActionListener {
protected ListGUI listGUI;
protected Entity entity;
protected String name;
protected BufferedImage image;
JPanel drawPanel;
private static Logger logger = Logger.getLogger("gui.Editable");
Editable(ListGUI listGUI){
this.listGUI = listGUI;
addMouseListener(this);
addMouseMotionListener(this);
// РАСКОММЕНТИТЬ ЕСЛИ НУЖНО ВЫВОДИТЬ ПОДРОБНЫЕ ЛОГИ
logger.setLevel(Level.ALL);
}
//Абстрактные методы
public abstract void drawing(Graphics2D g);
public abstract void saveDataInEntity();
//методы родительского класса Editable
//get,set для name
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
//заполнить текущую сущность по имени.
public void setEntityByName(String name) throws Exception {
entity = Project.getInstance().getEntityByName(name);
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawImage(image, 0, 0, this);
if(entity != null) {
drawing((Graphics2D)g);
}
}
// из mouse motion listener'a
@Override
public void mouseDragged(MouseEvent e) {}
// этих ребят нас обязывает создать MouseListener, так что они здесь
@Override
public void mouseClicked(MouseEvent e) {}
@Override
public void mousePressed(MouseEvent e) {}
@Override
public void mouseEntered(MouseEvent e) {}
@Override
public void mouseExited(MouseEvent e) {}
@Override
public void mouseReleased(MouseEvent e) {}
@Override
public void valueChanged(ListSelectionEvent e) {
logger.log(Level.FINEST, "entering method {0} of class {1}", new Object[]{"MouseClicked()" , this.getClass().getName()});
//logger.entering(this.getClass().getName(), "MouseClicked()");
if(e.getSource() instanceof JList) {
//TODO: надо бы элегантнее пробросить сюда ListGUI - просто передача его в аргументах немножко громоздкая
// как-то обыграть это через события?
// ps. попытки обратиться к eventSource проваливаются - ListGUI это панель, уже внутри которой лежит JList
name = listGUI.getSelectedName();
try {
entity = Project.getInstance().getEntityByName(name);
} catch (Exception e1) {
logger.severe("Entity with name '"+name+"' was not found! Cannot display it on panel!");
}
image = Project.getInstance().loadImageByName(name);
//TODO: if(image == null) вызов FileChooser'a и выбор изображения
this.repaint();
}
}
}

View File

@ -0,0 +1,47 @@
package gui;
import java.awt.Graphics2D;
import java.awt.event.ActionEvent;
import java.awt.event.MouseEvent;
import javax.swing.JPanel;
public class HitboxCircleEditor extends Editable {
HitboxCircleEditor(ListGUI listGUI) {
super(listGUI);
// TODO Auto-generated constructor stub
}
@Override
public void drawing(Graphics2D g) {
// TODO Auto-generated method stub
}
@Override
public void saveDataInEntity() {
// TODO Auto-generated method stub
}
@Override
public void mouseClicked(MouseEvent e) {
// TODO Auto-generated method stub
}
@Override
public void mouseMoved(MouseEvent e) {
// TODO Auto-generated method stub
}
@Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
}
}

View File

@ -0,0 +1,48 @@
package gui;
import java.awt.Graphics2D;
import java.awt.event.ActionEvent;
import java.awt.event.MouseEvent;
import javax.swing.JPanel;
public class HitboxPoligonEditor extends Editable {
HitboxPoligonEditor(ListGUI listGUI) {
super(listGUI);
// TODO Auto-generated constructor stub
}
@Override
public void drawing(Graphics2D g) {
// TODO Auto-generated method stub
}
@Override
public void saveDataInEntity() {
// TODO Auto-generated method stub
}
@Override
public void mouseClicked(MouseEvent e) {
// TODO Auto-generated method stub
}
@Override
public void mouseMoved(MouseEvent e) {
// TODO Auto-generated method stub
}
@Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
}
}

View File

@ -0,0 +1,53 @@
package gui;
import java.awt.Graphics2D;
import java.awt.event.ActionEvent;
import java.awt.event.MouseEvent;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class HitboxRectangleEditor extends Editable {
HitboxRectangleEditor(ListGUI listGUI) {
super(listGUI);
// TODO Auto-generated constructor stub
}
@Override
public void drawing(Graphics2D g) {
// TODO Auto-generated method stub
}
@Override
public void saveDataInEntity() {
// TODO Auto-generated method stub
}
@Override
public void mouseClicked(MouseEvent e) {
// TODO Auto-generated method stub
}
@Override
public void mouseMoved(MouseEvent e) {
// TODO Auto-generated method stub
}
@Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
}
}

219
src/gui/ListGUI.java Normal file
View File

@ -0,0 +1,219 @@
package gui;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.Image;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.DefaultListCellRenderer;
import javax.swing.DefaultListModel;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.ListSelectionModel;
import javax.swing.event.ListSelectionListener;
import javax.xml.parsers.ParserConfigurationException;
import org.xml.sax.SAXException;
import listeners.CreateFrameAddElementListener;
import listeners.RemoveListElementEntityListener;
import model.Drawbox;
import model.Entity;
import model.Hitbox;
import model.Point;
import repository.Project;
public class ListGUI extends JPanel {
private Map<String, Icon> iconMap = new HashMap<>();
JButton addListElementEntity;
JButton removeListElementEntity;
JButton addPicEntity;
String pathImage;
JList list;
JScrollPane scroll;
ActionListener removeEntity;
ActionListener addEntity;
DefaultListModel<String> testModel;
private static Logger logger = Logger.getLogger("gui.ListGUI");
public ListGUI() {
try {
Project.getInstance().load();
} catch (SAXException | IOException | ParserConfigurationException e) {
// TODO: сделать нормальную обработку исключений - ситуации когда файл не существует, случилась ошибка парсинга и тд должны обрабатываться отдельно
// в идеале должны появляться разные окошки, которые обрисуют в чём проблема и предложения что делать
JOptionPane.showMessageDialog(this, "Parser exception, cause: "+e);
}
String[] nameList = createNameList();
testModel = new DefaultListModel<>();
list = new JList(testModel);
list.setCellRenderer(new ListEntityRenderer());
addEntity = new CreateFrameAddElementListener(this);
removeEntity = new RemoveListElementEntityListener(this);
scroll = new JScrollPane(list);
scroll.setSize(new Dimension(223, 638));
scroll.setLocation(5, 5);
this.add(scroll);
list.getSelectionModel().setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
addListElementEntity = createButton(5,645, addEntity,"res/addbutton.png");
removeListElementEntity = createButton(117,645,removeEntity,"res/deletebutton.png");
/// ЧТОБЫ ОТКЛЮЧИТЬ ИЗБЫТОЧНЫЙ ВЫВОД В КОНСОЛЬ - НУЖНО СМЕНИТЬ УРОВЕНЬ ЛОГГИРОВАНИЯ В СТРОКЕ НИЖЕ
logger.setLevel(Level.FINEST);
// в идеале достаточно уровня WARNING, но если нужна более точна информация о модуле - можно снизить уровень
updateList();
}
public String getSelectedName() {
return (String) list.getSelectedValue();
}
public void addListElement(String name,String solid) {
// плейсхолдеры для новых хитбоксов и дроубоксов, иначе всё валится с NPE
List<Point> hitboxPoints = new LinkedList<Point>();
List<Point> drawboxPoints = new LinkedList<Point>();
Hitbox hitbox = new Hitbox("Rectangle", hitboxPoints);
Drawbox drawbox = new Drawbox(drawboxPoints);
// а тут уже создание новой сущности
Entity e = new Entity(name, hitbox, drawbox);
e.setType(solid);
logger.finer("Entity \""+name+"\" was created.");
Project.getInstance().addEntity(e);
updateList();
}
public void updateList() {
String[] nameList = createNameList();
testModel.removeAllElements();
for (String name : nameList)
testModel.addElement(name);
pathImage = Project.getInstance().getXMLPath();
createImageMap(nameList);
list.updateUI();
}
/**
* Функция, формирующая список имён сущностей для JList, чтобы сформировать его итемы
* */
private String[] createNameList() {
//TODO: meh, хочется избавиться от использования списка - нехорошее это дело, лучше работать через интерфейс Project
int index = 0,
size = Project.getInstance().getListEntity().size();
String[] names = new String[size];
for(Entity e: Project.getInstance())
names[index++] = e.getName();
//TODO: не будет ли лучше хранить в JList не только имена, но и ссылки на сущности?
//было бы удобно по нажатию на итем JList'а сразу дёргать из него нужную сущность а
//из неё её хитбоксы и дроубоксы вместо вызовов по типу "Project.getInstance().getEntityByName(jListItem.getText())"
//НО! текущий вариант не требует написания кастомного JList, без которого в него целую сущность не запихать...
return names;
}
private final float iconMaxWidth = 40, iconMaxHeight = 40;
public Icon imageScaling(BufferedImage image) {
CustomIcon icon = null;
try {
int imageWidth = image.getWidth(), imageHeight = image.getHeight();
float scaleFactorX = iconMaxWidth / imageWidth, scaleFactorY = iconMaxHeight / imageHeight,
scaleFactor = scaleFactorX < scaleFactorY ? scaleFactorX : scaleFactorY;
// debug print
// System.out.printf("ImageWidth: %d, ImageHeight: %d, scaleFactorX: %f,
// scaleFactorY: %f, scaleFactor: %f \n", imageWidth, imageHeight, scaleFactorX,
// scaleFactorY, scaleFactor);
Image scaledImage = image.getScaledInstance((int) (imageWidth * scaleFactor),
(int) (imageHeight * scaleFactor), Image.SCALE_SMOOTH);
icon = new CustomIcon(scaledImage, (int) iconMaxWidth, (int) iconMaxHeight);
} catch (NullPointerException npe) {
logger.log(Level.WARNING, "Cannot scale icon for list item - the reference is null");
}
return icon;
}
public class ListEntityRenderer extends DefaultListCellRenderer
{
Font font = new Font("helvitica", Font.BOLD, 14);
@Override
public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus)
{
int iconTextOffset = 10;
JLabel label = (JLabel) super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus);
Entity e = null;
try {
e = Project.getInstance().getEntityByName((String)value);
String text = label.getText();
text = "<html>"+text+"<br>"+"<small>"+e.getType()+"</small>";
label.setText(text);
} catch (Exception e1) {
e1.printStackTrace();
}
Icon icon = iconMap.get((String) value);
if(icon != null) {
label.setIcon(icon);
label.setIconTextGap((int)iconMaxWidth - icon.getIconWidth() + iconTextOffset);
}
label.setFont(font);
return label;
}
}
private void createImageMap(String[] nameList) {
for (int i = 0; i < nameList.length; i++) {
String name = nameList[i];
BufferedImage image = Project.getInstance().loadImageByName(name);
iconMap.put(name, imageScaling(image));
}
}
private JButton createButton(int width,int height,ActionListener listener,String pathImage) {
JButton button = new JButton(new ImageIcon(pathImage));
button.setSize(110, 46);
button.setLocation(width, height);
button.addActionListener(listener);
button.setContentAreaFilled(false);
button.setFocusPainted(false);
this.add(button);
return button;
}
/**
* Немного костыль, который позволяет зарегестрировать слушатель мыши на списке компонентов
* не создавая излишне тесных связей между компонентами
* */
public void registerJListListener(ListSelectionListener ml) {
list.addListSelectionListener(ml);
}
public void printNameList(String[] nameList) {
System.out.println("вызван принт лист: "+nameList.length);
for(int i = 0;i<nameList.length;i++) {
System.out.println(nameList[i]);
}
}
}

115
src/gui/MainGUI.java Normal file
View File

@ -0,0 +1,115 @@
package gui;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Point;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.List;
import javax.swing.Box;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JScrollPane;
import javax.swing.JTabbedPane;
import listeners.OpenXMLFileButtonListener;
public class MainGUI extends JFrame{
ListGUI list;
ActionListener OpenXMLFileButtonListener;
JButton openXMLJButton;
JButton saveXMLJButton;
JButton clearLinesJButton;
public static JTabbedPane editorPane;
public static JTabbedPane hitdrawPane;
List <Editable> listEditorPanel = new ArrayList<Editable>();
DrawboxEditor drawBoxPanel;
HitboxCircleEditor hitboxCirclePanel;
HitboxRectangleEditor hitboxRectanglePanel;
HitboxPoligonEditor hitboxPoligonPanel;
public MainGUI() {
setTitle("Hitbox/Drawbox Editor");
setLayout(null);
setSize(1200,780);
setLocationRelativeTo(null);
setResizable(false);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
list = new ListGUI();
this.add(list);
list.setLayout(null);
list.setSize(230, 691);
list.setLocation(0, 47);
list.setVisible(true);
drawBoxPanel = new DrawboxEditor(list);
hitboxCirclePanel = new HitboxCircleEditor(list);
hitboxRectanglePanel = new HitboxRectangleEditor(list);
hitboxPoligonPanel = new HitboxPoligonEditor(list);
listEditorPanel.add(drawBoxPanel);
listEditorPanel.add(hitboxCirclePanel);
listEditorPanel.add(hitboxRectanglePanel);
listEditorPanel.add(hitboxPoligonPanel);
list.registerJListListener(drawBoxPanel);
list.registerJListListener(hitboxCirclePanel);
list.registerJListListener(hitboxPoligonPanel);
list.registerJListListener(hitboxRectanglePanel);
OpenXMLFileButtonListener = new OpenXMLFileButtonListener(list);
openXMLJButton = createButton("XML",5,5, OpenXMLFileButtonListener,"res/xml.png");
saveXMLJButton = createButton("Save",80,5,null,"res/download.png");
clearLinesJButton = createButton("Clear lines",155,5,null,"res/destroy.png");
clearLinesJButton.addActionListener(drawBoxPanel);
clearLinesJButton.addActionListener(hitboxCirclePanel);
clearLinesJButton.addActionListener(hitboxPoligonPanel);
clearLinesJButton.addActionListener(hitboxRectanglePanel);
repaint();
this.add(editorPane = createPane(editorPane, 230, 50));
editorPane.addTab("Hitbox", hitdrawPane = createPane(hitdrawPane,10, 10));
editorPane.addTab("Drawbox", drawBoxPanel);
hitdrawPane.addTab(null, new ImageIcon("res/square.png"),hitboxRectanglePanel, null);
hitdrawPane.addTab(null, new ImageIcon("res/circle.png"),hitboxCirclePanel, null);
hitdrawPane.addTab(null, new ImageIcon("res/formless.png"),hitboxPoligonPanel, null);
hitdrawPane.setTabPlacement(JTabbedPane.LEFT);
}
@Override
public void paint(Graphics g){
super.paint(g);
g.drawLine(0, 72, 1200, 72);
}
public JTabbedPane createPane(JTabbedPane pane, int x, int y) {
pane = new JTabbedPane();
pane.setSize(new Dimension(950, 688));
pane.setLocation(new Point(x, y));
pane.setVisible(true);
return pane;
}
private JButton createButton(String text,int width,int height,ActionListener listener,String pathImage) {
JButton button = new JButton(new ImageIcon(pathImage));
button.setSize(68, 34);
button.setLocation(width, height);
button.addActionListener(listener);
button.setContentAreaFilled(false);
button.setFocusPainted(false);
this.add(button);
return button;
}
}

View File

@ -0,0 +1,90 @@
package gui;
import java.awt.FlowLayout;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import listeners.AddListElementEntityListener;
import listeners.CopyImageToFile;
public class PropertyFrameAddElement extends JFrame {
JPanel contents;
JButton acceptSettingsJButton;
JButton addPuthImage;
JTextField nameTextField,typeTextField;
ActionListener acceptSettingListener;
ActionListener copyImageToFile;
JLabel nameLabel,typeLabel,imageLabel;
public PropertyFrameAddElement(ListGUI listGUI) {
this.setTitle("Add Entity");
this.setLayout(null);
this.setSize(400,250);
this.setLocationRelativeTo(null);
this.setResizable(false);
this.setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);
nameLabel = new JLabel("Введите имя сущности:");
nameLabel.setSize(150,20);
nameLabel.setLocation(20, 20);
typeLabel = new JLabel("Введите тип сущности:");
typeLabel.setSize(150,20);
typeLabel.setLocation(20, 50);
imageLabel = new JLabel("Для выбора нажмите:");
imageLabel.setSize(150,20);
imageLabel.setLocation(20, 108);
nameTextField = new JTextField();
nameTextField.setSize(200,20);
nameTextField.setLocation(160, 20);
typeTextField = new JTextField();
typeTextField.setSize(200,20);
typeTextField.setLocation(160, 50);
contents = new JPanel(new FlowLayout(FlowLayout.LEFT));
contents.setLayout(null);
contents.setSize(600,400);
contents.add(nameLabel);
contents.add(typeLabel);
contents.add(imageLabel);
contents.add(nameTextField);
contents.add(typeTextField);
acceptSettingListener = new AddListElementEntityListener(listGUI,this);
copyImageToFile = new CopyImageToFile(this);
acceptSettingsJButton = createButton("Accept", 148, 170, acceptSettingListener, null);
addPuthImage = createButton("Добавить image", 160, 100, copyImageToFile, null);
addPuthImage.setSize(160, 40);
contents.add(acceptSettingsJButton);
contents.add(addPuthImage);
setContentPane(contents);
}
private JButton createButton(String text,int width,int height,ActionListener listener,String pathImage) {
JButton button = new JButton(text);
button.setSize(90, 40);
button.setLocation(width, height);
button.addActionListener(listener);
button.setContentAreaFilled(false);
button.setFocusPainted(false);
this.add(button);
return button;
}
public String getInputName() {
String name = nameTextField.getText();
return name;
}
public String getInputType() {
String type = typeTextField.getText();
return type;
}
}

37
src/launch/Launcher.java Normal file
View File

@ -0,0 +1,37 @@
package launch;
import java.io.IOException;
import java.util.logging.Handler;
import java.util.logging.Level;
import java.util.logging.LogManager;
import java.util.logging.Logger;
import javax.xml.parsers.ParserConfigurationException;
import org.xml.sax.SAXException;
import gui.MainGUI;
public class Launcher {
public static void main(String[] args) throws SAXException, IOException, ParserConfigurationException {
// Настройка системы логгирования
// Указываем, в каком формате выводится строка в консоль
System.setProperty("java.util.logging.SimpleFormatter.format",
"[%1$tF %1$tT] [%4$-7s] %5$s %n");
Logger rootLogger = LogManager.getLogManager().getLogger("");
//указываем, какой уровень логгирования учитывается при выводе - всё что меньше заданного уровня откидывается
//p.s. уровень вывода и уровень регистрации (handler.level | logging.level) это не одно и то же
Handler[] handlers = rootLogger.getHandlers();
Level lv = Level.FINE;
for(int i = 0; i < handlers.length; i++) {
handlers[i].setLevel(lv);
}
rootLogger.info("Root Handler Logging level is "+lv.getName());
MainGUI gui = new MainGUI();
gui.setVisible(true);
}
}

View File

@ -0,0 +1,30 @@
package listeners;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JTextField;
import javax.swing.event.ListDataEvent;
import javax.swing.event.ListDataListener;
import gui.ListGUI;
import gui.PropertyFrameAddElement;
public class AddListElementEntityListener implements ActionListener
{
ListGUI listGUI;
PropertyFrameAddElement propertyFrame;
public AddListElementEntityListener(ListGUI listGUI,PropertyFrameAddElement propetry) {
this.listGUI = listGUI;
propertyFrame = propetry;
}
@Override
public void actionPerformed(ActionEvent e) {
listGUI.addListElement(propertyFrame.getInputName(),propertyFrame.getInputType());
propertyFrame.dispose();
}
}

View File

@ -0,0 +1,59 @@
package listeners;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
import javax.swing.filechooser.FileNameExtensionFilter;
import gui.PropertyFrameAddElement;
import repository.Project;
public class CopyImageToFile extends JFileChooser implements ActionListener {
File source;
File dest;
PropertyFrameAddElement propertyFrame;
public String directory = "res/";
public String file = "objecttypes.xml";
public CopyImageToFile(PropertyFrameAddElement propFrame){
propertyFrame = propFrame;
}
@Override
public void actionPerformed(ActionEvent e) {
dest = new File(Project.getInstance().getXMLPath()+propertyFrame.getInputName()+".png");
this.setDialogTitle("Choose file");
this.setFileSelectionMode(JFileChooser.FILES_ONLY);
FileNameExtensionFilter filter = new FileNameExtensionFilter("Image PNG", "png");
this.setFileFilter(filter);
int result = this.showOpenDialog(CopyImageToFile.this);
System.out.println("propertyFrame.getInputName() = "+propertyFrame.getInputName());
if (result == JFileChooser.APPROVE_OPTION && propertyFrame.getInputName()!=null)
{
System.out.println("Выбрали!!!!!!!!!!!!");
directory = this.getCurrentDirectory().toString()+'/';
file = this.getName(getSelectedFile()).toString();
source = new File(directory+file);
try {
copyFileUsingJava7Files(source,dest);
System.out.println("ФАЙЛ ВРОДЕ КАК ДОЛЖЕН БЫЛ СОЗДАТЬСЯ, ИДИ ПРОВЕРЬ");
} catch (IOException e1) {
JOptionPane.showMessageDialog(null, "Выбранное изображение уже существует!");
e1.printStackTrace();
}
}
}
// простой и удобный метод копирования файла в Java 7
private static void copyFileUsingJava7Files(File source, File dest) throws IOException {
Files.copy(source.toPath(), dest.toPath());
}
}

View File

@ -0,0 +1,24 @@
package listeners;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import gui.ListGUI;
import gui.PropertyFrameAddElement;
public class CreateFrameAddElementListener implements ActionListener {
PropertyFrameAddElement frameProperty;
ListGUI listGUI;
public CreateFrameAddElementListener(ListGUI listGUI) {
this.listGUI = listGUI;
}
@Override
public void actionPerformed(ActionEvent e) {
frameProperty = new PropertyFrameAddElement(listGUI);
frameProperty.setVisible(true);
}
}

View File

@ -0,0 +1,44 @@
package listeners;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JFileChooser;
import javax.swing.filechooser.FileNameExtensionFilter;
import gui.ListGUI;
import repository.Project;
public class OpenXMLFileButtonListener extends JFileChooser implements ActionListener
{
//public String directory = "C:\\Users\\sivan\\Desktop\\Диплом\\GUI-Collision&Drawing-Metadata-Editor\\res\\";
public String directory = "res/";
public String file = "objecttypes.xml";
ListGUI listGUI;
public OpenXMLFileButtonListener(ListGUI listGUI) {
this.listGUI = listGUI;
}
@Override
public void actionPerformed(ActionEvent e)
{
this.setDialogTitle("Choose file");
this.setFileSelectionMode(JFileChooser.FILES_ONLY);
FileNameExtensionFilter filter = new FileNameExtensionFilter("Xml File", "xml");
this.setFileFilter(filter);
int result = this.showOpenDialog(OpenXMLFileButtonListener.this);
if (result == JFileChooser.APPROVE_OPTION )
{
directory = this.getCurrentDirectory().toString()+'/';
file = this.getName(getSelectedFile()).toString();
Project.getInstance().load(directory, file);
listGUI.updateList();
//Debug
System.out.println(directory + file);
}
}
}

View File

@ -0,0 +1,32 @@
package listeners;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.List;
import gui.ListGUI;
import model.Entity;
import repository.Project;
public class RemoveListElementEntityListener implements ActionListener{
ListGUI listGUI;
public RemoveListElementEntityListener(ListGUI listGUI) {
this.listGUI = listGUI;
}
@Override
public void actionPerformed(ActionEvent event) {
String name = listGUI.getSelectedName();
if(name == null) return;
// System.out.println(name);
try {
Entity e = Project.getInstance().getEntityByName(name);
Project.getInstance().removeEntity(e);
listGUI.updateList();
} catch (Exception exception) {
exception.printStackTrace();
}
}
}

Some files were not shown because too many files have changed in this diff Show More