java - 读取 CSV 文件,并使用 MVC 在图表中绘制值

标签 java swing csv model-view-controller jfreechart

我正在尝试使用 Java、JFreeChart 和 MVC 概念将 csv 文件中的值绘制成图表。目前,我创建了一个按钮,当单击该按钮时,它会向图表添加一个新的绘图,但是我不这样做,而是希望它从 csv 文件中读取值,该文件由csv 文件适配器并存储在模型中。我想知道是否有人可以帮助我解决这个问题。如果您能提供任何帮助,我将不胜感激。谢谢

//主类

public class Main
{
    public static void main(String[] args) {           
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {                                           
                Model model = new Model(0);

                Controller controller = new Controller(model);
                View view = new View(controller, "-");


                view.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                view.setVisible(true);
            }
        });  
    }
}

//csv文件适配器

public List<Double> readFile(final String filename)
    {
        List<Double> result = new ArrayList<Double>();

        String csvFile = filename;
        BufferedReader br = null;
        String line = "";
        String splitBy = ",";

        try {

            br = new BufferedReader(new FileReader(csvFile));
            while((line = br.readLine()) != null){

                String[] test = line.split(splitBy);
                System.out.println("csvFile [Value= " + test[0] + ", Value=" + test[1] + ", Value=" + test[2] + "]");
                try
                {
                    for (String val : test)
                    {
                        final Double valueToAdd = Double.parseDouble(val);
                        result.add(valueToAdd);
                    }
                }
                catch (NumberFormatException nfe)
                {
                    System.out.println("Failed to parse line: " + line);
                }
            }   
        }
        catch(FileNotFoundException e){
            e.printStackTrace();
        }catch (IOException e){
            e.printStackTrace();
        }finally{
            if (br != null){
                try{
                    br.close();
                } catch (IOException e){
                    e.printStackTrace();
                }
            }
        }

        return result;
    }
}

//型号

public class Model {

  private int x;

    public Model(){
        x = 0;
    }

    public Model(int x){
        this.x = x;
    }

    public void incX(){
        x++;
    }

    public int getX(){
        return x;
    }

    public void addDataset(final List<Double> data)
    {
        System.out.println("Added data to model");
        for (Double d : data)
        {
            System.out.println("Value: " + d.toString());
        }
    }
}

//查看

public class View extends JFrame
{
    private Controller controller;

    private JFrame frame;
    private JLabel label;
    private JButton button;
    private ChartDisplayWidget myChart;

    public View(Controller c, String text){
        this.controller = c;
        getContentPane().setLayout(new BorderLayout());                                          
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);           
        setSize(1000,1000);        

        //label = new JLabel(text);
        //getContentPane().add(label, BorderLayout.CENTER);

        button = new JButton("Button");        
        getContentPane().add(button, BorderLayout.SOUTH); 
        button.addActionListener(new Action());

        myChart = new ChartDisplayWidget();
        getContentPane().add(myChart, BorderLayout.CENTER);
    }

    public class Action implements ActionListener {

        public void actionPerformed (ActionEvent e){
            System.out.println("I was clicked");
            controller.control();
            myChart.addTimeSeriesPerformancePlot("NewPlot", new Double[] {60.0, 40.0, 500.0, 10.0});    

               /*this is where I would like to plot the values from the csv file*/
        }
   }

    public JButton getButton(){
        return button;
    }

    public void setText(String text){
        label.setText(text);
    }
}

//controller

public class Controller {

    public Model model;
    public ActionListener actionListener;

    public Controller(Model model){
        this.model = model;
    }

    public void control(){        
        CSVFileAdapter c = new CSVFileAdapter();
        model.addDataset(c.readFile("C:/dstat.csv"));

    }
}

//图表显示小部件

public class ChartDisplayWidget extends JPanel
{
    /**
     * 
     */
    private static final long serialVersionUID = 1L;

    private TimeSeriesCollection chartData;
    private JFreeChart chart;

    public ChartDisplayWidget()
    {
        init();
    }

    public void init()
    {
        final XYDataset dataset = getSampleData();

        chart = ChartFactory.createTimeSeriesChart(
                "Our test chart",
                "Time",
                "Some Value",
                dataset);

        final ChartPanel chartPanel = new ChartPanel(chart); 

        add(chartPanel);
    }

    public void addTimeSeriesPerformancePlot(final String plotName, final Double[] values)
    {
        final TimeSeries newSeries = new TimeSeries(plotName);

        int arrLen = values.length;
        int monthIndex = 2;
        int yearIndex = 2001;
        for (int index = 0; index < arrLen; index++)
        {
            newSeries.add(new Month(monthIndex++, yearIndex++), values[index]);
        }
        chartData.addSeries(newSeries);
    }

    private XYDataset getSampleData()
    {
        TimeSeries s1 = new TimeSeries("Max CPU");

        s1.add(new Month(2, 2001), 181.5);
        s1.add(new Month(3, 2001), 20.5);
        s1.add(new Month(4, 2001), 1.1);
        s1.add(new Month(5, 2001), 81.5);
        s1.add(new Month(6, 2001), 1181.5);
        s1.add(new Month(7, 2001), 1081.5);

        TimeSeries s2 = new TimeSeries("Disk I/O");

        s2.add(new Month(2, 2001), 50.0);
        s2.add(new Month(3, 2001), 55.0);
        s2.add(new Month(4, 2001), 60.6);
        s2.add(new Month(5, 2001), 70.8);
        s2.add(new Month(6, 2001), 1000.1);
        s2.add(new Month(7, 2001), 1081.5);

        chartData = new TimeSeriesCollection();
        chartData.addSeries(s1);
        chartData.addSeries(s2);

        return chartData;
    }
}

最佳答案

使用observer pattern :更新模型,一个未指定的实现XYDataset,监听 View 将更新自身作为响应。例子见herehere 。由于文件延迟本质上是不可预测的,因此请在 SwingWorker 的后台线程中读取文件。 ,publish()中间结果,并在process()中更新模型;显示了 JFreeChart 示例 here .

关于java - 读取 CSV 文件,并使用 MVC 在图表中绘制值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21281407/

相关文章:

java - 在圆中定位组件

java - 显示 JTable 对象

java - 无法解析第三方库

java - 从 Web 应用程序执行需要 sudo 的 shell 脚本

java - "Inconsistent datatypes: expected DATE got NUMBER"与 DepartmentsImpl 类

Java JFrame : howto parse recursively through componets (i.如果使用 JScrollPane)

java - 如何以编程方式将数据库中的数据导出为 .csv 格式?

java - Java 中的 CSV 解析 - 工作示例..?

mysql - 将数据从 csv 文件导入 MySQL 表时如何避免创建空格

java - 无法从我的 android 应用程序访问 mysql 数据库