gpt4 book ai didi

java - Java Swing 中的图形绘制仅绘制点

转载 作者:塔克拉玛干 更新时间:2023-11-01 21:39:59 27 4
gpt4 key购买 nike

我目前正在开发一个程序,其中某些数值变量会随着时间的推移而变化,并在每次迭代时显示它们的值。这很好用,但现在我想绘制一个图表来显示它们随时间的演变。因此,我研究了一个在 Swing 中绘制图形的代码示例。我的最终代码如下所示:

public class Populus3 extends JPanel
{
public static void main(String[] args) throws IOException {

final Populus3 pop = new Populus3();

JFrame f = new JFrame(); //where I want to plot the graph
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.add(new GraphingData());
f.setSize(400,400);
f.setLocation(200,200);
f.setVisible(true);


frame = new JFrame("Animation Frame"); //where I'm running animation for another element of the program
frame.add(pop, BorderLayout.CENTER);
frame.setSize(graphSize, graphSize);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

//insert all sort of things

}


public void paint(Graphics g)
{
super.paint(g);
paintCell(g, 1);
Toolkit.getDefaultToolkit().sync(); // necessary for linux users to draw and animate image correctly
g.dispose();
}


public void actionPerformed(ActionEvent e) {
repaint();
}



@Override
protected void paintComponent(Graphics g)
{
super.paintComponent(g);
for(int i = 0; i < particleType.length; i++)
paintCell(g, i); //a method that draws a small circle for the animation panel
}



public static class GraphingData extends JPanel {
int[] data = {
21, 14, 18, 03, 86, 88, 74, 87, 54, 77,
61, 55, 48, 60, 49, 36, 38, 27, 20, 18
};
final int PAD = 20;

protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2 = (Graphics2D)g;
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
int w = getWidth();
int h = getHeight();
// Draw ordinate.
g2.draw(new Line2D.Double(PAD, PAD, PAD, h-PAD));

// Draw abcissa.
g2.draw(new Line2D.Double(PAD, h-PAD, w-PAD, h-PAD));
double xInc = (double)(w - 2*PAD)/(data.length-1);
double scale = (double)(h - 2*PAD)/getMax();
// Mark data points.
g2.setPaint(Color.red);
for(int i = 0; i < data.length; i++) {
double x = PAD + i*xInc;
double y = h - PAD - scale*data[i];
g2.fill(new Ellipse2D.Double(x-2, y-2, 4, 4));
}
}

private int getMax() {
int max = -Integer.MAX_VALUE;
for(int i = 0; i < data.length; i++) {
if(data[i] > max)
max = data[i];
}
return max;
}
}
}

现在,动画面板工作正常。另一方面,图形面板......当我运行程序时,它显示了一堆红点,没有线连接它们。我做错了什么?

最佳答案

除了@Hovercraft 的有用建议外,还可以考虑以下其他方法:

  • GeneralPath 中累积可以根据需要呈现的点,example .

lissajou image

  • 使用合适的坐标系重复调用 drawLine() 连接点,概述 here .

sine image

关于java - Java Swing 中的图形绘制仅绘制点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17536229/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com