I'm trying to do a quite easy boardgame (Carcassonne) but I'm having a lot of troubles with the graphic interface. The problem is that I don't see the way to make a relation between the mouse clicks and the gridpane row and columns.
The first tile is given and it's always added to the 100, 100 gridpanes position. You won't see it in the code, but for each tile added if the adjacents are empty it's added a white tile, so it looks like this:
Then, the player is expected to do a legal move ( we're not controlling cheaters, so yeah, it will be a weak game ) in the positions x = 99 y = 100, x = 101 y = 100, x = 100 y = 99, x = 100 y = 101.
But when i click there using the method play() the e.getSceneX(); method returns me the pixel position, and I need a way to convert it to a valid row index. So this is happening:
This is the console output:
tile XCCCC added at 100 100 // this is always given by the program, it's always the same
tile MFFCF added at 391 380
In this case, I clicked to the x = 100 y = 101 gridpane but the mouse returned me the pixel 391, 380.
Any idea?
This is the structure of my code:
public final class GUI extends Application {
private Game _game;
private GridPane _visualBoard;
#Override
public void start(final Stage primaryStage) {
// some stuff setting the gridpane, which will be inside a scrollpane and the scrollpane will be inside a borderpane which will alse have 2 additional VBoxes with the current turn information
play();
primaryStage.show();
}
public static void main(String[] args) {
Application.launch(args);
}
public void play() {
_visualBoard.setOnMousePressed((MouseEvent e) -> {
double x = e.getSceneX();
double y = e.getSceneY();
_game.doMove(x, y);
});
}
public void insertTile(myTile r, int x, int y) {
myVisualTile rV = new myVisualTile(r);
_visualBoard.add(rV, x, y);
}
And this is the class game:
public class Game {
private GUI _gui;
private List<Player> _players; // An arraylist of players
private int _currentPlayer; // The index of the current player in the ArrayList
private Board _board; // The logical board, totally separeted from the gridpane
private tileStack _stack;
public void doMove(double x, double y) {
int ax = (int) x;
int ay = (int) y;
if (_stack.isEmpty()) {
System.out.println("Game finnished");
//stuff
}
else {
myTile r = _stack.poll(); // takes the first tile of the stack
_gui.insertTile(r, ax, ay);
}
}
public void play() {
_visualBoard.setOnMousePressed((MouseEvent e) -> {
Node source = (Node)e.getTarget() ;
Integer x = GridPane.getColumnIndex(source);
Integer y = GridPane.getRowIndex(source);
_game.doMove(x, y);
});
}
That actualy worked. Thanks everybody!
I wrote a program that allows a user to add nodes and connect them with edges with a GUI interface. The first node is always labeled "0". When I call the findPath method however it shows the entire path appropriately just lacking the 0. For example if I want to find the path from 0-4, and they're all connected numerically it will show [1,2,3,4]. To get a proper reading of the path after connecting the nodes you need to hit the print adjacency button. Everything else is running as expected but I can't seem to figure out why this won't add the first node.
Thanks Guys!
import javax.swing.JFrame;//imports JFrame package
public class Graph//class header
{
public static void main (String[] args)//main method
{
JFrame frame = new JFrame ("Directed Graph");//sets variable frame to a JFrame object and titles it
frame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);//exits application when it is closed
frame.getContentPane().add (new GraphPanel());//adding GraphPanel() to the frame
frame.setLocationRelativeTo(null);//sets location to the center
frame.pack();//packs the frame, fits everything inside
frame.setVisible(true);//makes frame visible
}
}
import java.util.ArrayList;//all of these are the required to get classes from other packages
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.JPanel;
public class GraphPanel extends JPanel
{
private final int SIZE = 10; // radius of each node
private double alpha; // double variable to define later
private JButton print, create, delete, path1; //allpath;//button variables
private JTextField label, label1;
boolean mode = true;//sets boolean for entire class to true, until later when I define it as false for certain methods to be complete
String x1, y1;
String str1 = new String("Mode Chosen Is : create" );//when you choose create it will print this instead
String str2 = new String("Mode Chosen Is : delete" );//when you choose delete it will print this
int x, y;
int mode1 = 1; // int mode1 variable, will comment why i need this when it is later defined/changed
private Point point1 = null, point2 = null, point3 = null;//makes pointers null, i added a third pointer to put the distance from the first drawn string at the top right, but no longer needed it
//keeping it incase I wanted to add it again
private ArrayList<Point> nodeList; // Graph nodes
private ArrayList<Edge> edgeList; // Graph edges
static private int[][] a = new int[100][100]; // Graph adjacency matrix
static ArrayList<Integer> path = new ArrayList<Integer>();
public GraphPanel()
{
nodeList = new ArrayList<Point>();//declares ArrayList<Point>
edgeList = new ArrayList<Edge>();//declares ArrayList<Edge>
GraphListener listener = new GraphListener();//assigns 'listener' to a Graphlistener object
addMouseListener (listener);//accepts and reads mouseListener methods to the GraphListener object
addMouseMotionListener (listener);//accepts and reads MouseMotionListener methods to the GraphListener object
label = new JTextField (1);
label1 = new JTextField (1);
//allpath = new JButton ("Find All Paths");
path1 = new JButton ("Find Path");//path button
create = new JButton("Create");//declares 'create' as a JButton object with text on it that says 'create'
delete = new JButton("Delete");//declares 'delete' as a JButton object with text that says 'delete'
JButton print = new JButton("Print adjacency matrix");//declares 'print' as a JButton object with text that reads 'print adjacency matrix'
print.addActionListener (new ButtonListener());//adds an action listener to the print button from the buttonlistener object
create.addActionListener (new ButtonListener1());//adds an actionListener to the create button from the buttonlistener1 object
delete.addActionListener (new ButtonListener2());//adds an actionliseneer to the delete button from the buttonlistener2 object
path1.addActionListener (new ButtonListener3());//adds button that will find path of nodes
//allpath.addActionListener (new ButtonListener4());
setBackground (Color.black);//sets backround as black
setPreferredSize (new Dimension(400, 300));//this is preferred size of graphpanel
add(print);//these next six add()'s add each button to GraphPanel
add(delete);//
add(create);//
//add(allpath);
add(path1);
add(label);
add(label1);
}
public static boolean findPath(int x, int y) //boolean method findpath that takes two ints as parameters
{
boolean found = false;
if (a[x][y]==1) //base case
{
//System.out.println(x + " -> " + y);//prints node -> node
found = true;//path is found
path.add(0,y);
}
else
{
int z;
for (z=0; !found& z<a.length; z++)
{
if (a[x][z]==1)
{
a[x][z]=2;
found = findPath(z,y);
}
if (found)
{
//System.out.println(x + " -> " + z);
path.add(0,z);
}
}
}
if (!found){
System.out.println("Path Does Not Exist");
}
return found;
}
// public static ArrayList findPath1(int x, int y, ArrayList path)
// {
// System.out.println("CALL FIND: " + path);
// ArrayList path2 = null;
// if (a[x][y]==1)
// {
// ArrayList path3 = (ArrayList)path.clone();
// path3.add(y);
// System.out.println("EXIT BASE: " + path3);
// path2 = path3;
// }
// else
// {
// int z;
// for (z=0; z<a.length; z++)
// if (a[x][z]==1)
// {
// ArrayList path3 = (ArrayList)path.clone();
// path3.add(z);
// path3 = findPath1(z,y,path3);
// System.out.println("EXIT RECU: " + path);
// path2 = path3;
// }
// }
// return path2;
// }
// Draws the graph
public void paintComponent (Graphics page)
{
super.paintComponent(page);//using parent methods
// Draws the edge that is being dragged
page.setColor (Color.green);//setting color of what will be drawn to green
if (mode1 == 1)//if mode1 is set to 1, which is when the create button is selected
{
page.drawString(str1, 125, 75);//then this is printed
}
if (mode1 == 2)//if mode1 is set to 2, which is when the delete button is selected
{
page.drawString(str2, 125, 75);//then this is printed
}
if (point1 != null && point2 != null)//if and only if both points are not null
{
page.drawLine (point1.x, point1.y, point2.x, point2.y);//then it draws the line from between point1(x, y cords), and point2(x, y cords)
page.fillOval (point2.x-3, point2.y-3, 6, 6);//fills this oval by the rectangle it is specified from
}
// Draws the nodes
for (int i=0; i<nodeList.size(); i++) //for loop going through the nodeList ArrayList
{
page.setColor (Color.green);//color is set to green
page.fillOval (nodeList.get(i).x-SIZE, nodeList.get(i).y-SIZE, SIZE*2, SIZE*2);//fills oval by subtracting the SIZE from the x, y and setting the height and width as two times the SIZE
page.setColor (Color.black);//sets next line to black
page.drawString (String.valueOf(i), nodeList.get(i).x-SIZE/2, nodeList.get(i).y+SIZE/2);//writes inside the node what number index it is from the ArrayList with black text
}
// Draws the edges
for (int i=0; i<edgeList.size(); i++) // for loop going through the edgeList ArrayList
{
page.setColor (Color.green);//sets the next line to green
page.drawLine (edgeList.get(i).a.x, edgeList.get(i).a.y,edgeList.get(i).b.x, edgeList.get(i).b.y);//draws the line from x and y cords of where it starts to end
//page.fillOval (edgeList.get(i).b.x-3, edgeList.get(i).b.y-3, 6, 6);
//page.drawString (String.valueOf(point1.x*(point2.y-point3.y)+point2.x*(point3.y-point1.y)+point3.x*(point1.y-point2.y)), 5, 15);
alpha = Math.atan((double)(edgeList.get(i).b.y-edgeList.get(i).a.y)/(edgeList.get(i).b.x-edgeList.get(i).a.x));//alpha = b.y-a.y cords/b.x-a.x chords as a double variable
if (edgeList.get(i).a.x > edgeList.get(i).b.x)//if the x chord of a is greater than the x cordinate of b
{
alpha = alpha + Math.PI;//then alpha = previously defined alpha multiplied by PI
}
if (edgeList.get(i).a.x < edgeList.get(i).b.x && edgeList.get(i).a.y > edgeList.get(i).b.y)//if a.x is less than b.x and a.y is less than b.y
{
alpha = alpha + 2*Math.PI;//then alpha becomes the previously defined alpha multiplied by 2 PI
}
arrow(page,edgeList.get(i).b.x,edgeList.get(i).b.y,0,1.57-alpha);//arrow method, taking a x(edgeList.get(i).b.x, y(edgeList.get(i).b.y, length = 0 so arrow is at the
// very end of the drawn line subtracted by a double aplha
}
}
// arrow method to call when making an arrow
private void arrow(Graphics page, int x, int y, int len, double alpha)//arrow method, taking a x, y, length and double parameter
{
page.setColor (Color.green);//sets arrow to green
int x1 = x+(int)(len*Math.sin(alpha));//x1 is set to x plus length *sin of alpha
int y1 = y+(int)(len*Math.cos(alpha));//y1 is set to y plus the length * cosin of alpha
page.drawLine (x, y, x1, y1);//drawa the x and y, and then previously defined x1, and y1
page.drawLine (x1, y1, x1+(int)(20*Math.sin(alpha+2.5)), y1+(int)(20*Math.cos(alpha+2.5)));//arithmatic to draw one side of the line for the arrow
page.drawLine (x1, y1, x1+(int)(20*Math.sin(alpha+3.7)), y1+(int)(20*Math.cos(alpha+3.7)));//arithmatic to draw the corresponding line for the arrow to complete the arrow
}
// The listener for mouse events.
private class GraphListener implements MouseListener, MouseMotionListener//GraphListener which implements MouseListener and MouseMotionListener, meaning it takes methods from both of those classes
{
public void mouseClicked (MouseEvent event)//when mouse is clicked and released
{
if (mode == true)//if the mode is true
{
nodeList.add(event.getPoint());//the current point to the nodeList
repaint();//whenever you change the look of a componenet you call this method
}
if (mode == false)//if boolean mode is false
{
for (int i=0; i<nodeList.size(); i++)//for loop to go through the nodeList ArrayList
{
if (distance(nodeList.get(i), event.getPoint()) < SIZE)//if the distance between a specific node and the pointer is less than the radius of the node (SIZE)
nodeList.remove(i);//then remove that node
}
for (int i=0; i<edgeList.size(); i++)
{
if (distance(edgeList.get(i).a, event.getPoint())+distance(event.getPoint(), edgeList.get(i).b)-distance(edgeList.get(i).a, edgeList.get(i).b) < SIZE)
//if the (distance between starting point of that edgelist index and the current point) plus (the distance between the current point and ending point of that edgeList index)
//subtracted by the (distance of the starting and ending point of that edgeList index)(AB+BC-AC) is all less than the size
edgeList.remove(i);//then remove that index
}
}
}
public void mousePressed (MouseEvent event)//when the mouse is pressed down
{
if (mode == true)//if the mode is true
{
point1 = event.getPoint();//you start that point
}
}
public void mouseDragged (MouseEvent event)//when the mouse is dragged while pressed down
{
if (mode == true)//if the mode is true
{
point2 = event.getPoint();//then you get the second point
repaint();//must use this method because you are making a change to the component
}
}
public void mouseReleased (MouseEvent event)//when the mouse is released after being pressed (not to be confused with a click)
{
if (mode == true)//if the mode is true
{
point2 = event.getPoint();//then you set point2 to where that point landed
if (point1.x != point2.x && point1.y != point2.y)//if the points are not in the same spots
{
edgeList.add(new Edge(point1,point2));//then you add a new edgeList element to the ArrayList, by definition of Edge() object
repaint();//must use this method because changes to component have been made
}
}
}
public void mouseMoved (MouseEvent event)// if the mouse is moved, without it being clicked (not to be confused by mouseDragged)
{
point3 = event.getPoint();//point three is set to be where the mouse is at the current time(used this to find the distance of original edge drawn, keeping here incase I want to add)
repaint();//must use this method because changes were made to component
}
// Empty definitions for unused event methods.
public void mouseEntered (MouseEvent event){}//when the mouse enters a component
public void mouseExited (MouseEvent event) {}//when the mouse exits a component
private int distance(Point p1, Point p2) //private distance formula but inside of this class so i was able to use it for determining how to erase nodes and edges
{
return (int)Math.sqrt((p1.x-p2.x)*(p1.x-p2.x)+(p1.y-p2.y)*(p1.y-p2.y));//square root of x cordinants of first point minus second point times its self plus the y coordinates
//of first point minus second point times itself
}
}
// Represents the graph edges
private class Edge //defines how edges are made
{
Point a, b;
public Edge(Point a, Point b)
{
this.a = a;
this.b = b;
}
}
private class ButtonListener implements ActionListener
{
public void actionPerformed (ActionEvent event)
{
if (event.getSource()== create)
{
mode = true;
mode1 = 1;
}
if (event.getSource()==delete)
{
mode = !true;
mode1 = 2;
}
// Initializes graph adjacency matrix
for (int i=0; i<nodeList.size(); i++)
for (int j=0; j<nodeList.size(); j++) a[i][j]=0;
// Includes the edges in the graph adjacency matrix
for (int i=0; i<edgeList.size(); i++)
{
for (int j=0; j<nodeList.size(); j++)
if (distance(nodeList.get(j),edgeList.get(i).a)<=SIZE+3)
for (int k=0; k<nodeList.size(); k++)
if (distance(nodeList.get(k),edgeList.get(i).b)<=SIZE+3)
{
System.out.println(j+"->"+k);
a[j][k]=1;
}
}
if (event.getSource()==print)
{
// Prints the graph adjacency matrix
for (int i=0; i<nodeList.size(); i++)
{
for (int j=0; j<nodeList.size(); j++)
System.out.print(a[i][j]+"\t");
System.out.println();
}
}
}
// Euclidean distance function
private int distance(Point p1, Point p2)
{
return (int)Math.sqrt((p1.x-p2.x)*(p1.x-p2.x)+(p1.y-p2.y)*(p1.y-p2.y));
}
}
private class ButtonListener1 implements ActionListener
{
public void actionPerformed (ActionEvent event)
{
if (event.getSource()== create)//if create button is selected
{
mode = true;//then the mode is set to true
mode1 = 1;//and mode1 is set to 1
}
}
}
private class ButtonListener2 implements ActionListener
{
public void actionPerformed (ActionEvent event)
{
if (event.getSource()== delete)//if create button is selected
{
mode = !true;//then the mode is set to true
mode1 = 2;//and mode1 is set to 2, which would change the string that is output
}
}
}
private class ButtonListener3 implements ActionListener
{
public void actionPerformed (ActionEvent event)
{
x1 = label.getText();
y1 = label1.getText();
x = Integer.parseInt(x1);
y = Integer.parseInt(y1);
System.out.println("Path from " +x+" to " +y);
System.out.println(findPath(x,y));
System.out.println(path);
}
}
You just never add the first node to path. You can do it when you check if path exists:
if (!found){
System.out.println("Path Does Not Exist");
} else {
path.add(0, x);
}
and then you also need to remove this block:
if (found) {
//System.out.println(x + " -> " + z);
path.add(0,z);
}
So complete method will look like
public static boolean findPath(int x, int y) //boolean method findpath that takes two ints as parameters
{
boolean found = false;
if (a[x][y]==1) //base case
{
//System.out.println(x + " -> " + y);//prints node -> node
found = true;//path is found
path.add(0,y);
}
else
{
int z;
for (z=0; !found& z<a.length; z++)
{
if (a[x][z]==1)
{
a[x][z]=2;
found = findPath(z,y);
}
/*if (found)
{
//System.out.println(x + " -> " + z);
path.add(0,z);
}*/
}
}
if (!found){
System.out.println("Path Does Not Exist");
} else {
path.add(0,x);
}
return found;
}
I also suggest you to look at Dijkstra's algorithm of finding the shortest path between nodes
I was able to find it, and of course it was the smallest mistake I missed, adding this because in case anyone else has the same problem I hope this helps. The main differences are in my buttonlistener3 class but I'll add the whole thing again just incase this helps anyone out.
import java.util.ArrayList;//all of these are the required to get classes from other packages
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.JPanel;
public class GraphPanel extends JPanel
{
private final int SIZE = 10; // radius of each node
private double alpha; // double variable to define later
private JButton print, create, delete, path1; //allpath;//button variables
private JTextField label, label1;
boolean mode = true;//sets boolean for entire class to true, until later when I define it as false for certain methods to be complete
String x1, y1;
String str1 = new String("Mode Chosen Is : create" );//when you choose create it will print this instead
String str2 = new String("Mode Chosen Is : delete" );//when you choose delete it will print this
int x, y;
int mode1 = 1; // int mode1 variable, will comment why i need this when it is later defined/changed
private Point point1 = null, point2 = null, point3 = null;//makes pointers null, i added a third pointer to put the distance from the first drawn string at the top right, but no longer needed it
//keeping it incase I wanted to add it again
private ArrayList<Point> nodeList; // Graph nodes
private ArrayList<Edge> edgeList; // Graph edges
static private int[][] a = new int[100][100]; // Graph adjacency matrix
static ArrayList<Integer> path = new ArrayList<Integer>();
public GraphPanel()
{
nodeList = new ArrayList<Point>();//declares ArrayList<Point>
edgeList = new ArrayList<Edge>();//declares ArrayList<Edge>
GraphListener listener = new GraphListener();//assigns 'listener' to a Graphlistener object
addMouseListener (listener);//accepts and reads mouseListener methods to the GraphListener object
addMouseMotionListener (listener);//accepts and reads MouseMotionListener methods to the GraphListener object
label = new JTextField (1);
label1 = new JTextField (1);
//allpath = new JButton ("Find All Paths");
path1 = new JButton ("Find Path");//path button
create = new JButton("Create");//declares 'create' as a JButton object with text on it that says 'create'
delete = new JButton("Delete");//declares 'delete' as a JButton object with text that says 'delete'
JButton print = new JButton("Print adjacency matrix");//declares 'print' as a JButton object with text that reads 'print adjacency matrix'
print.addActionListener (new ButtonListener());//adds an action listener to the print button from the buttonlistener object
create.addActionListener (new ButtonListener1());//adds an actionListener to the create button from the buttonlistener1 object
delete.addActionListener (new ButtonListener2());//adds an actionliseneer to the delete button from the buttonlistener2 object
path1.addActionListener (new ButtonListener3());//adds button that will find path of nodes
//allpath.addActionListener (new ButtonListener4());
setBackground (Color.black);//sets backround as black
setPreferredSize (new Dimension(400, 300));//this is preferred size of graphpanel
add(print);//these next six add()'s add each button to GraphPanel
add(delete);//
add(create);//
//add(allpath);
add(path1);
add(label);
add(label1);
}
public static boolean findPath(int x, int y) //boolean method findpath that takes two ints as parameters
{
boolean found = false;
if (a[x][y]==1) //base case
{
//System.out.println(x + " -> " + y);//prints node -> node
found = true;//path is found
path.add(0,y);
}
else
{
int z;
for (z=0; !found& z<a.length; z++)
{
if (a[x][z]==1)
{
a[x][z]=2;
found = findPath(z,y);
}
if (found)
{
//System.out.println(x + " -> " + z);
path.add(0,z);
}
}
}
return found;
}
// public static ArrayList findPath1(int x, int y, ArrayList path)
// {
// System.out.println("CALL FIND: " + path);
// ArrayList path2 = null;
// if (a[x][y]==1)
// {
// ArrayList path3 = (ArrayList)path.clone();
// path3.add(y);
// System.out.println("EXIT BASE: " + path3);
// path2 = path3;
// }
// else
// {
// int z;
// for (z=0; z<a.length; z++)
// if (a[x][z]==1)
// {
// ArrayList path3 = (ArrayList)path.clone();
// path3.add(z);
// path3 = findPath1(z,y,path3);
// System.out.println("EXIT RECU: " + path);
// path2 = path3;
// }
// }
// return path2;
// }
// Draws the graph
public void paintComponent (Graphics page)
{
super.paintComponent(page);//using parent methods
// Draws the edge that is being dragged
page.setColor (Color.green);//setting color of what will be drawn to green
if (mode1 == 1)//if mode1 is set to 1, which is when the create button is selected
{
page.drawString(str1, 125, 75);//then this is printed
}
if (mode1 == 2)//if mode1 is set to 2, which is when the delete button is selected
{
page.drawString(str2, 125, 75);//then this is printed
}
if (point1 != null && point2 != null)//if and only if both points are not null
{
page.drawLine (point1.x, point1.y, point2.x, point2.y);//then it draws the line from between point1(x, y cords), and point2(x, y cords)
page.fillOval (point2.x-3, point2.y-3, 6, 6);//fills this oval by the rectangle it is specified from
}
// Draws the nodes
for (int i=0; i<nodeList.size(); i++) //for loop going through the nodeList ArrayList
{
page.setColor (Color.green);//color is set to green
page.fillOval (nodeList.get(i).x-SIZE, nodeList.get(i).y-SIZE, SIZE*2, SIZE*2);//fills oval by subtracting the SIZE from the x, y and setting the height and width as two times the SIZE
page.setColor (Color.black);//sets next line to black
page.drawString (String.valueOf(i), nodeList.get(i).x-SIZE/2, nodeList.get(i).y+SIZE/2);//writes inside the node what number index it is from the ArrayList with black text
}
// Draws the edges
for (int i=0; i<edgeList.size(); i++) // for loop going through the edgeList ArrayList
{
page.setColor (Color.green);//sets the next line to green
page.drawLine (edgeList.get(i).a.x, edgeList.get(i).a.y,edgeList.get(i).b.x, edgeList.get(i).b.y);//draws the line from x and y cords of where it starts to end
//page.fillOval (edgeList.get(i).b.x-3, edgeList.get(i).b.y-3, 6, 6);
//page.drawString (String.valueOf(point1.x*(point2.y-point3.y)+point2.x*(point3.y-point1.y)+point3.x*(point1.y-point2.y)), 5, 15);
alpha = Math.atan((double)(edgeList.get(i).b.y-edgeList.get(i).a.y)/(edgeList.get(i).b.x-edgeList.get(i).a.x));//alpha = b.y-a.y cords/b.x-a.x chords as a double variable
if (edgeList.get(i).a.x > edgeList.get(i).b.x)//if the x chord of a is greater than the x cordinate of b
{
alpha = alpha + Math.PI;//then alpha = previously defined alpha multiplied by PI
}
if (edgeList.get(i).a.x < edgeList.get(i).b.x && edgeList.get(i).a.y > edgeList.get(i).b.y)//if a.x is less than b.x and a.y is less than b.y
{
alpha = alpha + 2*Math.PI;//then alpha becomes the previously defined alpha multiplied by 2 PI
}
arrow(page,edgeList.get(i).b.x,edgeList.get(i).b.y,0,1.57-alpha);//arrow method, taking a x(edgeList.get(i).b.x, y(edgeList.get(i).b.y, length = 0 so arrow is at the
// very end of the drawn line subtracted by a double aplha
}
}
// arrow method to call when making an arrow
private void arrow(Graphics page, int x, int y, int len, double alpha)//arrow method, taking a x, y, length and double parameter
{
page.setColor (Color.green);//sets arrow to green
int x1 = x+(int)(len*Math.sin(alpha));//x1 is set to x plus length *sin of alpha
int y1 = y+(int)(len*Math.cos(alpha));//y1 is set to y plus the length * cosin of alpha
page.drawLine (x, y, x1, y1);//drawa the x and y, and then previously defined x1, and y1
page.drawLine (x1, y1, x1+(int)(20*Math.sin(alpha+2.5)), y1+(int)(20*Math.cos(alpha+2.5)));//arithmatic to draw one side of the line for the arrow
page.drawLine (x1, y1, x1+(int)(20*Math.sin(alpha+3.7)), y1+(int)(20*Math.cos(alpha+3.7)));//arithmatic to draw the corresponding line for the arrow to complete the arrow
}
// The listener for mouse events.
private class GraphListener implements MouseListener, MouseMotionListener//GraphListener which implements MouseListener and MouseMotionListener, meaning it takes methods from both of those classes
{
public void mouseClicked (MouseEvent event)//when mouse is clicked and released
{
if (mode == true)//if the mode is true
{
nodeList.add(event.getPoint());//the current point to the nodeList
repaint();//whenever you change the look of a componenet you call this method
}
if (mode == false)//if boolean mode is false
{
for (int i=0; i<nodeList.size(); i++)//for loop to go through the nodeList ArrayList
{
if (distance(nodeList.get(i), event.getPoint()) < SIZE)//if the distance between a specific node and the pointer is less than the radius of the node (SIZE)
nodeList.remove(i);//then remove that node
}
for (int i=0; i<edgeList.size(); i++)
{
if (distance(edgeList.get(i).a, event.getPoint())+distance(event.getPoint(), edgeList.get(i).b)-distance(edgeList.get(i).a, edgeList.get(i).b) < SIZE)
//if the (distance between starting point of that edgelist index and the current point) plus (the distance between the current point and ending point of that edgeList index)
//subtracted by the (distance of the starting and ending point of that edgeList index)(AB+BC-AC) is all less than the size
edgeList.remove(i);//then remove that index
}
}
}
public void mousePressed (MouseEvent event)//when the mouse is pressed down
{
if (mode == true)//if the mode is true
{
point1 = event.getPoint();//you start that point
}
}
public void mouseDragged (MouseEvent event)//when the mouse is dragged while pressed down
{
if (mode == true)//if the mode is true
{
point2 = event.getPoint();//then you get the second point
repaint();//must use this method because you are making a change to the component
}
}
public void mouseReleased (MouseEvent event)//when the mouse is released after being pressed (not to be confused with a click)
{
if (mode == true)//if the mode is true
{
point2 = event.getPoint();//then you set point2 to where that point landed
if (point1.x != point2.x && point1.y != point2.y)//if the points are not in the same spots
{
edgeList.add(new Edge(point1,point2));//then you add a new edgeList element to the ArrayList, by definition of Edge() object
repaint();//must use this method because changes to component have been made
}
}
}
public void mouseMoved (MouseEvent event)// if the mouse is moved, without it being clicked (not to be confused by mouseDragged)
{
point3 = event.getPoint();//point three is set to be where the mouse is at the current time(used this to find the distance of original edge drawn, keeping here incase I want to add)
repaint();//must use this method because changes were made to component
}
// Empty definitions for unused event methods.
public void mouseEntered (MouseEvent event){}//when the mouse enters a component
public void mouseExited (MouseEvent event) {}//when the mouse exits a component
private int distance(Point p1, Point p2) //private distance formula but inside of this class so i was able to use it for determining how to erase nodes and edges
{
return (int)Math.sqrt((p1.x-p2.x)*(p1.x-p2.x)+(p1.y-p2.y)*(p1.y-p2.y));//square root of x cordinants of first point minus second point times its self plus the y coordinates
//of first point minus second point times itself
}
}
// Represents the graph edges
private class Edge //defines how edges are made
{
Point a, b;
public Edge(Point a, Point b)
{
this.a = a;
this.b = b;
}
}
private class ButtonListener implements ActionListener
{
public void actionPerformed (ActionEvent event)
{
if (event.getSource()== create)
{
mode = true;
mode1 = 1;
}
if (event.getSource()==delete)
{
mode = !true;
mode1 = 2;
}
// Initializes graph adjacency matrix
for (int i=0; i<nodeList.size(); i++)
for (int j=0; j<nodeList.size(); j++) a[i][j]=0;
// Includes the edges in the graph adjacency matrix
for (int i=0; i<edgeList.size(); i++)
{
for (int j=0; j<nodeList.size(); j++)
if (distance(nodeList.get(j),edgeList.get(i).a)<=SIZE+3)
for (int k=0; k<nodeList.size(); k++)
if (distance(nodeList.get(k),edgeList.get(i).b)<=SIZE+3)
{
System.out.println(j+"->"+k);
a[j][k]=1;
}
}
if (event.getSource()==print)
{
// Prints the graph adjacency matrix
for (int i=0; i<nodeList.size(); i++)
{
for (int j=0; j<nodeList.size(); j++)
System.out.print(a[i][j]+"\t");
System.out.println();
}
}
}
// Euclidean distance function
private int distance(Point p1, Point p2)
{
return (int)Math.sqrt((p1.x-p2.x)*(p1.x-p2.x)+(p1.y-p2.y)*(p1.y-p2.y));
}
}
private class ButtonListener1 implements ActionListener
{
public void actionPerformed (ActionEvent event)
{
if (event.getSource()== create)//if create button is selected
{
mode = true;//then the mode is set to true
mode1 = 1;//and mode1 is set to 1
}
}
}
private class ButtonListener2 implements ActionListener
{
public void actionPerformed (ActionEvent event)
{
if (event.getSource()== delete)//if create button is selected
{
mode = !true;//then the mode is set to true
mode1 = 2;//and mode1 is set to 2, which would change the string that is output
}
}
}
private class ButtonListener3 implements ActionListener
{
public void actionPerformed (ActionEvent event)
{
x1 = label.getText();
y1 = label1.getText();
x = Integer.parseInt(x1);
y = Integer.parseInt(y1);
System.out.println("Path from " +x+" to " +y);
System.out.println(findPath(x,y));
path.add(0,x);
System.out.println(path);
path.clear();
}
}
// private class ButtonListener4 implements ActionListener
// {
// public void actionPerformed (ActionEvent event)
// {
// x1 = label.getText();
// y1 = label1.getText();
// x = Integer.parseInt(x1);
// y = Integer.parseInt(y1);
// System.out.println("Path from " +x+" to " +y);
// System.out.println(findPath1(x,y,path));
// System.out.println(path);
// }
// }
}
There are balls in my app that just fly through display. They draws as I want. But now I want to draw the trail behind them.
All I could make is just drawing by canvas.drawPath something like following picture:
But it is not what I want. It should have pointed tail and gradient color like this:
I have no idea how to make it. Tried BitmapShader - couldn't make something right. Help, please.
Code:
First of all, there is Point class for position on display:
class Point {
float x, y;
...
}
And trail is stored as queue of Point:
private ConcurrentLinkedQueue<Point> trail;
It doesn't matter how it fills, just know it has size limit:
trail.add(position);
if(trail.size() > TRAIL_MAX_COUNT) {
trail.remove();
}
And drawing happened in DrawTrail method:
private void DrawTrail(Canvas canvas) {
trailPath.reset();
boolean isFirst = true;
for(Point p : trail) {
if(isFirst) {
trailPath.moveTo(p.x, p.y);
isFirst = false;
} else {
trailPath.lineTo(p.x, p.y);
}
}
canvas.drawPath(trailPath, trailPaint);
}
By the way, trailPaint is just really fat paint :)
trailPaint = new Paint();
trailPaint.setStyle(Paint.Style.STROKE);
trailPaint.setColor(color);
trailPaint.setStrokeWidth(radius * 2);
trailPaint.setAlpha(150);
I see you want to see a gradient on the ball path, you could use something like this
int x1 = 0, y1 = 0, x2 = 0, y2 = 40;
Shader shader = new LinearGradient(0, 0, 0, 40, Color.WHITE, Color.BLACK, TileMode.CLAMP);
trailPaint = new Paint();
trailPaint.setShader(shader);
This is what you should change your trailPaint to and see if it works.
provided from here.
I found solution. But still think it is not the best one.
First of all there are my class fields used for that task.
static final int TRAIL_MAX_COUNT = 50; //maximum trail array size
static final int TRAIL_DRAW_POINT = 30; //number of points to split the trail for draw
private ConcurrentLinkedQueue<Point> trail;
private Paint[] trailPaints;
private float[][] trailPoss, trailTans;
private Path trailPath;
Additionally to trailPath object I used PathMeasure object to split path to multiple equal parts.
After filling trail array object added call of trail calculating function.
lastTrailAdd = now;
trail.add(pos.Copy());
if (trail.size() > TRAIL_MAX_COUNT) {
trail.remove();
}
FillTrail();
Then my FillTrail function.
private void FillTrail() {
trailPath.reset();
boolean isFirst = true;
for(Point p : trail) {
if(isFirst) {
trailPath.moveTo(p.x, p.y);
trailPoss[0][0] = p.x;
trailPoss[0][1] = p.y;
isFirst = false;
} else {
trailPath.lineTo(p.x, p.y);
}
}
PathMeasure path = new PathMeasure(trailPath, false);
float step = path.getLength() / TRAIL_DRAW_POINT;
for(int i=0; i<TRAIL_DRAW_POINT; i++) {
path.getPosTan(step * i, trailPoss[i], trailTans[i]);
}
}
It separated from drawing thread. Next code is drawing function.
private void DrawTrail(Canvas canvas) {
if(trail.size() > 1) {
float prevWidthHalfX = 0f, prevWidthHalfY = 0f, prevX = 0f, prevY = 0f;
Path trailStepRect = new Path();
boolean isFirst = true;
for (int i = 0; i < TRAIL_DRAW_POINT; i++) {
float currWidthHalf = (float) (radius) * i / TRAIL_DRAW_POINT / 2f,
currWidthHalfX = currWidthHalf * trailTans[i][1],
currWidthHalfY = currWidthHalf * trailTans[i][0],
currX = trailPoss[i][0], currY = trailPoss[i][1];
if (!isFirst) {
trailStepRect.reset();
trailStepRect.moveTo(prevX - prevWidthHalfX, prevY + prevWidthHalfY);
trailStepRect.lineTo(prevX + prevWidthHalfX, prevY - prevWidthHalfY);
trailStepRect.lineTo(currX + currWidthHalfX, currY - currWidthHalfY);
trailStepRect.lineTo(currX - currWidthHalfX, currY + currWidthHalfY);
canvas.drawPath(trailStepRect, trailPaints[i]);
} else {
isFirst = false;
}
prevX = currX;
prevY = currY;
prevWidthHalfX = currWidthHalfX;
prevWidthHalfY = currWidthHalfY;
}
}
}
Main point of this is drawing trail by parts with different paints. Closer to ball - wider the trail. I think I will optimise it, but it is allready work.
If you want to watch how it looks just install my app from google play.
I'm doing a Klondike game. The logic is all working. I'm just having trouble with the UI in javafx.
I've been trying to move/drag the cards from the 'tableau pile' arround without the expected result.
My card is a ImageView with an Image inside. The cards are inside a Pane:
Pane tableau = new Pane();
for (int i = 0; i < n; i++) {
Image img = new Image("resources/images/" + (i + 1) + ".png");
ImageView imgView = new ImageView(img);
imgView.setY(i * 20);
//imgView Mouse Events here
tableau.getChildren().add(imgView);
}
I tried:
imgView.setOnMousePressed((MouseEvent mouseEvent) -> {
dragDelta.x = imgView.getLayoutX() - mouseEvent.getSceneX();
dragDelta.y = imgView.getLayoutY() - mouseEvent.getSceneY();
});
imgView.setOnMouseDragged((MouseEvent mouseEvent) -> {
imgView.setLayoutX(mouseEvent.getSceneX() + dragDelta.x);
imgView.setLayoutY(mouseEvent.getSceneY() + dragDelta.y);
});
This solution dont work because I'm setting the positions so when release the card wont return to where it was, and because the card is colliding with other UI objects.
Another attempt:
imgView.setOnDragDetected((MouseEvent event) -> {
ClipboardContent content = new ClipboardContent();
content.putImage(img);
Dragboard db = imgView.startDragAndDrop(TransferMode.ANY);
db.setDragView(img, 35, 50);
db.setContent(content);
event.consume();
});
In this solution the problems are: the card comes semitransparent, like moving a file, the cursor becames no/forbidden but other than that it works well: no collisions and the card goes to his original place if I release the mouse.
Another problem is that I dont know if I can move more than 1 card with this solution?
My final question is, How can I move a node (in this case an ImageView) or a group of nodes, from one pile to another, like in a Solitaire Card Game?
For knowing the original card position you should use the setTranslateX (and Y) instead of setLayoutX in your mouse handler. So when the user releases the card, you can simply invoke a Transition and let the card fly back to the layout position. If the user releases the card on a valid place, you set the translate coordinates to 0 and change the layout position or use relocate.
If you want to make the cards semitransparent, you could e. g. change the opacity or apply CSS.
By the way, I wouldn't use Clipboardcontent, it seems inappropriate for your needs.
You can move multiple objects with your mouse handling code. You simple have to apply the translation to multiple objects simultaneously. When you drag a pile, you determine the cards on top of the selected card and apply the transition to all of them.
Here's a quick example to show you how it could look like.
Card.java, you'll use an ImageView.
public class Card extends Rectangle {
static Random rand = new Random();
public Card() {
setWidth(100);
setHeight(200);
Color color = createRandomColor();
setStroke(color);
setFill( color.deriveColor(1, 1, 1, 0.4));
}
public static Color createRandomColor() {
int max = 200;
Color color = Color.rgb( (int) (rand.nextDouble() * max), (int) (rand.nextDouble() * max), (int) (rand.nextDouble() * max));
return color;
}
}
Game.java, the application.
public class Game extends Application {
static List<Card> cardList = new ArrayList<>();
#Override
public void start(Stage primaryStage) {
MouseGestures mg = new MouseGestures();
Group root = new Group();
for( int i=0; i < 10; i++) {
Card card = new Card();
card.relocate( i * 20, i * 10);
mg.makeDraggable(card);
cardList.add( card);
}
root.getChildren().addAll( cardList);
Scene scene = new Scene( root, 1600, 900);
primaryStage.setScene( scene);
primaryStage.show();
}
public static void main(String[] args) {
launch(args);
}
// TODO: don't use a static method, I only added for the example
public static List<Card> getSelectedCards( Card currentCard) {
List<Card> selectedCards = new ArrayList<>();
int i = cardList.indexOf(currentCard);
for( int j=i + 1; j < cardList.size(); j++) {
selectedCards.add( cardList.get( j));
}
return selectedCards;
}
}
MouseGestures.java, the mouse handling mechanism.
public class MouseGestures {
final DragContext dragContext = new DragContext();
public void makeDraggable(final Node node) {
node.setOnMousePressed(onMousePressedEventHandler);
node.setOnMouseDragged(onMouseDraggedEventHandler);
node.setOnMouseReleased(onMouseReleasedEventHandler);
}
EventHandler<MouseEvent> onMousePressedEventHandler = new EventHandler<MouseEvent>() {
#Override
public void handle(MouseEvent event) {
dragContext.x = event.getSceneX();
dragContext.y = event.getSceneY();
}
};
EventHandler<MouseEvent> onMouseDraggedEventHandler = new EventHandler<MouseEvent>() {
#Override
public void handle(MouseEvent event) {
Node node = (Node) event.getSource();
double offsetX = event.getSceneX() - dragContext.x;
double offsetY = event.getSceneY() - dragContext.y;
node.setTranslateX(offsetX);
node.setTranslateY(offsetY);
// same for the other cards
List<Card> list = Game.getSelectedCards( (Card) node);
for( Card card: list) {
card.setTranslateX(offsetX);
card.setTranslateY(offsetY);
}
}
};
EventHandler<MouseEvent> onMouseReleasedEventHandler = new EventHandler<MouseEvent>() {
#Override
public void handle(MouseEvent event) {
Node node = (Node) event.getSource();
moveToSource(node);
// same for the other cards
List<Card> list = Game.getSelectedCards( (Card) node);
for( Card card: list) {
moveToSource(card);
}
// if you find out that the cards are on a valid position, you need to fix it, ie invoke relocate and set the translation to 0
// fixPosition( node);
}
};
private void moveToSource( Node node) {
double sourceX = node.getLayoutX() + node.getTranslateX();
double sourceY = node.getLayoutY() + node.getTranslateY();
double targetX = node.getLayoutX();
double targetY = node.getLayoutY();
Path path = new Path();
path.getElements().add(new MoveToAbs( node, sourceX, sourceY));
path.getElements().add(new LineToAbs( node, targetX, targetY));
PathTransition pathTransition = new PathTransition();
pathTransition.setDuration(Duration.millis(1000));
pathTransition.setNode(node);
pathTransition.setPath(path);
pathTransition.setCycleCount(1);
pathTransition.setAutoReverse(true);
pathTransition.play();
}
/**
* Relocate card to current position and set translate to 0.
* #param node
*/
private void fixPosition( Node node) {
double x = node.getTranslateX();
double y = node.getTranslateY();
node.relocate(node.getLayoutX() + x, node.getLayoutY() + y);
node.setTranslateX(0);
node.setTranslateY(0);
}
class DragContext {
double x;
double y;
}
// pathtransition works with the center of the node => we need to consider that
public static class MoveToAbs extends MoveTo {
public MoveToAbs( Node node, double x, double y) {
super( x - node.getLayoutX() + node.getLayoutBounds().getWidth() / 2, y - node.getLayoutY() + node.getLayoutBounds().getHeight() / 2);
}
}
// pathtransition works with the center of the node => we need to consider that
public static class LineToAbs extends LineTo {
public LineToAbs( Node node, double x, double y) {
super( x - node.getLayoutX() + node.getLayoutBounds().getWidth() / 2, y - node.getLayoutY() + node.getLayoutBounds().getHeight() / 2);
}
}
}
When you pick a card or a multiple of cards, they'll transition back to their origin.
Here's a screenshot where I dragged the 3rd card from top.
When you check if a card is on a valid destination, you should invoke the fixPosition method. It simply relocates the card, i. e. calculates the position using the translation values, repositions the node and sets its translation to 0.
The tricky part was the PathTransition. It's working from the center of a node, not from the x/y coordinates. Here's a thread regarding that issue to which I replied in case you wish to know more about it.
So I'm trying to map the pixel on the rgbMap to one on the depthMap so I can get the depth from a color tracked object.
I've noticed the depth map is smaller than the rgb map in addition to the different POV from being on a different spot on the kinect itself.
Is there an efficient way to do this that I'm unaware of? Currently I'm thinking of trying to line up the example pixels and then try to figure out an equation for the offset as you get farther away.
Code below, please not that the color tracking is far from done, and that I'm using mouse pressed for testing the pixel position.
/**
* ControlP5 Controlframe
* with controlP5 2.0 all java.awt dependencies have been removed
* as a consequence the option to display controllers in a separate
* window had to be removed as well.
* this example shows you how to create a java.awt.frame and use controlP5
*
* by Andreas Schlegel, 2012
* www.sojamo.de/libraries/controlp5
*
*/
import java.awt.Frame;
import java.awt.BorderLayout;
import controlP5.*;
import SimpleOpenNI.*;
private ControlP5 cp5;
ControlFrame cf;
SimpleOpenNI context;
Ktracker p,o,b;
float rx,ry,dx,dy;
int def;
void setup() {
size((2 * 640),480);
cp5 = new ControlP5(this);
o = new Ktracker(188,57,49);
// by calling function addControlFrame() a
// new frame is created and an instance of class
// ControlFrame is instanziated.
cf = addControlFrame("Output", 640,480);
// add Controllers to the 'extra' Frame inside
// the ControlFrame class setup() method below.
context = new SimpleOpenNI(this);
context.enableRGB();
context.enableDepth();
smooth();
rx=context.rgbWidth()/2;
ry=height/2;
}
void draw() {
context.update();
background(0,150,0);
image(context.depthImage(),context.rgbWidth(),0);
image(context.rgbImage(), 0,0);
int[] dm = context.depthMap();
o.run();
rectMode(CENTER);
noStroke();
fill(255,255,0);
rect(rx,ry,5,5);
dx=rx;
dy=ry;
fill(0,255,255);
rect(dx+context.rgbWidth(),dy,5,5);
rectMode(CORNER);
if(o.wr<10){
fill(0,0,255);
noStroke();
ellipse(o.currentPoints[0]+context.rgbWidth(),o.currentPoints[1],10,10);
cf.z = dm[int(o.currentPoints[0]*o.currentPoints[1])];
} else {
cf.z=0;
}
}
void mousePressed(){
rx=mouseX;
ry=mouseY;
}
ControlFrame addControlFrame(String theName, int theWidth, int theHeight) {
Frame f = new Frame(theName);
ControlFrame p = new ControlFrame(this, theWidth, theHeight);
f.add(p);
p.init();
f.setTitle(theName);
f.setSize(p.w, p.h);
f.setLocation(100, 100);
f.setResizable(false);
f.setVisible(true);
return p;
}
// the ControlFrame class extends PApplet, so we
// are creating a new processing applet inside a
// new frame with a controlP5 object loaded
public class ControlFrame extends PApplet {
int w, h;
float z;
int abc = 100;
public void setup() {
size(w, h, P3D);
frameRate(25);
z=0;
}
public void draw() {
background(abc);
translate(width/2,height/2,z/100);
sphere(250);
}
private ControlFrame() {
}
public ControlFrame(Object theParent, int theWidth, int theHeight) {
parent = theParent;
w = theWidth;
h = theHeight;
}
public ControlP5 control() {
return cp5;
}
ControlP5 cp5;
Object parent;
}
class Ktracker{
float mx,my,wr;
// A variable for the color we are searching for.
color trackColor;
float[] currentPoints, prevPoints;
Ktracker(int r,int g, int b){
trackColor = color(r,g,b);
currentPoints = new float[2];
prevPoints = new float[2];
prevPoints[0]=0;
prevPoints[1]=0;
}
void run(){
loadPixels();
// Before we begin searching, the "world record" for closest color is set to a high number that is easy for the first pixel to beat.
float worldRecord = 500;
// XY coordinate of closest color
int closestX = 0;
int closestY = 0;
// Begin loop to walk through every pixel
for (int x = 0; x < width/2; x ++ ) {
for (int y = 0; y < height; y ++ ) {
int loc = x + y*width;
// What is current color
color currentColor = pixels[loc];
float r1 = red(currentColor);
float g1 = green(currentColor);
float b1 = blue(currentColor);
float r2 = red(trackColor);
float g2 = green(trackColor);
float b2 = blue(trackColor);
// Using euclidean distance to compare colors
float d = dist(r1,g1,b1,r2,g2,b2); // We are using the dist( ) function to compare the current color with the color we are tracking.
// If current color is more similar to tracked color than
// closest color, save current location and current difference
if (d < worldRecord) {
worldRecord = d;
closestX = x;
closestY = y;
currentPoints[0] = closestX;
currentPoints[1] = closestY;
}
}
}
wr=worldRecord;
// We only consider the color found if its color distance is less than 10.
// This threshold of 10 is arbitrary and you can adjust this number depending on how accurate you require the tracking to be.
if (worldRecord < 10) {
// Draw a circle at the tracked pixel
fill(255,0,0);
//strokeWeight(4.0);
stroke(0,0);
ellipse(currentPoints[0],currentPoints[1],16,16);
}
println("wr: "+wr);
println("worldRecord: "+worldRecord);
}
}
If you want to align the depth map with the RGB map you need to simply tell OpenNI to do so fo you in setup:
context.alternativeViewPointDepthToImage();
Have a look at the AlternativeViewpoint3d sketch in Examples > SimpleOpenNI > OpenNI
OpenNI has the registration done already so all you need to do is enable it when you need it.