1

I want to create a small grid (let's say 2 x 2) where each individual point in the grid (4 points total) will have its own value of integer. I will also want to be able to call on the values of each point by its location. This is because I want each point's integer to be affected by its neighboring points. What is the best way that I can get each point to have its own values and then be able to call upon those values?

I have this so far, which only makes the grid and displays its values. In the end, I will also want to display its neighbors' values in its location. Thanks!

edit: just looking for best approach to solving this problem to guide me in right direction to go about this.

import javax.swing.JFrame;
import javax.swing.JButton;
import java.awt.GridLayout;

public class Grid {
JFrame frame = new JFrame(); // create frame
JButton[][] grid; // name grid
// constructor
public Grid (int width, int length) {
    frame.setLayout(new GridLayout(width, length));
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.pack();
    frame.setVisible(true);
    // create grid
    grid = new JButton[width][length]; // allocate size
    for (int y = 0; y < length; y++) {
        for (int x = 0; x < width; x++) {
            grid[x][y] = new JButton("value");
            frame.add(grid[x][y]);
        }
    }
}
public static void main (String[] args) {
    // DIMENSION
    int d = 2; 
    // LENGTH
    int l = 2;
    // WIDTH
    int w = 2;
    new Grid(l,w); // create new Grid with parameters
}
}
OTPYG
  • 45
  • 1
  • 7

1 Answers1

1

Use a nested int array to make a grid.

int[][]grid = new int[2][2];
for(int x=0; x<2;x++){
    for(int y=0; y<2; y++){
        grid[x][y] = value;
    }
}

This will return a grid you can address (call the value of) by calling int val = grid[x][y]

Adam Yost
  • 3,616
  • 23
  • 36