Hi, I am trying to write some code to insert coordinates which are taken from the mouseClick position and then added to a 2D array. The user should click 6 positions on a panel and these positions should be stored in a 2D array.

I hope you can help. Thank you!

public void mouseClicked(MouseEvent e) {
        alignCoord = new int[10][10];
        for (int i = 0; i < alignCoord.length; i++) {
            for (int j = 0; j < alignCoord.length; j++) {
                x = e.getX();
                y = e.getY();
            alignCoord[i][j]; <--- I know this is wrong but I'm not sure how to add the elements to the array
            }
        }

Without a structure...


It is unclear what you want! You have a 10x10 array and you want to count everytime that area of the screen is clicked in the cell corresponding to that area, or merely store the X,Y in all the positions?

based upon your description....

int alignCoord[6][2];
int index = 0;


    public void mouseClicked(MouseEvent e) 
   {
             if (index < 6)
              {
               alignCoord[ index ][0] = e.getX();
               alignCoord[ index ][1] = e.getY();
               index++;
             }
        }

How would I print the contents of the array to make sure that the correct values are passed? Thank you for your help!

for (int j = 0; j < 6; j++) 
            {
               x = alignCoord[ j ][0];
               y = alignCoord[ j ][1];

             print x,y coordinates
}

I don't know if there is a special reason to use a 2d array here, but, if not, you would probably be a lot better off with a simpler approach.
For example - create a simple ArrayList of Points - you can add to it, retrieve from it, loop thru it etc very easily and with less housekeeping than an array. Some examples:

ArrayList<Point> points = new ArrayList<Point>();

public void mouseClicked(MouseEvent e) {
    points.add(e.getPoint());
}

for (Point p : points) {
  System.out.println(p);
}

Thank you very much. That was so much easier than using a 2d array.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.