O'Reilly logo

Java Examples in a Nutshell, 3rd Edition by David Flanagan

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

A Simple Bean

As noted earlier, Swing and AWT components can all function as beans. When you write a custom GUI component, it is not difficult to make it function as a bean as well. Example 15-1 shows the definition of a custom JavaBeans component, MultiLineLabel, that displays one or more lines of static text.

What makes this component a bean is that all its properties have get and set accessor methods. Because MultiLineLabel doesn't respond to user input in any way, it doesn't define any events, so no event-listener registration methods are required. MultiLineLabel also defines a no-argument constructor, so that it can be easily instantiated by beanboxes.

Example 15-1. MultiLineLabel.java

package je3.beans; import java.awt.*; import javax.swing.*; import java.util.StringTokenizer; /** * A custom component that displays multiple lines of text with specified * margins and alignment. **/ public class MultiLineLabel extends JComponent { // User-specified properties protected String label; // The label, not broken into lines protected int margin_width; // Left and right margins protected int margin_height; // Top and bottom margins protected Alignment alignment; // The alignment of the text. // Computed state values protected int num_lines; // The number of lines protected String[ ] lines; // The label, broken into lines protected int[ ] line_widths; // How wide each line is protected int max_width; // The width of the widest line protected int line_height; // Total height of the ...

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