在java中,你能从两个数组中创建一个折线图吗?

时间:2016-10-17 22:14:28

标签: java arrays graph

我想制作一个x值为1-100且y值范围为1-18的折线图。我把它们存储在两个目前打印到文本文件的数组中(出于显而易见的原因,我不想手动制作包含100个点的条形图)。也许使用应用程序窗口的东西?

我不知道我能给你什么更多的信息,让我更清楚我要求的东西,所以如果有任何东西只是要求它并且生病了。

1 个答案:

答案 0 :(得分:1)

这样的事可能吗?

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Graphics;

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;

public final class LineGraph {
    private LineGraph() {

    }

    public static void main(final String[] args) {
        SwingUtilities.invokeLater(LineGraph::doRun);
    }

    private static void doRun() {
        final int[] x = new int[] {0, 40, 80, 120, 160, 200, 240, 280, 320, 360};
        final int[] y = new int[] {100, 200, 100, 50, 200, 0, 300, 200, 100, 300};

        final
        JFrame jFrame = new JFrame();
        jFrame.getContentPane().setLayout(new BorderLayout());
        jFrame.getContentPane().add(new JPanelImpl(x, y), BorderLayout.CENTER);
        jFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        jFrame.setSize(800, 600);
        jFrame.setVisible(true);
    }

    private static final class JPanelImpl extends JPanel {
        private final int[] x;
        private final int[] y;

        public JPanelImpl(final int[] x, final int[] y) {
            this.x = x;
            this.y = y;
        }

        @Override
        public void paintComponent(final Graphics graphics) {
            graphics.setColor(Color.WHITE);
            graphics.fillRect(0, 0, getWidth(), getHeight());

            for(int i = 0; i < this.x.length; i++) {
                if(i + 1 < this.x.length) {
                    final int x0 = this.x[i];
                    final int y0 = this.y[i];
                    final int x1 = this.x[i + 1];
                    final int y1 = this.y[i + 1];

                    graphics.setColor(Color.BLACK);
                    graphics.drawLine(x0, y0, x1, y1);
                    graphics.fillOval(x1 - 3, y1 - 3, 6, 6);
                }
            }
        }
    }
}