猿问

用Java绘制简单的折线图

在我的程序中,我想绘制一个简单的分数线图。我有一个文本文件,并且在每一行上都是一个整数分数,我已阅读该分数并将其作为参数传递给我的图形类。我在实现graph类时遇到了一些麻烦,我所看到的所有示例都将它们的方法和它们的main放在同一个类中,而我不会。


我希望能够将数组传递给对象并生成图形,但是在调用我的绘画方法时,它要求我提供Graphics g ...这是我到目前为止所拥有的:


public class Graph extends JPanel {


    public void paintGraph (Graphics g){


        ArrayList<Integer> scores = new ArrayList<Integer>(10);


        Random r = new Random();


        for (int i : scores){

            i = r.nextInt(20);

            System.out.println(r);

        }


        int y1;

        int y2;


        for (int i = 0; i < scores.size(); i++){

            y1 = scores.get(i);

            y2 = scores.get(i+1);

            g.drawLine(i, y1, i+1, y2);

        }

    }

}

现在,我已经插入了一个简单的随机数生成器来填充我的数组。


我有一个现有的框架,并且基本上想实例化Graph类并将面板安装到我的框架上。非常抱歉,这个问题似乎很混乱,但是我睡得很少。


我的主要声明中的代码是:


testFrame = new JFrame();

testFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

Graph graph = new Graph();

testFrame.add(graph);

我不确定确切是什么SSCE,但这是我的尝试:


public class Test {


    JFrame testFrame;

    public Test() {

        testFrame = new JFrame();

        testFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        Graph graph = new Graph();

        testFrame.add(graph);

        testFrame.setBounds(100, 100, 764, 470);

        testFrame.setVisible(true);

    }

Graph.java


public class Graph extends JPanel {

    public Graph() {

       setSize(500, 500);

    }


    @Override

    public void paintComponent(Graphics g) {

        Graphics2D gr = (Graphics2D) g; // This is if you want to use Graphics2D

        // Now do the drawing here

        ArrayList<Integer> scores = new ArrayList<Integer>(10);


        Random r = new Random();


        for (int i : scores) {

            i = r.nextInt(20);

            System.out.println(r);

        }


        int y1;

        int y2;


        for (int i = 0; i < scores.size() - 1; i++) {

            y1 = (scores.get(i)) * 10;

            y2 = (scores.get(i + 1)) * 10;

            gr.drawLine(i * 10, y1, (i + 1) * 10, y2);

        }

    }

}


ibeautiful
浏览 1659回答 3
3回答

繁华开满天机

有许多开源项目可以通过几行代码为您处理所有折线图。这是CSV使用XChart库从一对文本()文件中的数据绘制折线图的方法。免责声明:我是该项目的首席开发人员。在此示例中,存在两个文本文件./CSV/CSVChartRows/。请注意,文件中的每一行代表要绘制的数据点,并且每个文件代表不同的序列。series1包含x,y和error bar数据,而series2包含公正x和y数据。series1.csv1,12,1.42,34,1.123,56,1.214,47,1.5series2.csv1,562,343,124,26源代码public class CSVChartRows {&nbsp; public static void main(String[] args) throws Exception {&nbsp; &nbsp; // import chart from a folder containing CSV files&nbsp; &nbsp; XYChart chart = CSVImporter.getChartFromCSVDir("./CSV/CSVChartRows/", DataOrientation.Rows, 600, 400);&nbsp; &nbsp; // Show it&nbsp; &nbsp; new SwingWrapper(chart).displayChart();&nbsp; }}结果图
随时随地看视频慕课网APP

相关分类

Java
我要回答