Sunday Apr 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:

  1. 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...");
        }
    
    }

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

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

About

Geertjan Wielenga (@geertjanw) is a Principal Product Manager in the Oracle Developer Tools group living & working in Amsterdam. He is a Java technology enthusiast, evangelist, trainer, speaker, and writer. He blogs here daily.

The focus of this blog is mostly on NetBeans (a development tool primarily for Java programmers), with an occasional reference to NetBeans, and sometimes diverging to topics relating to NetBeans. And then there are days when NetBeans is mentioned, just for a change.

Search

Archives
« April 2008 »
SunMonTueWedThuFriSat
  
2
4
5
13
18
19
23
30
   
       
Today