The JComponent is essentially the must "basic" Swing component. In user programs,
the main use of the JComponent class is in fact to override it in order to
create a Swing component that lets you paint arbitrary graphics. From that point
of view, it is to some extent the Swing equivalent of the AWT Canvas class.
To use JComponent, the procedure is usually as follows:
- create a subclass of JComponent;
- override the paintComponent() method to draw whatever
graphics are required;
- override getPreferredSize(), getMinimumSize()
and getMaximumSize() to make your new component
The JComponent class can therefore be used to implement components that
draw graphs, diagrams etc. For example, the Currency Quoter
application uses a JComponent to draw the graph, as shown in the screenshot below:
Your JComponent can also have listeners added to it, for example, to respond
to mouse events.
A common mistake is to override paint() rather than paintComponent().
Although the two are superficially similar, you should override the latter in order for
your new Swing component to render correctly.