java - 使用 Paint 组件绘制折线图

标签 java graph paint paintcomponent

您将如何使用线程的输出创建折线图,这些线程是在 52 秒的时间内运行的传入和传出账单的模拟,这将显示在折线图上,如下所示

我想使用绘图组件,而不是像 JChart 这样的任何第三方类。

enter image description here

最佳答案

假设您有一些用于绘画的 JPanel 对象,我会将以下内容添加到您的对象中:

public class GraphPanel extends JPanel{
    //static constants for defining the size and positioning of the graph on canvas
    //Ignore the values I chose, they were completely random :p
    private static final int X_AXIS_LENGTH = 1000;
    private static final int Y_AXIS_LENGTH = 500;

    private static final int X_AXIS_OFFEST = 50;
    private static final int Y_AXIS_OFFSET = 50;
...

这些都应该是常量值,定义您希望图表在 Canvas 上的大小(轴长度)及其位置(偏移量)。

然后,您可以在 paintComponent 方法中引用这些值,以查找要在 Canvas 上为此更新绘制的线条的实际位置。

...
@Override
public void paintComponent(Graphics g){
    int x, y;
    int prevX, prevY;
    int maxX, maxY;
    ...
    //retrieve values from your model for the declared variables
    ...
    //calculate the coords of your line on the canvas
    int xPos = ((x / maxX) * X_AXIS_LENGTH) + X_AXIS_OFFSET;
    ...
    //do the same for y, prevX, prevY and then you can use g.drawLine
}
...

请注意,您想要更改 maxXmaxY,因为 xy 值正在移动到这些值之上限制,您将需要添加一些额外的代码来检查该更改并使用新的限制重新绘制整个图表。

关于java - 使用 Paint 组件绘制折线图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9497806/

相关文章:

python - 在 Networkx 中获取特定类型的节点

javascript - D3.js 强制有向图,通过使边相互排斥来减少边交叉

java - 如何在android中绘制从Firebase数据库检索的数据

java - 如何从 Main 刷新 JApplet?

java - 从另一个类调用paint()方法?

java - 使用 for 循环创建牛眼

java - 单击复选框时如何调用bean方法

java - Guava + 合并多个文件并跳过重复的标题

java - Double.doubleToLongBits(x) 的含义

java - 如何解决连接工厂从createConnection返回null的问题