O'Reilly logo

Java Swing by Dave Wood, Marc Loy, Robert Eckstein

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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 TableModelEvents 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 ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required