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.3. 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 easy: 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 pluggable look-and-feel. 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
TableModelEvent
s from the
TableModel
to determine when changes have been
made.
To do the actual drawing, TableChart
relies on a
“delegate.” Our delegate will be a
PieChartPainter
, which is responsible for
rendering the data on the screen. To keep things flexible,
PieChartPainter
is a subclass of
ChartPainter
, which gives us the option of building other ...
Get Java Swing now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.