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

Get Java Examples in a Nutshell, 3rd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.