// Modified BarChart class from the JFreeChart Example // Create barchart of exchange rates from // data read from an input file. // These JAR files must be added to the project as dependencies: // jcommon-1.0.23.jar and jfreechart-1.0.19.jar import java.io.*; import java.util.Scanner; import org.jfree.data.category.DefaultCategoryDataset; import org.jfree.chart.ChartFactory; import org.jfree.chart.plot.PlotOrientation; import org.jfree.chart.JFreeChart; import org.jfree.chart.ChartUtilities; public class BarChart { public static void main(String[] args) { Scanner s = null; File f = new File("exchange-rates.txt"); try { s = new Scanner(f); } catch (FileNotFoundException e) { System.out.println("Couldn't open input file."); System.out.println(1); } // Create dataset to hold values for barchart. DefaultCategoryDataset barChartDataset = new DefaultCategoryDataset(); // Read currency rates from input file using // to create bars in barchart while(s.hasNextLine( )) { String line = s.nextLine(); String[] fields = line.split(","); String currency = fields[0].trim(); double exchangeRate = Double.parseDouble(fields[1].trim()); // Add data to barchart dataset barChartDataset.addValue(exchangeRate, "total", currency); } // Define JFreeChart object that represents line chart. JFreeChart barChartObject = ChartFactory.createBarChart( "Currency Exchange Rates", "Currency Code", "Currency Rate", barChartDataset, PlotOrientation.VERTICAL, false, // Include legend. false, // Include tooltips. false); // Include URLs. // Write line chart to a file. int imageWidth = 640; int imageHeight = 480; File barChart = new File("exchange-rates.png"); try { ChartUtilities.saveChartAsPNG( barChart, barChartObject, imageWidth, imageHeight); } catch (IOException e) { System.out.println("Could not output image file."); System.exit(2); } } }