Hardwired sorry to bother you but I was able to get the JFrame to size itself based on the number of grid squares. I also have each square as being 100x100. However at the bottom and right side of the grid I get lines that just keep going. I get the correct number of squares in each direction but than the extra lines appear. Below is the code I have but I cannot seem to pinpoint where the issue lies.
import java.awt.*;
import java.awt.geom.Line2D;
import javax.swing.*;
public class CreateGridRx extends JPanel {
int gridSize;
final int PAD = 10;
public CreateGridRx(int size) {
this.gridSize = size;
}
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();
//double xInc = (double)(w - 2*PAD)/gridSize;
//double yInc = (double)(h - 2*PAD)/gridSize;
double xInc = 100;
double yInc = 100;
for(int j = 0; j <= gridSize; j++) {
double x = PAD + j*xInc;
g2.draw(new Line2D.Double(x, PAD, x, h-PAD));
}
for(int j = 0; j <= gridSize; j++) {
double y = PAD + j*yInc;
g2.draw(new Line2D.Double(PAD, y, w-PAD, y));
}
}
}
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JTable;
import java.awt.*;
public class CreateGrid {
/**
* @param args the command line arguments
*/
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
CreateGridRx test = new CreateGridRx(gridSquares);
int PAD = 10;
int calculatedWidth = ( 100 + 2*(PAD) )*gridSquares;
int calculatedHeight = ( 100 + 2*(PAD) )*gridSquares;
test.setPreferredSize(new Dimension(calculatedWidth, calculatedHeight));
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); //
}
}