I do not have much familiar with graphics in Java, sorry. However, this is what I'm trying to do. I want to be able draw a couple of points on a canvas (JPanel here), and be able to redraw the points everytime the method (drawPoints) is invoked with a new set of parameters: double[]xs, double[]ys. Any chance I could do this without 'redrawing' the canvas? I can't even get the points to plot in the current state of the code.
import java.awt.Graphics;
import java.awt.Color;
import java.awt.Graphics2D;
import javax.swing.JPanel;
import javax.swing.JFrame;
public class PlotPoints extends JPanel {
double[] x;
double[] y;
public void paintComponent (Graphics g)
{
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g;
g2d.setColor(Color.black);
for (int i=0; i<x.length; i++){
g2d.fillOval((int)this.x[i],(int)this.y[i], 10, 10);
}
}
public void drawPoints(double[]xs, double[]ys){
JFrame frame = new JFrame("Points");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.x=xs.clone();
this.y=ys.clone();
frame.add(new PlotPoints());
frame.setSize(100, 100);//laptop display size
frame.setVisible(true);
}
}
Here is the other class that invokes the 'drawPoints' method from the PlotPoints Class. I got this code snippet from some StackOverflow Q&As, and tried to improvise on it to suit my needs. If a different structure is more suited, I'd be grateful for your sharing.
import java.lang.*;
public class MainClass {
double[] xcoords;
double[] ycoords;
public static void main(String[] args){
//create instances of classes
PlotPoints myPlots=new PlotPoints();
MainClass myMain=new MainClass();
//initialize coordinates
myMain.xcoords=new double[5];
myMain.ycoords=new double[5];
//put values into coordinates
for (int i=0; i<5; i++){
myMain.xcoords[i]=Math.random()*1000; //Random number
myMain.ycoords[i]=Math.random()*1000;
}
//Create a plotter. Plot
//to draw points defined by: (xcoords[i],ycoords[i])
myPlots.drawPoints(myMain.xcoords, myMain.ycoords);
//Please do this!
}
}