GUI edge to node recursive path not finding first index of path - java

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);
// }
// }
}

Related

How to fix Java listening to more than 1 key at a time?

Me and my partner are attempting to create the game Pong for our computer science final project. We created a reference code where 2 cubes can be controlled upwards and downwards and it works fine. The problem occurs when attempting to control both cubes at the same time (only 1 cube will move at a time). We want to make both cubes move at the same time.
WE want to say that:
yPos - is the y position of the black cube
xPos - is the x position of the black cube
xPos2 - is the x position of the blue cube
YPos2 - is the y position of the blue cube
Keys:
A - Go up for black cube
Z - Go down for black cube
K - Go up for blue cube
M - go down for blue cube
We have tried using a more complicated version which used j-label animation. How ever we want to make our pong game through the graphics function. But we do not understand:
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
public class PongHelpNeed extends JFrame implements KeyListener
{
// booleans to tell which key is pressed
boolean upKey;
boolean downKey;
boolean upKey2;
boolean downKey2;
// the position variables
int yPos;
int xPos;
int xPos2;
int yPos2;
public PongHelpNeed ()
{
//create window
super ("Controller");
setSize (660, 700);
// set keys to false and original positions
upKey = false;
downKey = false;
upKey2 = false;
downKey2 = false;
xPos = 100;
yPos = 350;
xPos2 = 500;
yPos2 = 350;
// add the frame as a listener to your keys
addKeyListener (this);
// Show the frame
setVisible(true);
}
//needs to be here because the class implements KeyListener
public void keyTyped (KeyEvent e)
{
System.out.println (e.getKeyCode () + " Typed");
}
//needs to be here because the class implements KeyListener
public void keyPressed (KeyEvent e) {
//check if keys a,z or k,m are pressed
if (e.getKeyCode () == KeyEvent.VK_A)
{
upKey = true;
}
else if (e.getKeyCode () == KeyEvent.VK_Z)
{
downKey = true;
}
else if (e.getKeyCode () == KeyEvent.VK_K)
{
upKey2 = true;
}
else if (e.getKeyCode () == KeyEvent.VK_M)
{
downKey2 = true;
}
//repaint the window everytime you press a key
repaint ();
}
//needs to be here because the class implements KeyListener
public void keyReleased (KeyEvent e)
{
System.out.println (e.getKeyCode () + " Released");
}
//paints the pictures
public void paint (Graphics g)
{
//set background
g.setColor(Color.WHITE);
g.fillRect(0, 0, 660, 700);
//cube 1
g.setColor(Color.BLACK);
g.fillRect(xPos,yPos,50, 50);
//draw cube 2
g.setColor(Color.BLUE);
g.fillRect(xPos2,yPos2, 50, 50);
//if keys are pressed move the cubes accordingly up or down
if (upKey == true)
{
yPos = yPos - 15;
upKey = false;
}
else if (downKey == true)
{
yPos = yPos + 15;
downKey = false;
}
else if (downKey2 == true){
yPos2 = yPos2 + 15;
downKey2 = false;
}
else if (upKey2 == true) {
yPos2 = yPos2 - 15;
upKey2 = false;
}
}
public static void main (String[] args)
{
new PongHelpNeed ();
}
}
Our expected results are we are trying to move both cube at the same time. So when we press the A key and the K key the black square should move and the blue cube should move.
Calling repaint() does not trigger a call to the paint immediately, so it's possible that the keyPressed is triggered twice (or more) before paint.
In your paint method you are checking the keys in if-else, which means that if one of the flags is true, the rest are not checked. You also have a race condition where the keyPressed is fighting with paint over the flags. Also, if you press a key quickly multiple times, you'll lose all the extra key presses between the first handled event and the next repaint.
Instead of doing the move within paint, you should do it within the keyPressed handler. Don't set a flag to e.g. upKey = true;, but instead do the action directly: yPos = yPos - 15;. The paint method will then just refresh the view to reflect the current (updated) state.

Add a node in a gridpane using mouse

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!

How To Visualize A Matrix on Java FX

I have a matrix which consists of 0s and 1s. I want to visualize this matrix like a grid and put a mark to the cells which has 1 in it. I made my research in order to find a way of doing this in Java FX but I could not find something similar to what I said. Is there any way to do that in Java FX? Best Regards,
I visualized the matrix with using GridPane and Timeline in Java FX. I found this method thanks to c0der's comment above. In my case I needed to draw a path on the matrix, it is like finding a minimum path problem. Here is my source code:
public class VisualizationThread implements EventHandler<ActionEvent> {
private ArrayList<ArrayList<Integer>> matrix; // Matrix
private ArrayList<Integer> solution; // One individual
private ArrayList<ArrayList<Integer>> visited; // Visited coordinate list
private int currentX; // Current x coordinate
private int currentY; // Current y coordinate
private int index; // Current movement index
private int attempt; // unsuccessful attempt count (used while visualizing all generations)
private boolean closeAtTheAnd; // Close all stages except the last one which shows final situation, the correct path
private boolean isSuccessful; // Currently visualizing an unsuccessful attempt or correct path?
private Stage primaryStage; // primary stage (gui component)
public VisualizationThread(ArrayList<ArrayList<Integer>> matrix, ArrayList<Integer> solution, int currentX, int currentY,
boolean isSuccessful, int attempt, boolean closeAtTheAnd){
this.matrix = matrix;
this.solution = solution;
this.currentY = currentY;
this.currentX = currentX;
this.isSuccessful = isSuccessful;
this.attempt = attempt;
this.primaryStage = new Stage();
this.index = 0;
this.closeAtTheAnd = closeAtTheAnd;
this.visited = new ArrayList<ArrayList<Integer>>();
}
// Visualize a single individual
public void run() {
// GUI processes
BorderPane root = new BorderPane();
GridPane grid = new GridPane();
grid.setPadding(new Insets(10));
grid.setHgap(10);
grid.setVgap(10);
StackPane[][] screen_buttons = new StackPane[matrix.size()][matrix.size()];
visited.add(new ArrayList<Integer>(){{add(currentX); add(currentY);}});
for (int y=0;y<matrix.size();y++) {
for (int x=0;x<matrix.get(y).size();x++) {
screen_buttons[y][x] = new StackPane();
Rectangle rec = new Rectangle(60,60);
// Visualize visited points as green and others yellow and foods red
if(!(currentX>=matrix.size() || currentY>=matrix.size())){
if(isVisited(visited, x, y)){
rec.setFill(Color.GREEN);
}else {
rec.setFill(matrix.get(y).get(x) == 0 ? Color.YELLOW : Color.RED);
}
}else {
rec.setFill(matrix.get(y).get(x) == 0 ? Color.YELLOW : Color.RED);
}
rec.setStyle("-fx-arc-height: 20; -fx-arc-width: 20;");
screen_buttons[y][x].getChildren().addAll(rec);
grid.add(screen_buttons[y][x], x, y);
}
}
//container for controls
GridPane controls = new GridPane();
root.setCenter(grid);
root.setBottom(controls);
Scene scene = new Scene(root);
primaryStage.setScene(scene);
primaryStage.setTitle(isSuccessful ? "Correct Path" : "Unsuccessful Attempt: " + attempt);
primaryStage.show();
if(!(index >= solution.size())){
switch (solution.get(index)){
case 1:
setCurrentY(getCurrentY()-1);
break;
case 2:
setCurrentX(getCurrentX()-1);
break;
case 3:
setCurrentY(getCurrentY()+1);
break;
case 4:
setCurrentX(getCurrentX()+1);
break;
}
index++;
}
if(closeAtTheAnd && index == solution.size()){
primaryStage.close();
}
}
// This method finds if current coordinate is visited before or not
// #param visitedList: List of visited points
// #param x: x coordinate
// #param y: y coordinate
public boolean isVisited(ArrayList<ArrayList<Integer>> visitedList, int x, int y){
boolean result = false;
// Check if x and y coordinates are visited before
for (ArrayList<Integer> temp : visitedList){
if(temp.get(0) == x && temp.get(1) == y){
result = true;
break;
}
}
return result;
}
public int getCurrentX() {
return currentX;
}
public void setCurrentX(int currentX) {
this.currentX = currentX;
}
public int getCurrentY() {
return currentY;
}
public void setCurrentY(int currentY) {
this.currentY = currentY;
}
public void handle(ActionEvent event) {
run();
}
}
// In another part of the code which I need to trigger the event above.
ArrayList<Integer> bestOfLastPopulation = geneticAlgorithm.findMostAte(finalPopulation, matrix, centerX, centerY);
VisualizationThread visualizationThread = new VisualizationThread(matrix, bestOfLastPopulation, centerX, centerY, true, 0, false);
Timeline fiveSecondsWonder = new Timeline(new KeyFrame(Duration.millis(150), visualizationThread));
fiveSecondsWonder.setCycleCount(bestOfLastPopulation.size() + 1);
fiveSecondsWonder.play();
For someone who is trying to find the same thing, should look at the part which begins with a nested for loop and ends with primaryStage.show(). At this part of code, it is visualizing the matrix in different colors. For example, if a cell contains 1 then red, if it contains a 0 then yellow and if it is visited before then it will painted to green color. Hope that helps to someone else. Best Regards,

Counter loop in Java

I have created a game where the player collects pods on the game board. I need to make an evasive maneuver so that after five turns when the player is one space away from the pod, the pod will transport 10 spaces away from the player. I believe my counter is not working and that is why the evasive maneuver is not working.
public class Pod {
int podPositionX;
int podPositionY;
String podDirection;
int layoutWidth;
int layoutHeight;
boolean podVisable = true;
int playerX;
int playerY;
int count = 0;
public Pod(int x, int y, String direction, int width, int height){
podPositionX = x;
podPositionY = y;
podDirection = direction;
layoutWidth = width;
layoutHeight = height;
count=count+1;
}
//Inspector Methods?
// Will get the the pods positon and will return it
public int getX()
{
return podPositionX;
}
//This method returns the current Y coordinate of the pod.
public int getY()
{
return podPositionY;
}
//This method returns true if the pod is visible, false otherwise. Once the
//pod has been caught, it should always return false.
public boolean isVisible(){
if (playerX == podPositionX && playerY == podPositionY && podVisable == true){
podVisable = false;}
return podVisable;
}
// to move pod diagonally across screen//
public void move(){
//Calling invasive methods!!
while (count>5 && count < 100){
podPositionX=transportX();
podPositionY=transportY();
}
/****************** To make pod move **************/
if (podDirection.equals("NW")|| podDirection.equals("NE")){
podPositionY = podPositionY + 1;}
if (podDirection.equals("SW")|| podDirection.equals("SE")){
podPositionY = podPositionY-1;}
if (podDirection.equals("NE")|| podDirection.equals("SE")){
podPositionX = podPositionX+1;}
if(podDirection.equals("NW")|| podDirection.equals("SW")){
podPositionX = podPositionX-1;}
/****************To make Pod bounce off wall******************/
//make pod bounce off left wall
if (podPositionX <= 1){
if (podDirection.equals("SW")){
podDirection = "SE";}
if (podDirection.equals("NW")){
podDirection = "NE";}
}
//make pod bounce off top
if (podPositionY >= layoutHeight-1){
if (podDirection.equals("NW")){
podDirection = "SW";}
if (podDirection.equals("NE")){
podDirection = "SE";}
}
//make pod bounce off right wall
if (podPositionX >= layoutWidth-1){
if (podDirection.equals("NE")){
podDirection = "NW";}
if (podDirection.equals("SE" )){
podDirection = "SW";}
}
//make pod bounce off bottom wall
if (podPositionY <= 1){
if (podDirection.equals("SW")){
podDirection = "NW";}
if (podDirection.equals("SE")){
podDirection = "NE";}
}
}
// to get player x and y positions
public void playerAt(int x, int y){
playerX = x;
playerY = y;
}
//envasive maneuver so that after 5 turns the pod can be transported away from the player if it is 1 spot away from the player.
//then the count is set to 100 so it will exit the loop and not be able to transport the pod again.
public int transportX(){
if (podPositionX == playerX -1 || podPositionX == playerX +1){
podPositionX= playerX +10;
count = 100;}
return podPositionX;
}
public int transportY(){
if (podPositionY == playerY -1 || podPositionY == playerY +1){
podPositionY= playerY +10;
count=100;}
return podPositionY;
}
}
the code my teacher provided us. Can no be touched so i can not put a counter in this file.
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class Project1 extends JFrame implements ActionListener {
// Member variables for visual objects.
private JLabel[][] board; // 2D array of labels. Displays either # for player,
// * for pod, or empty space
private JButton northButton, // player presses to move up
southButton, // player presses to move down
eastButton, // player presses to move right
westButton; // player presses to move left
// Current width and height of board (will make static later).
private int width = 15;
private int height = 9;
// Current location of player
private int playerX = 7;
private int playerY = 4;
// Pod object stored in array for efficiency
private Pod[] pods;
int podCount = 4;
public Project1() {
// Construct a panel to put the board on and another for the buttons
JPanel boardPanel = new JPanel(new GridLayout(height, width));
JPanel buttonPanel = new JPanel(new GridLayout(1, 4));
// Use a loop to construct the array of labels, adding each to the
// board panel as it is constructed. Note that we create this in
// "row major" fashion by making the y-coordinate the major
// coordinate. We also make sure that increasing y means going "up"
// by building the rows in revers order.
board = new JLabel[height][width];
for (int y = height-1; y >= 0; y--) {
for (int x = 0; x < width; x++) {
// Construct a label to represent the tile at (x, y)
board[y][x] = new JLabel(" ", JLabel.CENTER);
// Add it to the 2D array of labels representing the visible board
boardPanel.add(board[y][x]);
}
}
// Construct the buttons, register to listen for their events,
// and add them to the button panel
northButton = new JButton("N");
southButton = new JButton("S");
eastButton = new JButton("E");
westButton = new JButton("W");
// Listen for events on each button
northButton.addActionListener(this);
southButton.addActionListener(this);
eastButton.addActionListener(this);
westButton.addActionListener(this);
// Add each to the panel of buttons
buttonPanel.add(northButton);
buttonPanel.add(southButton);
buttonPanel.add(eastButton);
buttonPanel.add(westButton);
// Add everything to a main panel attached to the content pane
JPanel mainPanel = new JPanel(new BorderLayout());
getContentPane().add(mainPanel);
mainPanel.add(boardPanel, BorderLayout.CENTER);
mainPanel.add(buttonPanel, BorderLayout.SOUTH);
// Size the app and make it visible
setSize(300, 200);
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// Auxiliary method to create game setup
createGame();
}
// Auxiliary method used to create board. Sets player, treasure, and walls.
public void createGame() {
// Construct array of Pod objects
pods = new Pod[podCount];
// Construct each Pod in the array, passing it its initial location,
// direction of movement, and the width and heigh of board. This will
// later be modified to be done at random.
pods[0] = new Pod(1, 5, "NE", width, height);
pods[1] = new Pod(2, 1, "SW", width, height);
pods[2] = new Pod(12, 2, "NW", width, height);
pods[3] = new Pod(13, 6, "SE", width, height);
// Call method to draw board
drawBoard();
}
// Auxiliary method to display player and pods in labels.
public void drawBoard() {
// "Erase" previous board by writing " " in each label
for (int y = 0; y < height; y++) {
for (int x = 0; x < width; x++) {
board[y][x].setText(" ");
}
}
// Get location of each pod and write * into that label. We only
// do this for pods not yet caught.
for (int p = 0; p < podCount; p++) {
if (pods[p].isVisible()) {
board[pods[p].getY()][pods[p].getX()].setText("*");
}
}
// Write the player onto the board.
board[playerY][playerX].setText("#");
}
public void actionPerformed(ActionEvent e) {
// Determine which button was pressed, and move player in that
// direction (making sure they don't leave the board).
if (e.getSource() == southButton && playerY > 0) {
playerY--;
}
if (e.getSource() == northButton && playerY < height-1) {
playerY++;
}
if (e.getSource() == eastButton && playerX < width-1) {
playerX++;
}
if (e.getSource() == westButton && playerX > 0) {
playerX--;
}
// Move the pods and notify the pods about player location.
for (int p = 0; p < podCount; p++) {
pods[p].move();
pods[p].playerAt(playerX, playerY);
}
// Redraw the board
drawBoard();
}
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
Project1 a = new Project1();
}
}
I am looking at this quickly now. You said the problem is with the count variable. I see that you are incrementing it in the constructor i.e
public Pod(int, int, String, int, int){
count = count + 1;
}
why not put it in the move method. That way every time the move method is used the count variable will be incremented by one.
public void move(){
this.count++;
}
Also it is very hard to see exactly what you think your code is doing. I tried to run it and nothing happens. Sometimes it is good to print something to the console.

Having trouble with methods in an array

I am trying to add and remove balls into an array, I'm only allowed to use an array (not an arraylist).
I'm having trouble with the add and remove ball methods and keep getting an " insert "AssignmentOperator Expression" " error on length for add and remove ball methods. Not sure how to fix the problem.
Help appreciated.
private final int DIAMETER = 60;
private java.awt.Color _currentColor;
//private SmartEllipse _ball;
SmartEllipse [] myBalls = new SmartEllipse [25];
public BallPanel () {
super();
this.setBackground(java.awt.Color.white);
myBalls = new SmartEllipse[0];
_currentColor = java.awt.Color.red;
this.addMouseListener(new MyMouseListener());
}
//translate the click coordinates to a grid coordinate
public java.awt.Point translatePoint(java.awt.Point aPoint)
{
int x = aPoint.x;
int y = aPoint.y;
aPoint.x = x / 20;
aPoint.y = y / 20;
return aPoint;
}
//find a ball in the array
public int findBall(java.awt.Point p)
{
for (SmartEllipse se : myBalls )
{
java.awt.Point translatedPoint = translatePoint(se.getLocation());
if (translatedPoint.x == p.x && translatedPoint.y == p.y)
return myBalls.length;
}
return -1;
}
// remove a ball from the array
public void removeBall(SmartEllipse p)
{
myBalls.length-1;
this.repaint();
this.revalidate();
}
//add a peg to the array
public void addBall(SmartEllipse p)
{
myBalls.length;
this.repaint();
this.revalidate();
}
public void paintComponent(java.awt.Graphics aBrush)
{
super.paintComponent(aBrush);
java.awt.Graphics2D betterBrush = (java.awt.Graphics2D) aBrush;
for (SmartEllipse se : myBalls )
{
se.draw(betterBrush);
se.fill(betterBrush);
}
}
private class MyMouseListener extends javax.swing.event.MouseInputAdapter
{
public void mouseClicked(MouseEvent e)
{
// get X and Y of click
// translate X and Y to grid
// check peg array for duplicate
// if duplicate, remove ball
// else add ball to ball array
java.awt.Point p = translatePoint(e.getPoint());
// Adjust the coordinates
int index = findBall(p);
for (int i = 0; i< myBalls.length; i++)
{
myBalls[i] = null;
if ( index != -1)
remove(myBalls.length);
else
addBall(new SmartEllipse(_currentColor, p.x, p.y));
}
}
}
}
I'm not sure I understand your question since you don't specify very well where you're getting the error, but it looks as if you are declaring myBalls as an array of 25 elements, but then in the constructor your are assigning it a new array of zero elements. You can't add anything to an array of zero elements.

Categories