Using JComponent
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
"behave" properly.
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:
Listeners
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.
If you enjoy this Java programming article, please share with friends and colleagues. Follow the author on Twitter for the latest news and rants.
Editorial page content written by Neil Coffey. Copyright © Javamex UK 2021. All rights reserved.