Bar Chart Exercise
The exercise is to draw a bar chart, looking like this:

from a data file which the user selects using the Open item of the File menu.
We will do this in stages.
Exercise A
Extend the program BarChartAxes.java,
so that it reads in a fixed file, say sales.dat,
and draws the bar chart. The file sales.dat contains these lines:
23.5
12.7
45
10
8.25
Hints
- Assume the file is one decimal numper line. Use Double.parseDouble(String)
to obtain the double from the line.
- Store the numbers in an array or an ArrayList. The advantage of
using an ArrayList is that you don't need to know how big it's going
to be, but the disadvantage is that you have to convert your doubles into
objects (i.e. Doubles).
- Don't forget to import java.io for file reading, and java.util
if you want ArrayList.
- Calculate an appropriate thickness of bar and gap between bars, depending
on the number of data lines in the file. Scale the height of the bars so that
they fit into your JPanel.
Exercise B
Now make it read from the file chosen by the user. Add an "Open"
item to the file menu. Follow the notes below to create a dialogue box to allow
the user to select a file. Experiment with these files.
Here are the steps (copied from Horstmann/Cornell, Core Java, vol I, page 524)
needed to put up a file dialogue box and recover what the user chooses from
the box:
- Make a JFileChooser object. For example,
JFileChooser d = new JFileChooser();
- Set the directory with, for example,
d.setCurrentDirectory(new File("."));
As you can see, the File class has a constructor that takes a file
name string and produces a File object.
- Show the dialogue box by calling the showOpenDialog() or showSaveDialog()
method. These methods take as parameter the parent component. The call does
not return until the user has pressed OK or cancel. The return value is JFileChooser.APPROVE_OPTION
or JFileChooser.CANCEL_OPTION.
- You get the selected file (as a File object) with getSelectedFile(),
for example
File f = d.getSelectedFile();
If you want to know the file name, call the getName() method on the
File object.
After you have read in the file, you will need to call the repaint()
method of your JPanel to force it to be repainted.

© 2001 Mark Ryan and Alan Sexton