Sunday April 27, 2008
Using Spring to Enable the Print Menu Item
Recently I blogged about Spring integration into the NetBeans module system. Here's how you would use that integration to enable the Print menu item for a TopComponent. In effect, what this example shows is how to use a Spring configuration file to extend a TopComponent's Lookup to include a PrintCookie:
- Implement PrintCookie, which requires a dependency on Nodes API:
package org.yourorghere.nbspringdemo1; import javax.swing.JOptionPane; import org.openide.cookies.PrintCookie; public class PrintImpl implements PrintCookie { @Override public void print() { JOptionPane.showMessageDialog(null, "I am printing..."); } } - Create a bean for your PrintCookie in your Spring app-config.xml:
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd"> <bean id="printCookie" class="org.yourorghere.nbspringdemo1.PrintImpl"/> </beans> - Add to the TopComponent's constructor:
//Bring in Spring: String[] contextPaths = new String[]{"org/yourorghere/nbspringdemo1/app-context.xml"}; ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext(contextPaths); //Convert Spring to Lookup: Lookup lookup = NbSpring.create(ctx); //Potentially, look up your JPanel and add to TopComponent: //Item<JPanel> item = lookup.lookupItem(new Template<JPanel>(JPanel.class, null, null)); //JPanel foo = item.getInstance(); //add(foo, java.awt.BorderLayout.CENTER); //Add node for PrintCookie: AbstractNode myNode = new AbstractNode(Children.LEAF, lookup); ProxyLookup proxyLookup = new ProxyLookup(Lookups.singleton(myNode), myNode.getLookup()); associateLookup(proxyLookup);
That's it. Now the Print menu item is enabled whenever the TopComponent is activated. You could narrow it down further, basing it on whether something in the TopComponent has changed.
Thanks to Jaroslav Tulach for showing me how to do this.
Apr 27 2008, 03:05:47 PM PDT Permalink


