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

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:

  1. Make a JFileChooser object. For example,
    JFileChooser d = new JFileChooser();
  2. 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.
  3. 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.
  4. 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