-
Functions Graph
Hi there, I would like to design a plotter, where the user enters min x / max x and min y and max y accordingly, and then presses plot button to see the points on the graph. I have managed setting the labels, buttons, combobox; all these entries are settled using the gridbay layout on the left.
Now on the right I have implemented the x and y coordinates which resizes accordingly in any size of the main frame window. How do I rescale the coordinates as well along the x and y coordinates when the main frame window is resized?
Thanks
-
There are 2 possible options. First you can calculate all painting coordinates with a factor for and factor for y. Alternate you calculated only the factors and set a transformation on the Graphics.
-
Can you please provide me a sample code, cause I tried many times and still cannot do it... thanks
-
I does not know what you expected. It is like how I have described in text.
Dimension realSize = size();
float factorX = realSite.width/virtualWidth;
float factorY = realSite.heigth/virtualHeight;
Graphics gr = g.createGraphics();
gr.setScale( factorX, factorY );
...
-
The following code is what I have done so far,
Code:
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.geom.AffineTransform;
import javax.swing.JPanel;
public class GraphPanel extends JPanel {
private double minX;
@Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2D = (Graphics2D) g;
this.setBackground(Color.lightGray); // sets GraphPanel background
// color;
// Set graph panel width and height to resize accordingly;
int graphWidth = getWidth();
int graphHeight = getHeight();
// Drawed the x and y coordinates;
g.drawLine(0, getHeight() / 2, getWidth(), getHeight() / 2); // x
g.drawLine(getWidth() / 2, 0, getWidth() / 2, getHeight()); // y
AffineTransform oldtransform = g2D.getTransform();
g2D.scale(1.0, -1.0);
g.translate(graphWidth / 2, graphHeight / 2); // shift to cartesian
int noOfPoints= 10000;
int maxX = 0;
int xRange= (int) (minX + maxX);
double x = this.minX;
double increment = xRange/(1.0*noOfPoints);
// calculate all the points.
for (int i=0; i < noOfPoints; i++){
int xPoint = x;
Object xPoints = null;
Object yPoint = calculateY(xPoints);
x += increment;
// draw xPoint, yPoint here
g.fillRect(x,x,1,1);
}
// restore old coordinate system.
g2D.setTransform(oldtransform);
}
private Object calculateY(Object xPoints) {
// TODO Auto-generated method stub
return null;
}
}
Moderator Edit: Code tags added
-
Seems ok. For calculateY you need to know the range of your points, the virtual size. Currently xPoint and yPoint are ever null.
-
after // calculate all the points you should define the xPoint as double and when you call fillRect cast the x as int.