我对Java中的图形并不熟悉,抱歉。但是,这正是我想要做的。我希望能够在画布上绘制几个点(这里是JPanel),并且每次使用一组新参数调用方法(drawPoints)时都能够重绘点:double [] xs,double [] ys。没有'重绘'画布我有可能做到这一点吗?我甚至无法在代码的当前状态下绘制点。
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);
}
}
这是从PlotPoints类调用'drawPoints'方法的另一个类。我从一些StackOverflow Q&amp; As获得了这段代码片段,并试图根据我的需要进行即兴创作。如果不同的结构更合适,我将非常感谢您的分享。
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!
}
}
答案 0 :(得分:3)
如果没有'重绘'画布,我有可能做到这一点吗?
不确定。将它们绘制到BufferedImage
,JLabel
本身显示在paint()
中。例如。如this answer中所示。
但是不要太快走这条路。 Java-2D可以用{{1}}方法为数千个图形元素制作动画。