Swing introduction  Swing components  Events and listeners  Text fields/labels  Layouts  JPanel and Box

Threads Database Profiling Regular expressions Random numbers Compression Exceptions C Equivalents in Java
 Comment on this article  List of Java topics

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:


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.

Unless otherwise stated, the Java programming articles and tutorials on this site are written by Neil Coffey. Suggestions are always welcome if you wish to suggest topics for Java tutorials or programming articles, or if you simply have a programming question that you would like to see answered on this site. Most topics will be considered. But in particular, the site aims to provide tutorials and information on topics that aren't well covered elsewhere, or on Java performance information that is poorly described or understood. Suggestions may be made via the Javamex blog (see the site's front page for details).
Copyright © Javamex UK 2009. All rights reserved.