站内搜索: 请输入搜索关键词
当前页面: 在线文档首页 > NetBeans API Javadoc 4.1.0

How to use certain NetBeans APIs - NetBeans API Javadoc 4.1.0

How to use certain NetBeans APIs

This page contains extracted usecases for some of the NetBeans modules that offer an API.

How to use ant/project?

Provides the basic infrastructure by which Ant-based projects can be created, read and write configuration parameters and properties from/to disk, satisfy common queries and interfaces, etc. See Javadoc and build system design document.

Mostly an SPI for use by project type providers to create the project type. Also includes a small API/SPI for other projects to find what Ant build steps are necessary to create a certain build product, for use in inter-project dependencies.

Ant project support faq:

How to use support for storing project properties?

Q: I'm creating a customizer (properties dialog) for my project type. I wan't to use the support for simple data types. What do I need to do?

You basicaly need to do two things. First create the representation of the project properties which can be used in the GUI. Second at some time convert the objects back to the ANT properties form and store them into the project.


How to use Debugger Core API?

The debuggercore/api module (Debugger Core API) allows to install different debugger implementation to one IDE. It allows to share some common UI components. See debugger.netbeans.org and debuggercore.netbeans.org for more information.

See Usecases.

How to use Debugger Core UI API?

The debuggercore module (Debugger Core UI) contains shared UI components for all debugger implementations, and defines some SPI for sharing of them. See debugger.netbeans.org and debuggercore.netbeans.org for more information.

See Usecases.

How to use Debugger JPDA API?

The debuggerjpda/api (Debugger JPDA API) defines API for NetBeans Java Debugger. See debugger.netbeans.org and debuggercore.netbeans.org for more information.

See Usecases.

How to use editor/fold?

The Code Folding is part of the editor module functionality and it's responsible for hiding of the portions of the code that are less important for the user at the given time.

API Use Cases

Exploring of the Folds

The code folding structure (fold hierarchy) relates to javax.swing.JTextComponent instance in one-to-one relationship.
To find the code folding hierarchy instance for the given non-null text component the following code snippet can be used:

    JTextComponent editorComponent = ...
    FoldHierarchy hierarchy = FoldHierarchy.get(editorComponent);

Explore the Folds Hierarchy

The tree-based hierarchy has one non-removable and non-collapsable root fold that covers the whole document. It can be obtained by

    FoldHierarchy foldHierarchy = ...
    Fold rootFold = hierarchy.getRootFold();

The children folds of the root fold (or children folds) can be obtained by

    // the hierarchy must be locked prior exploration or manipulation
    hierarchy.lock();
    try {
        Fold rootFold = ...
        int foldCount = rootFold.getFoldCount();
        for (int i = 0; i < foldCount; i++) {
            Fold childFold = rootFold.getFold(i);
        }
    } finally {
        hierarchy.unlock();
    }

Index of the child in its parent can be found by

    hierarchy.lock();
    try {
        Fold rootFold = ...
        int foldIndex = rootFold.getFoldIndex(childFold);
    } finally {
        hierarchy.unlock();
    }

Collapse Nearest Fold

In the given fold hierarchy find the nearest fold right at or after the given offset and collapse it.

    hierarchy.lock();
    try {
        Fold fold = FoldUtilities.findNearestFold(hierarchy, offset);
        hierarchy.collapse(fold);
    } finally {
        hierarchy.unlock();
    }

Expand All Folds

In the given fold hierarchy expand all folds that are currently collapsed.

    FoldUtilities.expand(hierarchy, null);

Collapse All Folds of Certain Type

In the given fold hierarchy collapse all e.g. javadoc folds that are currently collapsed.
The example can be generalized to any fold type.

    FoldUtilities.collapse(hierarchy, JAVADOC_FOLD_TYPE);

Force Fold Expansion for Caret Moving Into Collapsed Fold

In the given fold hierarchy expand the fold into which the caret is going to be moved by Caret.setDot(offset).
The hierarchy must be locked and this example assumes that the underlying document is already read-locked e.g. by Document.render().

    FoldHierarchy hierarchy = FoldHierarchy.get(caretComponent);
    hierarchy.lock();
    try {
        Fold collapsed = FoldUtilities.findCollapsedFold(hierarchy, offset, offset);
        if (collapsed != null && collapsed.getStartOffset() < offset &&
            collapsed.getEndOffset() > offset) {
            hierarchy.expand(collapsed);
        }
    } finally {
        hierarchy.unlock();
    }

Start Listening on Fold Hierarchy Changes

In the given fold hierarchy start to listen on all changes done in the hierarchy.
This is actually used e.g. in the Editor's View Hierarchy that needs to refresh views based on the fold changes.

    hierarchy.addFoldHierarchyListener(new FoldHierarchyListener() {
        public void foldHierarchyChanged(FoldHierarchyEvent evt) {
            // Hierarchy does not need to be locked here
            //
            // evt.getAffectedStartOffset() and getAffectedEndOffset()
            // give text area affected by the fold changes in the event
        }
    });

Inspect Collapsed Folds in Affected Area

Listen on the hierarchy changes and refresh the views in the text area affected by the fold change.
Inspect the collapsed folds in the affected area because special views need to be created for the collapsed folds.
The actual code in the View Hierarchy is somewhat different but the one given here is more descriptive.

    hierarchy.addFoldHierarchyListener(new FoldHierarchyListener() {
        public void foldHierarchyChanged(FoldHierarchyEvent evt) {
            for (Iterator collapsedFoldIterator
                = FoldUtilities.collapsedFoldIterator(hierarchy,
                    evt.getAffectedStartOffset(),
                    evt.getAffectedEndOffset()
                );
                it.hasNext();
            ) {
                Fold collapsedFold = (Fold)it.next();
                // Create special view for the collapsedFold
            }
        }
    });

SPI Use Cases

Create a New Fold Manager

Manipulation of the folds is designed to be done by fold managers.
Those classes implement FoldManager interface in the SPI.
At initialization time they are given instance of FoldOperation through which they can create, add or remove the fold instances.

To create and use a new FoldManager instance it's necessary to

Create a New Fold by Fold Manager

Create a new fold and add it to the hierarchy. The operation is performed by the fold manager either at initialization phase (in the initFolds() which gets called automatically by the infrastructure) or at any other time when the fold manager's operation gets invoked (usually by a listener that the fold manager attaches to be notified about changes that can cause the folds structure to be changed - e.g. a parsing listener for java folds).

Operations that manipulate the hierarchy are done in terms of a valid transaction over the fold hierarchy.
Transactions allow to fire the collected changes as a single FoldHierarchyEvent at the time when they are committed.

    // In the FoldManager's context
    FoldOperation operation = getOperation();
    FoldHierarchyTransaction transaction = operation.openTransaction();
    try {
        Fold fold = operation.createFold(...);
        operation.addFoldToHierarchy(fold, transaction);
    } finally {
        transaction.commit();
    }

Remove Fold from Hierarchy by Fold Manager

Remove the existing fold from the hierarchy

    // In the FoldManager's context
    FoldOperation operation = getOperation();
    FoldHierarchyTransaction transaction = operation.openTransaction();
    try {
        Fold fold = ...
        operation.removeFoldFromHierarchy(fold, transaction);
    } finally {
        transaction.commit();
    }

How to use projects/queries?

General kinds of queries between modules. Queries are one way of solving the intermodule communication problem when it is necessary for some modules to obtain basic information about the system (e.g. whether a particular file is intended for version control) without needing direct dependencies on the module providing the answer (e.g. the project type which controls the file). Details are covered in the Javadoc.

Particular use cases are enumerated in the Javadoc for each query API. Usage consists of simple static method calls. Potentially a wide variety of modules could use these queries; implementations are typically registered by project type providers, though also by Java library and platform implementations.


How to use java/platform?

Many Java-based project types need to be able to configure the version and location of Java to be used when building and running the project. This API/SPI permits these platforms to be registered and queried, and any customizations made in an appropriate GUI and persisted to disk.

The API can be used by any code wishing to know the list of installed platforms and information about each one; typically this would be used by project type providers to implement a customizer dialog. The SPI is intended to be implemented by a few modules supply support for locating and introspecting installed platforms, for example a JDK setup wizard.


How to use java/project?

Provides support infrastructure for projects working with the Java language.

Project type providers wishing to show Java packages in their logical views can use this SPI. Templates which are Java-centric can use it. Projects which wish to implement queries from the Java Support APIs can place implementations in their lookup and these will be delegated to automatically.


How to use java/api?

Models basic aspects of the metadata surrounding Java source files, such as the classpath. More information in the Javadoc.

The API is widely used by all sorts of IDE modules which need to work with Java sources. They can obtain the classpath or boot classpath for a file (if there is one), find out where its source root is, find sources corresponding to bytecode class files, find all sources or classpaths corresponding to open projects, find Javadoc, etc. The SPI is intended mainly for Java platform and library providers, and project type providers, to declare all of this information.


How to use Loaders?

In summary, the LoadersAPI is responsible for scanning files in a directory on disk, weeding out irrelevant files of no interest to the IDE, and grouping the rest into logical chunks, or just determining what type of data each represents. It does this scanning by asking each registered data loader whether or not the given file(s) should be handled. The first loader to recognize a file takes ownership of it, and creates a matching data object to represent it to the rest of the IDE.

A lot of usecases is described in the javadoc. Here is the list of some faqs:

How to add action to folder's popup menu?

The actions that the default folder loader shows in its popup menu are read from a layer folder Loaders/folder/any/Actions so if any module wishes to extend, hide or reorder some of them it can just register its actions there. As code like this does:
    <folder name="Loaders" >
        <folder name="folder" >
            <folder name="any" >
                <folder name="Actions" >
                    <file name="org-mymodule-MyAction.instance" >
                        <attr name="instanceCreate" stringvalue="org.mymodule.MyAction" />
                    </file>
                </folder>
            </folder>
        </folder>
    </folder>
    
As described in general actions registration tutorial.

This functionality is available since version 5.0 of the loaders module. Please use OpenIDE-Module-Module-Dependencies: org.openide.loaders > 5.0 in your module dependencies.

How to allow others to enhance actions of your loader?

If you want other modules to enhance or modify actions that are visible on DataObjects produced by your DataLoader and you are either using DataNode or its subclass, you can just override protected String actionsContext() method to return non-null location of context in layers from where to read the actions.

The usual value should match Loaders/mime/type/Actions scheme, for example java is using Loaders/text/x-java/Actions, but the name can be arbitrary.

This functionality is available since version 5.0 of the loaders module. Please use OpenIDE-Module-Module-Dependencies: org.openide.loaders > 5.0 in your module dependencies.

How to use NetBeans Metadata Repository?

See answer to the use-cases question.

The MDR should be used for data-integration accross different modules in the IDE. An example usecase can be found at http://mdr.netbeans.org/example.html. Basic usecases can also be found in the overview of individual API packages in javadoc.

How to use projects/projectapi?

Provides a generic infrastructure for modelling projects. Documentation available in the Javadoc. The build system design overview describes the basic purpose of modelling projects.

The SPI should be used by modules defining particular project types, e.g. the J2SE project type. The API is to be used primarily by GUI infrastructure and some queries, though other module code may on occasion need to refer to the API.


How to use projects/libraries?

Permits libraries to be defined, customized, and stored by the user for reuse in multiple projects. For example, a Java JAR library has a classpath (usually one JAR), and an optional source path and Javadoc path that may be used for development-time features.

Different technology support modules will supply definitions of different kinds of libraries, e.g. Java JARs, that may be reused in user projects. Modules may register library predefinitions to wrap libraries they bundle. Project type providers can refer to available libraries in customizer dialogs.


How to use projects/projectuiapi?

The module supplies the APIs for the basic, generic UI infrastructure for projects: list of opened projects, main project, basic project-sensitive actions, template wizards, etc.

The main use case is for project type providers to supply logical views and customizers for the project. Also for template providers to create project-aware file templates. Can also get a list of open projects, create different kinds of project-related actions, and select projects on disk.


How to use View Model?

The debuggercore/ViewModel module (View Model) allows to share one TreeTableView among different modules. See debugger.netbeans.org and debuggercore.netbeans.org for more information.

See Usecases.

How to use Actions?

Actions provides system of support and utility classes for 'actions' usage in NetBeans.

There is a great introduction to Actions and its usage in its javadoc. Here is just a list of frequently asked or interesting questions slowly expanding as people ask them:

Actions faq:

How to define configurable Shortcut for Component based shortcut?

Q: The usual Swing way of defining Actions for your component is to create an Action instance and put it into the Input and Action maps of your component. However how to make this Action's shortcut configurable from the Tools/Keyboard Shortcuts dialog?

In order for the action to show up in Keyboards Shortcut dialog you need the action defined in the layer file under "Actions" folder and have the shortcut defined there under "Shortcuts" linking to your action.

    <folder name="Actions" >
        <folder name="Window">
            <file name="org-netbeans-core-actions-PreviousViewCallbackAction.instance"/>
        </folder>
    </folder>

    <folder name="Shortcuts">
        <file name="S-A-Left.shadow">
	    <attr name="originalFile" stringvalue="Actions/Window/org-netbeans-core-actions-PreviousViewCallbackAction.instance"/>
	</file>
    </folder>

The mentioned Action has to be a subclass of org.openide.util.actions.CallbackSystemAction. It does not necessarily has to perform the action, it's just a placeholder for linking the shortcut. You might want to override it's getActionMapKey() and give it a reasonable key.

The actual action that does the work in your component (preferably a simple Swing javax.swing.Action) is to be put into your TopComponent's ActionMap. The key for the ActionMap has to match the key defined in the global action's getActionMapKey() method.

        getActionMap().put("PreviousViewAction", new MyPreviousTabAction());

This way even actions from multiple TopComponents with the same gesture (eg. "switch to next tab") can share the same configurable shortcut.

Note: Don't define your action's shortcut and don't put it into any of the TopComponent's javax.swing.InputMap. Otherwise the component would not pick up the changed shortcut from the global context.


How to use Dialogs API?

The DialogsAPI allows creating a user notification, a dialog's description and also permits it to be displayed. The wizard framework allows create a sequence of panels which leads a user through the steps to complete any task. This API is part of package org.openide.

There is a Wizard Guide Book providing the introductionary information, moreover here is a list of frequently asked questions and their answers:

How to change the title of a wizard?

Q: Although none of my panels have names set (using setName() method) and the method name() in the WizardDescriptor.Iterator returns an empty string, I'm getting "wizard ( )" as the title of each panel in my wizard. When I set the name of the panel and return a string from the method name() I get: "panelName wizard (myName)". The wizard steps are labeled correctly, it just the panel title/name that looks like it adds "wizard ()" to any of my panels. I don't mind the "( )", but I would like to rid of the word "wizard".

A: You can change the format of your wizard's title by WizardDescriptor.setTitleFormat(MessageFormat format) and rid of 'wizard' word in the default wizard's title.


How to use Lookup?

The Lookup is a central part of communication between different parts of a modularized component system. It allows lookup and discovery of features by description of their interfaces. It is available as separate library and also resides in the heart of the NetBeans.

There is a great introduction to Lookup and its usage in its javadoc. Here is just a list of frequently asked or interesting questions slowly expanding as people ask them:

Lookup faq:

How to specify that a service in Lookup should be available only on Windows?

Q: Most of the time I specify interfaces that I want to add to the Lookup class in the layer.xml file. But, let's say I have a platform-specific interface (something on Windows only, for instance).

How can I specify (in the xml, or programmatically) that this service should only be added to the Lookup if the platform is Windows? >

In general there are three ways to achieve this.

How shall I write an extension point for my module?

Q: I have more modules one of them providing the core functionality and few more that wish to extend it. What is the right way to do it? How does the Netbeans platform declare such extension point?

Start with declaring an extension interface in your core module and put it into the module's public packages. Imagine for example that the core module is in JAR file org-my-netbeans-coremodule.jar and already contains in manifests line like OpenIDE-Module: org.my.netbeans.coremodule/1 and wants to display various tips of the day provided by other modules and thus defines:

 

package org.my.netbeans.coremodule;

public interface TipsOfTheDayProvider {
    public String provideTipOfTheDay ();
}

And in its manifest adds line OpenIDE-Module-Public-Packages: org.my.netbeans.coremodule.* to specify that this package contains exported API and shall be accessible to other modules.

When the core module is about to display the tip of the day it can ask the system for all registered instances of the TipsOfTheDayProvider, randomly select one of them:


import java.util.Collection;
import java.util.Collections;
import org.openide.util.Lookup;

Lookup.Result result = Lookup.getDefault ().lookup (new Lookup.Template (TipsOfTheDayProvider.class));
Collection c = result.
allInstances ();
Collections.shuffle (c);
TipsOfTheDayProvider selected = (TipsOfTheDayProvider)c.iterator ().next ();

and then display the tip. Simple, trivial, just by the usage of Lookup interface once creates a registry that other modules can enhance. But such enhancing of course requires work on the other side. Each module that would like to register its TipsOfTheDayProvider needs to depend on the core module - add OpenIDE-Module-Module-Dependencies: org.my.netbeans.coremodule/1 into its manifest and write a class with its own implementation of the provider:


package org.my.netbeans.extramodule;

class ExtraTip implements TipsOfTheDayProvider {
    public String provideTipOfTheDay () {
        return "Do you know that in order to write extension point you should use Lookup?";
    }
}

Then, the only necessary thing is to register such class by using the J2SE standard into plain text file META-INF/services/org.my.netbeans.coremodule.TipsOfTheDayProvider in the module JAR containing just one line:

org.my.netbeans.extramodule.ExtraTip

and your modules are now ready to communicate using your own extension point.


How to use Window System?

Window System API is used to display and control application GUI: Main window, frames, components. There is a UI specification document.

General Use cases can be read on the external page. Here is a small howto for simple things that may be found useful:

How to create a '.settings' file for a TopComponent?

Either write it by hand (not that hard if you copy other file and tweak it to match your TC), or start the IDE, instantiate the TC somehow (You have a "Window->Show My TC", right? ), copy the file that gets created in $userdir/config/Windows2Local/Component and cleanup the serialdata section - replace it with proper "<instance class='..." /> tag.

How to make a TopComponentGroup?

Q: I'm trying to make a TopComponentGroup. I've just read http://ui.netbeans.org/docs/ui/ws/ws_spec.html#3.9 I want to make a group that uses the first invocation strategy. That is, I want the group to open/close when I activate a certain subclass of TopComponent. Say, for example, I have a FooTopComponent, and when it's active, I want to open a FooPropertySheetComponent, docked in a mode on the right-hand side. I know I have to:
  1. declare the group in the layer file (Windows2/Groups)
  2. have code for opening the group
  3. have code for closing the group
I think I do #2 in FooTopComponent.componentActivated() and #3 in FooTopComponent.componentDeactivated(). Is that right?

A:Yes it is correct way. You can check simple test module. First you must get TopComponentGroup instance using find method then call TopComponentGroup.open()/close(). Here is the code in your componentDeactivated method:
   protected void componentDeactivated ()
   {
       // close window group containing propsheet, but only if we're
       // selecting a different kind of TC in the same mode
       boolean closeGroup = true;
       Mode curMode = WindowManager.getDefault().findMode(this);
       TopComponent selected = curMode.getSelectedTopComponent();
       if (selected != null && selected instanceof FooTopComponent)
           closeGroup = false;
             if (closeGroup)
       {
           TopComponentGroup group = WindowManager.getDefault().findTopComponentGroup(TC_GROUP);
           if (group != null)
           {
               group.close();
           }
       }
   }