JavaFX如何从可观察列表中创建折线图?

时间:2017-06-22 11:14:35

标签: database javafx linechart

我一直在玩这里的折线图教程:http://docs.oracle.com/javase/8/javafx/user-interface-tutorial/line-chart.htm#CIHGBCFI

我想扩展教程并尝试使用数据库中的数据构建折线图,而不是像这样设置数据:

series.getData().add(new XYChart.Data(1, 23));
series.getData().add(new XYChart.Data(2, 14));

我需要从数据库导入数据:

public ObservableList<Items> loadChart() {
    try {
        Statement stmt = connection.createStatement();
        ResultSet rs = stmt.executeQuery("SELECT cost, date FROM Items ORDER BY date ASC");

        ObservableList<Items> data = FXCollections.observableArrayList();

        while(rs.next()){
            Items items = new Items();
            items.setCost(rs.getInt(1));
            items.setDate(rs.getString(2));
            data.add(items);

        }

        return data;

    } catch (Exception e) {
        e.printStackTrace();
    }
    return null;
}

我想在折线图中绘制成本和日期...但是不知道如何这样做(基于可观察列表和教程)。

1 个答案:

答案 0 :(得分:1)

如果您使用的是该示例,则代码应如下所示。

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.logging.Level;
import java.util.logging.Logger;
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.chart.LineChart;
import javafx.scene.chart.NumberAxis;
import javafx.scene.chart.XYChart;
import javafx.stage.Stage;


public class LineChartSample extends Application {

    @Override public void start(Stage stage) {
        stage.setTitle("Line Chart Sample");
        //defining the axes
        final NumberAxis xAxis = new NumberAxis();
        final NumberAxis yAxis = new NumberAxis();
        xAxis.setLabel("Number of Month");
        //creating the chart
        final LineChart<Number,Number> lineChart = 
                new LineChart<Number,Number>(xAxis,yAxis);

        lineChart.setTitle("Stock Monitoring, 2010");
        //defining a series
        XYChart.Series series = new XYChart.Series();
        series.setName("My portfolio");
        //populating the series with data         
        try 
        {
            Connection connection = DriverManager.getConnection("...");//You can use try with resources. Establish a Connection
            Statement stmt = connection.createStatement();//Create Statement
            ResultSet rs = stmt.executeQuery("SELECT cost, date FROM Items ORDER BY date ASC");//Query DB and get results.

            //Iterate through results.
            while(rs.next())
            {
                series.getData().add(new XYChart.Data(rs.getInt(1), Integer.parseInt(rs.getString(2))));//Add data to Chart. Changed the second input to Integer due to LineChart<Number,Number>. This should work, though I haven't tested it.
            }
        }
        catch (SQLException ex) {
            Logger.getLogger(LineChartSample.class.getName()).log(Level.SEVERE, null, ex);
        }

        Scene scene  = new Scene(lineChart,800,600);
        lineChart.getData().add(series);

        stage.setScene(scene);
        stage.show();
    }

    public static void main(String[] args) {
        launch(args);
    }
}
  

以下更新

如果你想拥有一个数据库处理程序类,你可以尝试这样的东西。

  

DBHandler Class

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javafx.scene.chart.XYChart;

/**
 *
 * @author blj0011
 */
public class DBHandler
{
    List<List<Integer>> dataHolder;


    //There is probably a better way to structure this DBHandler Class
    public DBHandler()
    {
        dataHolder = new ArrayList();

        try 
        {
            Connection connection = DriverManager.getConnection("...");//You can use try with resources. Establish a Connection
            Statement stmt = connection.createStatement();//Create Statement
            ResultSet rs = stmt.executeQuery("SELECT cost, date FROM Items ORDER BY date ASC");//Query DB and get results.

            //Iterate through results.
            while(rs.next())
            {
                List<Integer> tempDataHolder = new ArrayList();
                tempDataHolder.add(rs.getInt(1));
                tempDataHolder.add(Integer.parseInt(rs.getString(2)));
                dataHolder.add(tempDataHolder);
            }
        }
        catch (SQLException ex) {
            Logger.getLogger(DBHandler.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    public List<List<Integer>> getDataHolder()
    {
        return dataHolder;
    }

}
  

主类

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.chart.LineChart;
import javafx.scene.chart.NumberAxis;
import javafx.scene.chart.XYChart;
import javafx.stage.Stage;


public class LineChartSample extends Application {

    @Override public void start(Stage stage) {
        stage.setTitle("Line Chart Sample");
        //defining the axes
        final NumberAxis xAxis = new NumberAxis();
        final NumberAxis yAxis = new NumberAxis();
        xAxis.setLabel("Number of Month");
        //creating the chart
        final LineChart<Number,Number> lineChart = 
                new LineChart<Number,Number>(xAxis,yAxis);

        lineChart.setTitle("Stock Monitoring, 2010");
        //defining a series
        XYChart.Series series = new XYChart.Series();
        series.setName("My portfolio");
        //populating the series with data
        DBHandler dbHandler = new DBHandler();

        List<List<Integer>> dataHolder = dbHandler.getDataHolder();
        for(int i = 0; i < dataHolder.size(); i++)
        {
            series.getData().add(new XYChart.Data(dataHolder.get(i).get(0), dataHolder.get(i).get(1)));
        }


        Scene scene  = new Scene(lineChart,800,600);
        lineChart.getData().add(series);

        stage.setScene(scene);
        stage.show();
    }

    public static void main(String[] args) {
        launch(args);
    }
}