Friday April 25, 2008
NetBeans Lookup Example
Lookup example, producing a new message automatically every 2 seconds:
- Provider module:
public final class Selection { private Selection() { } private static MyLookup LKP = new MyLookup(); //Make the Lookup accessible: public static Lookup getSelection() { return LKP; } private static final class MyLookup extends ProxyLookup implements Runnable { private static ScheduledExecutorService EX = Executors.newSingleThreadScheduledExecutor(); public MyLookup() { EX.schedule(this, 2000, TimeUnit.MILLISECONDS); } private int i; @Override public void run() { //Add to the Lookup a new MyHello: setLookups(Lookups.singleton(new MyHello(i++))); EX.schedule(this, 2000, TimeUnit.MILLISECONDS); } } private static final class MyHello implements HelloProvider { private String text; public MyHello(int i) { text = i % 2 == 0 ? "Hello from Tom" : "Hello from Jerry"; } public String sayHello() { return text; } } }public interface HelloProvider { public String sayHello(); } - Consumer module, with dependency on the provider module:
final class HelloTopComponent extends TopComponent implements LookupListener { private static HelloTopComponent instance; private static final String PREFERRED_ID = "HelloTopComponent"; private Resultresult; private HelloTopComponent() { ... ... ... //We have a dependency on the provider module, //where we can access Selection.getSelection(): Lookup lookup = Selection.getSelection(); //Get the HelloProvider from the result: result = lookup.lookupResult(HelloProvider.class); //Add LookupListener on the result: result.addLookupListener(this); //Call result changed: resultChanged(null); } StringBuilder sb = new StringBuilder(); int i; @Override public void resultChanged(LookupEvent arg0) { long mills = System.currentTimeMillis(); Collection<? extends HelloProvider> instances = result.allInstances(); for (HelloProvider helloProvider : instances) { String hello = helloProvider.sayHello(); sb.append(mills + ": " + hello + "\n"); jTextArea1.setText(sb.toString()); } } ... ... ...
Result:

Apr 25 2008, 07:54:49 AM PDT Permalink
3 Comments


