// GridPanel.java
import java.awt.*;
import java.awt.geom.*;
import javax.swing.JPanel;
import javax.swing.JFrame;
public class GridPanel extends JPanel
{
final static int resolution = 96;
AffineTransform tf = new AffineTransform();
protected void show_size(Graphics g)
{
int width = getWidth();
int height = getHeight();
String str = String.format("width %d height %d",width,height);
FontMetrics fm = g.getFontMetrics();
Rectangle2D rect = fm.getStringBounds(str,g);
width -= rect.getWidth();
height -= rect.getHeight();
g.drawString(str,width/2,height/2);
}
protected void draw_grid(Graphics g)
{
Graphics2D g2 = (Graphics2D) g;
Paint savePaint = g2.getPaint();
g2.setPaint(new Color(220,220,255));
Stroke saveStroke = g2.getStroke();
g2.setStroke(new BasicStroke(1.0f/resolution));
double u = 4.0;
for (int i=-4; i<=4; i++) {
double v = i;
g2.draw(new Line2D.Double(-u,v,4,v));
g2.draw(new Line2D.Double(v,-u,v,u));
}
// locate origin
boolean show_origin = false;
if (show_origin) {
g2.setPaint(Color.BLACK);
u = 0.05;
g2.draw(new Line2D.Double(-u,u,u,-u));
g2.draw(new Line2D.Double(-u,-u,u,u));
}
g2.setStroke(saveStroke);
g2.setPaint(savePaint);
}
// override to draw content on the grid pattern
public void drawContent(Graphics g)
{
Graphics2D g2 = (Graphics2D) g;
Paint savePaint = g2.getPaint();
g2.setPaint(Color.BLACK);
double u = 0.1;
g2.draw(new Line2D.Double(-u,u,u,-u));
g2.draw(new Line2D.Double(-u,-u,u,u));
g2.setPaint(savePaint);
}
public void paintComponent(Graphics g)
{
super.paintComponent( g );
Graphics2D g2 = (Graphics2D) g;
AffineTransform saveXform = g2.getTransform();
Paint savePaint = g2.getPaint();
int width = getWidth();
int height = getHeight();
g2.translate(width/2,height/2);
g2.scale(resolution,resolution);
try {
tf .setToTranslation(width/2,height/2);
tf.scale(resolution,resolution);
tf.invert();
}
catch(Exception e) {
System.err.println( e);
}
draw_grid(g);
Stroke saveStroke = g2.getStroke();
g2.setStroke(new BasicStroke(2.0f/resolution,BasicStroke.CAP_ROUND,BasicStroke.JOIN_ROUND));
drawContent(g);
g2.setTransform(saveXform);
g2.setPaint(savePaint);
g2.setStroke(saveStroke);
//show_size(g);
}
public void showTransform() {
double[] mtx = new double[6];
tf.getMatrix(mtx);
System.out.println("Transform:");
System.out.format(" %g %g %g\n",mtx[0],mtx[2],mtx[4]);
System.out.format(" %g %g %g\n",mtx[1],mtx[3],mtx[5]);
}
public static void main(String[] args)
{
EventQueue.invokeLater(() -> {
GridPanel panel = new GridPanel();
JFrame app = new JFrame("GridPanel");
app.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
app.add(panel);
app.setSize(496,358);
app.setVisible(true);
});
}
}
Maintained by John Loomis, updated Sun Mar 08 11:55:19 2020