package assicartesiani;
import java.awt.Dimension;
import java.awt.FontMetrics;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import javax.swing.JComponent;
public class JOxy extends JComponent {
private int scalaX, scalaY, traslX, traslY;
private String asseX, asseY;
public JOxy() {
setPreferredSize(new Dimension(400, 400));
setScalaX(50);
setScalaY(50);
setTraslX(40);
setTraslY(40);
setAsseX("X");
setAsseY("Y");
}
public int xg(double x) {
return (int) Math.round(getTraslX() + x * getScalaX());
}
public int yg(double y) {
return (int) Math.round(getHeight() - 1 - getTraslY() - y * getScalaY());
}
public double xr(int x) {
return (double) (x - getTraslX()) / getScalaX();
}
public double yr(int y) {
return (double) (getHeight() - 1 - getTraslY() - y) / getScalaY();
}
@Override
public void paintComponent(Graphics g) {
int w = getWidth() - 1;
int h = getHeight() - 1;
Graphics2D g2 = (Graphics2D) g;
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
g2.setFont(getFont());
FontMetrics fm = g2.getFontMetrics();
g2.setColor(getBackground());
g2.fillRect(0, 0, w, h);
g2.setColor(getForeground());
// asse x
g2.drawLine(0, yg(0), w, yg(0));
g2.drawLine(w - 20, yg(0) - 10, w, yg(0));
g2.drawLine(w - 20, yg(0) + 10, w, yg(0));
for (int x = -getTraslX() / getScalaX(); x < (w - getTraslX()) / getScalaX(); x++) {
g2.drawLine(xg(x), yg(0) - 5, xg(x), yg(0) + 5);
String xs = x + "";
g2.drawString(xs, xg(x) - fm.stringWidth(xs) / 2, yg(0) + 5 + fm.getHeight());
}
g2.drawString(getAsseX(), w - 5 - fm.stringWidth(getAsseX()), yg(0) - 15 - fm.getDescent());
// asse y
g2.drawLine(xg(0), h, xg(0), 0);
g2.drawLine(xg(0) - 10, 20, xg(0), 0);
g2.drawLine(xg(0) + 10, 20, xg(0), 0);
for (int y = -getTraslY() / getScalaY(); y < (h - getTraslY()) / getScalaY(); y++) { g2.drawLine(xg(0) - 5, yg(y), xg(0) + 5, yg(y)); String ys = y + ""; g2.drawString(ys, xg(0) - 10 - fm.stringWidth(ys), yg(y) + fm.getAscent() / 2); } g2.drawString(getAsseY(), xg(0) + 15, fm.getHeight()); } public int getScalaX() { return scalaX; } public final void setScalaX(int scalaX) { if (scalaX >= 20) {
this.scalaX = scalaX;
repaint();
}
}
public int getScalaY() {
return scalaY;
}
public final void setScalaY(int scalaY) {
if (scalaY >= 20) {
this.scalaY = scalaY;
repaint();
}
}
public int getTraslX() {
return traslX;
}
public final void setTraslX(int traslX) {
if (traslX >= 0) {
this.traslX = traslX;
repaint();
}
}
public int getTraslY() {
return traslY;
}
public final void setTraslY(int traslY) {
if (traslY >= 0) {
this.traslY = traslY;
repaint();
}
}
public String getAsseX() {
return asseX;
}
public final void setAsseX(String asseX) {
if (asseX != null) {
this.asseX = asseX;
} else {
this.asseX = "";
}
}
public String getAsseY() {
return asseY;
}
public final void setAsseY(String asseY) {
if (asseY != null) {
this.asseY = asseY;
} else {
this.asseY = "";
}
}
}