Ah... bhè, qualcosa del genere ad esempio:
codice:
import javax.swing.*;
import java.awt.*;
public class TestGraficoFunzione extends JFrame {
private class MyDrawingPanel extends JPanel {
private double[] x;
private double[] y;
private int scale ;
public MyDrawingPanel(int scale) {
this.scale = scale;
}
private void populateX() {
double minValue = -0.5*(this.getWidth()-10)/scale;
double maxValue = -minValue;
double step = maxValue*2/(this.getWidth()-10);
//populate x array
x = new double[2*(this.getWidth()-10)];
for (int i = 0; i < x.length; i++) {
x[i] = minValue + i*step;
}
}
private double evaluateFunction(double x) {
// Qui metto la funzione nel nostro caso
// f(x) = x^2+ 2x +1;
return x*x+ 2*x + 1;
}
private void populateY() {
y = new double[x.length];
for (int i = 0; i < y.length; i++) {
y[i] = evaluateFunction(x[i]);
}
}
private void plot(Graphics g, double x1, double y1, double x2, double y2) {
x1 += this.getWidth()/2;
x2 += this.getWidth()/2;
y1 = this.getHeight()/2-y1;
y2 = this.getHeight()/2-y2;
g.drawLine((int)x1, (int)y1, (int)x2, (int)y2);
}
private void paintAxis(Graphics g) {
g.drawLine(5, this.getHeight()/2, this.getWidth()-5, this.getHeight()/2);
int counter = 0;
while (counter < this.getWidth()/2 - (scale+5)) {
g.drawLine(this.getWidth()/2 + counter + scale, this.getHeight()/2 -2, this.getWidth()/2+counter + scale, this.getHeight()/2+2);
g.drawLine(this.getWidth()/2 - (counter+ scale), this.getHeight()/2 -2, this.getWidth()/2 - (counter + scale), this.getHeight()/2+2);
counter += scale;
}
g.drawLine(this.getWidth()/2, 5, this.getWidth()/2, this.getHeight()-5);
counter = 0;
while (counter < this.getHeight()/2 - (scale+5)) {
g.drawLine(this.getWidth()/2 - 2, this.getHeight()/2 + (counter + scale), this.getWidth()/2 + 2, this.getHeight()/2 + (counter + scale));
g.drawLine(this.getWidth()/2 - 2, this.getHeight()/2 - (counter + scale), this.getWidth()/2 + 2, this.getHeight()/2 - (counter + scale));
counter += scale;
}
}
public void paintComponent(Graphics g) {
paintAxis(g);
populateX();
populateY();
for (int i = 0; i < x.length-1; i++) {
plot(g, x[i]*scale, y[i]*scale, x[i+1]*scale, y[i+1]*scale);
}
}
}
public TestGraficoFunzione(int scala) {
super("Test");
this.setSize(600,400);
this.getContentPane().add(new MyDrawingPanel(scala));
this.setVisible(true);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public static void main(String[] args) {
new TestGraficoFunzione(20);
}
}