A More Complex Bean

Example 15-3 shows another bean, YesNoPanel. This bean displays a message (using MultiLineLabel) and three buttons to the user. It fires an event when the user clicks on one of the buttons. YesNoPanel is intended for use within dialog boxes, as it provides an ideal way to ask the user yes/no/cancel questions. Figure 15-1 shows a YesNoPanel instance being edited with the ShowBean program.

The YesNoPanel bean in a beanbox

Figure 15-1. The YesNoPanel bean in a beanbox

The YesNoPanel bean uses a custom AnswerEvent type to notify AnswerListener objects when the user has clicked on one of its three buttons. This new event class and listener interface are defined in the next section.

Notice that YesNoPanel doesn’t use any classes from the java.beans package. One of the surprising things about beans is that they typically don’t have to use any classes from this package. As you’ll see later in this chapter, it’s the auxiliary classes that are shipped with a bean that make heavy use of that package.

Example 15-3. YesNoPanel.java

package je3.beans; import java.awt.*; import java.awt.event.*; import javax.swing.*; import java.util.List; import java.util.ArrayList; /** * This JavaBean displays a multi-line message and up to three buttons. It * fires an AnswerEvent when the user clicks on one of the buttons **/ public class YesNoPanel extends JPanel { // Properties of the bean. protected String messageText; ...

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.