// Version 2 of modified BarChart class from the JFreeChart Example // Create barchart of currencies and exchange rates from // data read from two input files. // 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 BarChart2 { public static void main(String[] args) { Scanner s1 = null; File f1 = new File("currencies.txt"); try { s1 = new Scanner(f1); } catch (FileNotFoundException e) { System.out.println("Couldn't open currencies file."); System.out.println(1); } Scanner s2 = null; File f2 = new File("exchange-rates.txt"); try { s2 = new Scanner(f2); } 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(s1.hasNextLine( )) { String currency = s1.nextLine( ); double exchangeRate = Double.parseDouble(s2.nextLine( )); // 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); } } }