Scroll Bars

.

Scroll Bars

.

Decorator Pattern

Context

  1. Component objects can be decorated (visually or behaviorally enhanced)
  2. The decorated object can be used in the same way as the undecorated object
  3. The component class does not want to take on the responsibility of the decoration
  4. There may be an open-ended set of possible decorations

Decorator Pattern

Solution

  1. Define an interface type that is an abstraction for the component
  2. Concrete component classes realize this interface type.
  3. Decorator classes also realize this interface type.
  4. A decorator object manages the component object that it decorates
  5. When implementing a method from the component interface type, the decorator class applies the method to the decorated component and combines the result with the effect of the decoration.

Decorator Pattern

.

Decorator Pattern: Scroll Bars

Name in Design Pattern
Actual Name (scroll bars)
Component Component
ConcreteComponent JTextArea
Decorator JScrollPane
method()
a method of Component (e.g. paint)

ScrollPaneTest.java


import java.awt.*;
import javax.swing.*;

public class ScrollPaneTest
{
   public static void main(String[] args)
   {  
      JFrame frame = new JFrame();
      Container contentPane = frame.getContentPane();

      JTextArea area = new JTextArea(20, 40); // 20 rows, 40 columns
      JScrollPane scroller = new JScrollPane(area);
      contentPane.add(scroller, BorderLayout.CENTER);

      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      frame.setSize(200, 200);
      frame.setVisible(true);
   }
}


Results


Maintained by John Loomis, updated Sun Feb 25 21:40:04 2007