Check the calculation for the size of the grid:
int calculatedSize = 100*gridSquares + 2*PAD;
int calculatedWidth = ( 100 + 2*(PAD) )*gridSquares;
System.out.printf("calculatedSize = %d calculatedWidth = %d%n",
calculatedSize, calculatedWidth);
test.setPreferredSize(new Dimension(calculatedSize, calculatedSize));
A more elegant way to size the grid/graphic component is to let the graphic class establish its own preferred size. You can compute the size in the class constructor and call
setPreferredSize with it or you can override the
getPreferredSize method in the class to return the desired size. Here's one way you could do the second option.
import java.awt.*;
import javax.swing.*;
public class CreateGrid {
public static void main(String[] args) {
// Prompts user for size of grid. For example if user inputs a 4 a 4x4
// grid of squares is created.
String input = JOptionPane.showInputDialog(
"Enter number of rows and columns you want grid to contain\n" +
"(For example entering 2 will create a 2x2 grid)\n");
// Takes input and parses it from a string type to an integer type that
// can be used to generate the grid squares
int gridSquares = Integer.parseInt( input );
// Creates frame that holds the grid which is prouced by the CreateGridRx
// class
CreateGridRx2 test = new CreateGridRx2(gridSquares);
JFrame f = new JFrame(); // creates new JFrame object
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.getContentPane().add(test);
f.pack(); // sets size of frame
f.setLocation(200,200); // sets location of frame
f.setVisible(true);
}
}
class CreateGridRx2 extends JPanel {
int gridSize;
final int cellSize = 100;
final int PAD = 10;
public CreateGridRx2(int size) {
this.gridSize = size;
}
public Dimension getPreferredSize() {
int n = gridSize*cellSize + 2*PAD;
return new Dimension(n, n);
}
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2 = (Graphics2D)g;
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
int w = getWidth();
int h = getHeight();
for(int j = 0; j <= gridSize; j++) {
int x = PAD + j*cellSize;
g2.drawLine(x, PAD, x, h-PAD);
}
for(int j = 0; j <= gridSize; j++) {
int y = PAD + j*cellSize;
g2.drawLine(PAD, y, w-PAD, y);
}
}
}