【问题标题】:produce a plot with multiple points in a JPanel在 JPanel 中生成具有多个点的图
【发布时间】:2013-11-16 22:13:30
【问题描述】:

抱歉,我对 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 问答中得到了这个代码 sn-p,并试图即兴发挥它以满足我的需要。如果其他结构更适合,我将不胜感激您的分享。

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!       
}

}

【问题讨论】:

  • "Any chance I could do this without 'redrawing' the canvas?" -- 为什么不重新绘制组件,或者在这里,您只需调用repaint()

标签: java swing jframe jpanel graphics2d


【解决方案1】:

我有没有机会在不“重绘”画布的情况下做到这一点?

当然。将它们绘制到 BufferedImage,而 BufferedImage 本身显示在 JLabel 中。例如。如this answer 所示。

但是不要太快走这条路。 Java-2D 可以在 paint() 方法中为数千个图形元素设置动画。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-12-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-02-09
    • 1970-01-01
    相关资源
    最近更新 更多