Проблемы при изменении данных X и Y при использовании Jframe - PullRequest
0 голосов
/ 10 декабря 2018

Во-первых, я хотел бы сказать, что я новичок в Java, поэтому я хотел бы заранее извиниться, если некоторые из этих постов не имеют смысла.

Я создаю программу с графическим интерфейсом.Программа позволяет пользователю загружать файлы в формате CSV, JSON или XML.Затем программа читает каждую строку файла, разбивает каждый тип данных и затем анализирует их в списке массивов.Этот список данных затем сохраняется в объекте.

Цель программы состоит в том, чтобы затем манипулировать данными (например, создавать средние значения данных, минимальные значения данных, максимальные значения данных) ипостроить манипулированные данные на графике.

Итак, пользователь загружает файл, затем нажимает кнопку для построения графика.

У меня проблемы с отображением ВРЕМЕНИ вдоль оси X графика.Ниже приведен скриншот моего графического интерфейса.Как вы можете видеть, график отображает данные TEMP очень хорошо, однако я не уверен, откуда график получает данные для оси X (он увеличивается с шагом 5000).

https://imgur.com/a/Vg9A8Kd

Я думаю, что одной из моих главных проблем здесь является понимание того, как правильно использовать библиотеки LocalDateTime и DateTimeFormatter.Это связано с тем, как время / дата хранятся в файлах CSV / JSON / XML.Вот первые несколько строк файла CSV, которые помогут вам понять проблему.

millis,stamp,datetime,light,temp,vcc
1000, 1273010254, 2010/5/4 21:57:34, 333, 78.32, 3.54
2000, 1273010255, 2010/5/4 21:57:35, 333, 78.32, 3.92
3000, 1273010256, 2010/5/4 21:57:36, 344, 78.32, 3.95
4000, 1273010257, 2010/5/4 21:57:37, 326, 78.32, 3.97

Я исследовал Jframe и изо всех сил пытался понять, как его реализовать.Тем не менее, я изо всех сил пытаюсь найти соответствующую информацию о том, как использовать Jframe при использовании данных из списка массивов.

Ниже я поделюсь с вами некоторыми из классов и кода.

Класс Light Chart

import java.awt.Dimension;
import java.util.ArrayList;
import javax.swing.JPanel;
import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartPanel;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.axis.NumberAxis;
import org.jfree.chart.plot.PlotOrientation;
import org.jfree.chart.plot.XYPlot;
import org.jfree.chart.renderer.xy.XYLineAndShapeRenderer;
import org.jfree.data.xy.*;
import org.jfree.ui.ApplicationFrame;
import org.jfree.ui.RefineryUtilities;


public class LightBarChart extends ApplicationFrame
{

public LightBarChart(String title) {
    super(title);
    // TODO Auto-generated constructor stub
}

/**
 * 
 */
private static final long serialVersionUID = 2L;

//arraylist for LIGHT
private ArrayList<Double> light = new ArrayList<Double>();


public ArrayList<Double> getLight() {
    return light;
}

public void setLight(ArrayList<Double> light) {
    this.light = light;
}



private XYDataset createDataset()
{
    XYSeries xyseries1 = new XYSeries("Light");
    int i = 1;
    for(double d:light){
        xyseries1.add(i, d);//adds all the element of the araylist into the xyseries
        i++;
    }

    ///XYSeries xyseries2 = new XYSeries("Light");
    //i = 1;
    //for(double d:light){
        //xyseries2.add(i, d);//adds all the element of the araylist into the xyseries
        //i++;
    //}     

    XYSeriesCollection xyseriescollection = new XYSeriesCollection();
    xyseriescollection.addSeries(xyseries1);
    //xyseriescollection.addSeries(xyseries2);

    return xyseriescollection;
}

private JFreeChart createChart(XYDataset xydataset)
{
    JFreeChart jfreechart = ChartFactory.createXYLineChart("Line Chart Showing Light", "X", "Y", xydataset, PlotOrientation.VERTICAL, true, true, false);
    XYPlot xyplot = (XYPlot)jfreechart.getPlot();
    xyplot.setDomainPannable(true);
    xyplot.setRangePannable(true);
    XYLineAndShapeRenderer xylineandshaperenderer = (XYLineAndShapeRenderer)xyplot.getRenderer();
    xylineandshaperenderer.setBaseShapesVisible(true);
    xylineandshaperenderer.setBaseShapesFilled(true);
    NumberAxis numberaxis = (NumberAxis)xyplot.getRangeAxis();
    numberaxis.setStandardTickUnits(NumberAxis.createIntegerTickUnits());
    return jfreechart;
}

public JPanel createDemoPanel()
{
    JFreeChart jfreechart = createChart(createDataset());
    ChartPanel chartpanel = new ChartPanel(jfreechart);
    chartpanel.setMouseWheelEnabled(true);
    return chartpanel;
}

public void plot()
{
    //super(s);
    JPanel jpanel = createDemoPanel();
    jpanel.setPreferredSize(new Dimension(750, 450));
    setContentPane(jpanel);     
    this.pack();
    RefineryUtilities.centerFrameOnScreen(this);
    this.setVisible(true);



}
}

CSV READER CLASS

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;

public class CSVReader {

//create a class that will hold arraylist which will have objects representing all lines of the file

private List<Data> dataList = new ArrayList<Data>();
private String path;


public List<Data> getDataList() {
    return dataList;
}

public String getPath() {
    return path;
}
public void setPath(String path) {
    this.path = path;
}

//next job is to create a method to read through the csv stored in the path
//and create the list of data and store in the dataList

public void readCSV() throws IOException{

    //i will create connection with the file, in the path
    BufferedReader in  = new BufferedReader(new FileReader(path));  

    String line = null;
    line = in.readLine();

    while((line = in.readLine())!=null){

        //we have each line in the variable 'line'

        //we need to split and store in the temporary variable and create an object


        String[] splits = line.split(",");// line.split("\\s*(=>|,|\\s)\\s*");

        long millis = Long.parseLong(splits[0].trim());
        long stamp = Long.parseLong(splits[1].trim());
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy/M/d H:m:s");
        LocalDateTime datetime = LocalDateTime.parse(splits[2].trim(), formatter);
        LocalDate date = datetime.toLocalDate();
        LocalTime time = datetime.toLocalTime();
        DateTimeFormatter f = DateTimeFormatter.ofPattern( "uuuu/M/d HH:mm:ss" );
        LocalDateTime localDateTime = LocalDateTime.parse( "2010/5/4 21:57:34" , f );
        double light = Double.parseDouble(splits[3].trim());
        double temp = Double.parseDouble(splits[4].trim());
        double vcc = Double.parseDouble(splits[5].trim());


        Data d = new Data(millis,stamp,datetime,light,temp,vcc);//uses constructor

        dataList.add(d);

    }end of while loop

}
}

Класс данных

import java.time.LocalDate;
import java.time.LocalDateTime;

public class Data {

//define the attributes for your data here

private long millis;
private long stamp;
private LocalDateTime datetime;
//private String datetime;
private double light;
private double temp;    
private double vcc;

public Data() {}



public Data(long millis, long stamp, LocalDateTime datetime, double light, double temp, double vcc) {
    super();
    this.millis = millis;
    this.stamp = stamp;
    this.datetime = datetime;
    this.light = light;
    this.temp = temp;
    this.vcc = vcc;
}



public long getMillis() {
    return millis;
}

public void setMillis(long millis) {
    this.millis = millis;
}

public long getStamp() {
    return stamp;
}

public void setStamp(long stamp) {
    this.stamp = stamp;
}

public LocalDateTime getDatetime() {
    return datetime;
}

public void setDatetime(LocalDateTime datetime) {
    this.datetime = datetime;
}

public double getLight() {
    return light;
}

public void setLight(double light) {
    this.light = light;
}

public double getTemp() {
    return temp;
}

public void setTemp(double temp) {
    this.temp = temp;
}

public double getVcc() {
    return vcc;
}

public void setVcc(double vcc) {
    this.vcc = vcc;
}



@Override
public String toString() {
    return "Data [millis=" + millis + ", stamp=" + stamp + ", datetime=" + datetime + ", light=" + light + ", temp="
            + temp + ", vcc=" + vcc + "]";
}



}
...