Charting Data with a TableModel
Our last example shows that the table machinery isn’t just
for building tables; you can use it to build other kinds of components
(like the pie chart in Figure
16-6). If you think about it, there’s no essential difference
between a pie chart, a bar chart, and many other kinds of data displays;
they are all different ways of rendering data that’s logically kept in a
table. When that’s the case, it is easy to use a TableModel to manage the data and build your
own component for the display.
With AWT, building a new component was straightforward: you simply
created a subclass of Component. With
Swing, it’s a little more complex because of the distinction between the
component itself and the user-interface implementation. But it’s not
terribly hard, particularly if you don’t want to brave the waters of the
Pluggable L&F. In this case, there’s no good reason to make pie
charts that look different on different platforms, so we’ll opt for
simplicity. We’ll call our new component a TableChart; it extends JComponent. Its big responsibility is keeping
the data for the component updated; to this end, it listens for TableModelEvents from the TableModel to determine when changes have been
made.
To do the actual drawing, TableChart relies on a delegate, PieChartPainter. To keep things flexible,
PieChartPainter is a subclass of
ChartPainter, which gives us the
option of building other kinds of chart painters (bar chart painters,
etc.) in the future. ChartPainter ...