Java Reference
In-Depth Information
Some final issues regarding fragments: Fragments are allowed to have any metadata a
normal bundle can have except
Bundle-Activator
. This makes sense because frag-
ments can't be started or stopped and can only be used when combined with the host
bundle. Attaching a fragment to a host creates a dependency between the two, which is
similar to the dependencies created between two bundles via
Import-Package
or
Require-Bundle
. This means if either bundle is updated or uninstalled, the other bun-
dle is impacted, and any refreshing of the one will likely lead to refreshing of the other.
We started this foray into fragments discussing localization, because it's the main use
case for them. Next, we'll look at an example of how to use fragments for this purpose.
5.4.2
Using fragments for localization
To s e e h o w y o u c a n u s e f r a g m e n t s t o l o c a l i z e a n a p p l i c a t i o n , l e t 's r e t u r n t o t h e s e r v i c e -
based paint program from chapter 4. The main application window is implemented
by the
PaintFrame
class. Recall its design:
PaintFrame
doesn't have any direct depen-
dencies on the
OSG
i
API
. Instead, it uses a
ShapeTracker
class to track
SimpleShape
services in the
OSG
i service registry and inject them into the
PaintFrame
instance.
ShapeTracker
injects services into the
PaintFrame
using its
addShape()
method, as
shown in the following listing.
Listing 5.4 Method used to inject shapes into
PaintFrame
object
public void addShape(String name, Icon icon, SimpleShape shape) {
m_shapes.put(name, new ShapeInfo(name, icon, shape));
JButton button = new JButton(icon);
button.setActionCommand(name);
button.setToolTipText(name);
button.addActionListener(m_reusableActionListener);
if (m_selected == null) {
button.doClick();
}
m_toolbar.add(button);
m_toolbar.validate();
repaint();
}
The
addShape()
method is invoked with the name, icon, and service object of the
SimpleShape
implementation. The exact details aren't important, but the shape is
recorded in a data structure, a button is created for it, its name is set as the button's
tool tip, and, after a few other steps, the associated button is added to the toolbar. The
tool tip is textual information displayed to users when they hover the mouse over the
shape's toolbar icon. It would be nice if this information could be localized.
You can take different approaches to localize the shape name. One approach is
to define a new service property that defines the
ResourceBundle
base name. This
way, shape implementations can define their localization base name, much as they
use service properties to indicate the name and icon. In such an approach, the