NetBeans Visual Library Tutorial

來源:互聯網
上載者:User
最近都在學寫netbeans的外掛程式,感覺這個例子比較好。現在翻譯後貼出來共用下。

例子簡介:從palette中選擇下列三個圖形中的任意一個,左鍵拖動到主面板上,並可進行適量縮放及修改圖形的ID。


建立Module

首先我們需要建立一個mudule工程和一個使用者window component。

  1. 選擇 檔案 > 建立項目. 在建立項目的嚮導中,左邊選擇NetBeans Modules,右邊選擇 Module.點擊下一步.在項目名處輸入ShapeSample 並設定儲存在本機上的位置。最後選擇Standalone Module and Set as Main Project.點擊下一步步.

  2. 在代碼名處輸入org.netbeans.shapesample,在模組顯示名處輸入 Shape Sample. 點擊完成.
  3. 右鍵點擊建立好的項目,選擇Properties, 點擊 Libraries,添加以下lib:
    • Visual Library API
    • Action APIs
    • Command Line Parsing API
    • Common Palette
    • Nodes API
    • Swing Layout Extensions integration
    • UI Utilities API
    • Utilities API
    • Windows System API

    點擊確定。

  4. 右鍵點擊該項目,選擇建立
    New > Other 並在NetBeans Module Development category 中選擇 Window Component . 點擊下一步. 在第一個下拉式清單中選擇 editor 並選擇 Open on Application Start. 點擊下一步.

  5. 在類名中輸入 Shape. 最好選擇一副16px×16px的圖片做表徵圖,以便識別和更加專業:)。 點擊完成.               這樣多個檔案將會被自動建立。其中有一個叫ShapeTopComponent. 開啟它後你將看到如下視圖:
  6. 右鍵點擊ShapeTopComponent的面板中心, 選擇Set Layout, 選咋 Border Layout.
建立Editor
  1. 選則ShapeTopComponent,從 Palette (Ctrl-Shift-8) 中途一個JScrollPane 到 TopComponent上. 選擇屬性中的名字,把它修改為shapePane.並在inspector面板中雙擊JScrollPane,把名字改為shapePane。
  2. 在包 org.netbeans.shapesample 中建立一個 GraphSceneImpl.java
    /*
    * This is just a exercise to hoe to use JTable.
    */
    package org.netbeans.shapesample;

    import java.awt.Graphics2D;
    import java.awt.Image;
    import java.awt.Point;
    import java.awt.Rectangle;
    import java.awt.datatransfer.DataFlavor;
    import java.awt.datatransfer.Transferable;
    import java.awt.datatransfer.UnsupportedFlavorException;
    import java.awt.geom.AffineTransform;
    import java.io.IOException;
    import javax.swing.JComponent;
    import org.netbeans.api.visual.action.AcceptProvider;
    import org.netbeans.api.visual.action.ActionFactory;
    import org.netbeans.api.visual.action.ConnectorState;
    import org.netbeans.api.visual.action.TextFieldInplaceEditor;
    import org.netbeans.api.visual.action.WidgetAction;
    import org.netbeans.api.visual.graph.GraphScene;
    import org.netbeans.api.visual.widget.LabelWidget;
    import org.netbeans.api.visual.widget.LayerWidget;
    import org.netbeans.api.visual.widget.Widget;
    import org.netbeans.api.visual.widget.general.IconNodeWidget;
    import org.netbeans.shapesample.palette.MyNode;
    import org.openide.util.Utilities;

    /**
    *
    * @author Vanessa <liyuan.li at Yunnan University>
    * @version 1.0.0.0
    */
    public class GraphSceneImpl extends GraphScene<MyNode, String> {

    private LayerWidget mainLayer;
    private WidgetAction editorAction = ActionFactory.createInplaceEditorAction(new LabelTextFieldEditor());

    private class LabelTextFieldEditor implements TextFieldInplaceEditor {

    public boolean isEnabled(Widget widget) {
    return true;
    }

    public String getText(Widget widget) {
    return ((LabelWidget) widget).getLabel();
    }

    public void setText(Widget widget, String text) {
    ((LabelWidget) widget).setLabel(text);
    }
    }

    public GraphSceneImpl() {
    mainLayer = new LayerWidget(this);
    addChild(mainLayer);
    getActions().addAction(ActionFactory.createAcceptAction(new AcceptProvider() {

    public ConnectorState isAcceptable(Widget widget, Point point, Transferable transferable) {
    Image dragImage = getImageFromTransferable(transferable);
    JComponent view = getView();
    Graphics2D g2 = (Graphics2D) view.getGraphics();
    Rectangle visRect = view.getVisibleRect();
    view.paintImmediately(visRect.x, visRect.y, visRect.width, visRect.height);
    g2.drawImage(dragImage,
    AffineTransform.getTranslateInstance(point.getLocation().getX(),
    point.getLocation().getY()),
    null);
    return ConnectorState.ACCEPT;
    }

    public void accept(Widget widget, Point point, Transferable transferable) {
    Image image = getImageFromTransferable(transferable);
    Widget w = GraphSceneImpl.this.addNode(new MyNode(image));
    w.setPreferredLocation(widget.convertLocalToScene(point));
    }
    }));

    getActions().addAction(ActionFactory.createZoomAction());
    getActions().addAction(ActionFactory.createPanAction());
    }

    private Image getImageFromTransferable(Transferable transferable) {
    Object o = null;
    try {
    o = transferable.getTransferData(DataFlavor.imageFlavor);
    } catch (IOException ex) {
    ex.printStackTrace();
    } catch (UnsupportedFlavorException ex) {
    ex.printStackTrace();
    }
    return o instanceof Image ? (Image) o : Utilities.loadImage("org/netbeans/shapesample/palette/shape1.png");
    }

    @Override
    protected Widget attachNodeWidget(MyNode node) {
    IconNodeWidget widget = new IconNodeWidget(this);
    widget.setImage(node.getImage());
    widget.setLabel(Long.toString(node.hashCode()));

    //double-click, the event is consumed while double-clicking only:
    widget.getLabelWidget().getActions().addAction(editorAction);

    //single-click, the event is not consumed:
    widget.getActions().addAction(createSelectAction());

    //mouse-dragged, the event is consumed while mouse is dragged:
    widget.getActions().addAction(ActionFactory.createMoveAction());

    //mouse-over, the event is consumed while the mouse is over the widget:
    widget.getActions().addAction(createObjectHoverAction());

    mainLayer.addChild(widget);
    return widget;
    }

    @Override
    protected Widget attachEdgeWidget(String edge) {
    throw new UnsupportedOperationException("Not supported yet.");
    }

    @Override
    protected void attachEdgeSourceAnchor(String edge, MyNode oldSourceNode, MyNode sourceNode) {
    throw new UnsupportedOperationException("Not supported yet.");
    }

    @Override
    protected void attachEdgeTargetAnchor(String edge, MyNode oldTargetNode, MyNode targetNode) {
    throw new UnsupportedOperationException("Not supported yet.");
    }
    }
    在紅線處右鍵選擇Fix Imports。
  3. 在ShapeTopComponent.java中修改 getPersistenceType()如下
public int getPersistenceType() {

return TopComponent.PERSISTENCE_NEVER;

}

建立 Component Palette
  1. 建立org.netbeans.shapesample.palette包,並在其中船艦一下類:

    • Category.java

    /*
     * Category.java
     *
     * Created on September 21, 2006, 9:00 PM
     *
     * To change this template, choose Tools | Template Manager
     * and open the template in the editor.
     *
     * To understand this class, see http://platform.netbeans.org/tutorials/nbm-nodesapi3.html
     */

    package org.netbeans.shapesample.palette;

    /**
     *
     * @author Geertjan Wielenga
     */

    public class Category {
       
        private String name;
       
        /** Creates a new instance of Category */
        public Category() {
        }
       
        public String getName() {
            return name;
        }
       
        public void setName(String name) {
            this.name = name;
        }
       
    }

    • CategoryChildren.java

    /*
     * CategoryChildren.java
     *
     * Created on September 21, 2006, 9:00 PM
     *
     * To change this template, choose Tools | Template Manager
     * and open the template in the editor.
     *
     * To understand this class, see http://platform.netbeans.org/tutorials/nbm-nodesapi3.html
     */

    package org.netbeans.shapesample.palette;

    import org.openide.nodes.Children;
    import org.openide.nodes.Node;

    /**
     *
     * @author Geertjan Wielenga
     */
    public class CategoryChildren extends Children.Keys {

        private String[] Categories = new String[]{
            "Shapes"};

        public CategoryChildren() {
        }

        protected Node[] createNodes(Object key) {
            Category obj = (Category) key;
            return new Node[] { new CategoryNode(obj) };
        }

        protected void addNotify() {
            super.addNotify();
            Category[] objs = new Category[Categories.length];
            for (int i = 0; i < objs.length; i++) {
                Category cat = new Category();
                cat.setName(Categories[i]);
                objs[i] = cat;
            }
            setKeys(objs);
        }

    }

    • CategoryNode.java

    /*
     * CategoryNode.java
     *
     * Created on September 21, 2006, 9:02 PM
     *
     * To change this template, choose Tools | Template Manager
     * and open the template in the editor.
     *
     * To understand this class, see http://platform.netbeans.org/tutorials/nbm-nodesapi3.html
     */

    package org.netbeans.shapesample.palette;

    import org.openide.nodes.AbstractNode;
    import org.openide.util.lookup.Lookups;

    /**
     *
     * @author Geertjan Wielenga
     */
    public class CategoryNode extends AbstractNode {

        /** Creates a new instance of CategoryNode */
        public CategoryNode( Category category ) {
            super( new ShapeChildren(category), Lookups.singleton(category) );
            setDisplayName(category.getName());
        }
    }

    • PaletteSupport.java

    /*
     * PaletteSupport.java
     *
     * Created on September 25, 2006, 2:22 PM
     *
     * To change this template, choose Tools | Template Manager
     * and open the template in the editor.
     *
     * To understand this class, see http://platform.netbeans.org/tutorials/nbm-nodesapi3.html
     */

    package org.netbeans.shapesample.palette;

    import java.awt.Image;
    import java.awt.datatransfer.DataFlavor;
    import java.awt.datatransfer.UnsupportedFlavorException;
    import java.beans.BeanInfo;
    import java.io.IOException;
    import javax.swing.Action;
    import org.netbeans.spi.palette.DragAndDropHandler;
    import org.netbeans.spi.palette.PaletteActions;
    import org.netbeans.spi.palette.PaletteController;
    import org.netbeans.spi.palette.PaletteFactory;
    import org.openide.nodes.AbstractNode;
    import org.openide.nodes.Node;
    import org.openide.util.Lookup;
    import org.openide.util.datatransfer.ExTransferable;

    /**
     *
     * @author dave
     */
    public class PaletteSupport {
       
        public static PaletteController createPalette() {
            AbstractNode paletteRoot = new AbstractNode(new CategoryChildren());
            paletteRoot.setName("Palette Root");
            return PaletteFactory.createPalette( paletteRoot, new MyActions(), null, new MyDnDHandler() );
        }
       
        private static class MyActions extends PaletteActions {
            public Action[] getImportActions() {
                return null;
            }
           
            public Action[] getCustomPaletteActions() {
                return null;
            }
           
            public Action[] getCustomCategoryActions(Lookup lookup) {
                return null;
            }
           
            public Action[] getCustomItemActions(Lookup lookup) {
                return null;
            }
           
            public Action getPreferredAction(Lookup lookup) {
                return null;
            }
           
        }
       
        private static class MyDnDHandler extends DragAndDropHandler {

            public void customize(ExTransferable exTransferable, Lookup lookup) {
                Node node = lookup.lookup(Node.class);
                final Image image = (Image) node.getIcon(BeanInfo.ICON_COLOR_16x16);
                exTransferable.put(new ExTransferable.Single (DataFlavor.imageFlavor) {
                   
                    protected Object getData() throws IOException, UnsupportedFlavorException {
                        return image;
                    }
                   
                });
            }
           
        }

    }

    • Shape.java

    /*
     * Shape.java
     *
     * Created on September 21, 2006, 9:09 PM
     *
     * To change this template, choose Tools | Template Manager
     * and open the template in the editor.
     *
     * To understand this class, see http://platform.netbeans.org/tutorials/nbm-nodesapi3.html
     */

    package org.netbeans.shapesample.palette;

    /**
     *
     * @author Geertjan Wielenga
     */
    public class Shape {

        private Integer number;
        private String category;
        private String title;
        private String image;

        /** Creates a new instance of Instrument */
        public Shape() {
        }

        public Integer getNumber() {
            return number;
        }

        public void setNumber(Integer number) {
            this.number = number;
        }

        public String getCategory() {
            return category;
        }

        public void setCategory(String category) {
            this.category = category;
        }

        public String getImage() {
            return image;
        }

        public void setImage(String image) {
            this.image = image;
        }

    }

    • ShapeChildren.java

    /*
     * ShapeChildren.java
     *
     * Created on September 21, 2006, 9:10 PM
     *
     * To change this template, choose Tools | Template Manager
     * and open the template in the editor.
     *
     * To understand this class, see http://platform.netbeans.org/tutorials/nbm-nodesapi3.html
     */

    package org.netbeans.shapesample.palette;

    import java.util.ArrayList;
    import org.openide.nodes.Index;
    import org.openide.nodes.Node;

    /**
     *
     * @author Geertjan Wielenga
     */
    public class ShapeChildren  extends Index.ArrayChildren {

        private Category category;

        private String[][] items = new String[][]{
            {"0", "Shapes", "org/netbeans/shapesample/palette/image1.png"},
            {"1", "Shapes", "org/netbeans/shapesample/palette/image2.png"},
            {"2", "Shapes", "org/netbeans/shapesample/palette/image3.png"},
        };

        public ShapeChildren(Category Category) {
            this.category = Category;
        }

        protected java.util.List<Node> initCollection() {
            ArrayList childrenNodes = new ArrayList( items.length );
            for( int i=0; i<items.length; i++ ) {
                if( category.getName().equals( items[i][1] ) ) {
                    Shape item = new Shape();
                    item.setNumber(new Integer(items[i][0]));
                    item.setCategory(items[i][1]);
                    item.setImage(items[i][2]);
                    childrenNodes.add( new ShapeNode( item ) );
                }
            }
            return childrenNodes;
        }

    }

    • MyNode.java

    /*
     * This is just a exercise to hoe to use JTable.
     */

    package org.netbeans.shapesample.palette;

    import java.awt.Image;

    /**
     *
     * @author Vanessa <liyuan.li at Yunnan University>
     * @version 1.0.0.0
     */
    public class MyNode {
       
        private Image image;
       
        public MyNode(Image image) {
            this.image = image;
        }
       
        public Image getImage() {
            return image;
        }
    }

    • ShapeNode.java

    /*
     * ShapeNode.java
     *
     * Created on September 21, 2006, 9:18 PM
     *
     * To change this template, choose Tools | Template Manager
     * and open the template in the editor.
     *
     * To understand this class, see http://platform.netbeans.org/tutorials/nbm-nodesapi3.html
     */

    package org.netbeans.shapesample.palette;

    import org.openide.nodes.AbstractNode;
    import org.openide.nodes.Children;
    import org.openide.util.lookup.Lookups;

    /**
     *
     * @author Geertjan Wielenga
     */
    public class ShapeNode extends AbstractNode {
       
        private Shape shape;
       
        /** Creates a new instance of InstrumentNode */
        public ShapeNode(Shape key) {
            super(Children.LEAF, Lookups.fixed( new Object[] {key} ) );
            this.shape = key;
            setIconBaseWithExtension(key.getImage());
        }
       
    }

  2. 在ShapeTopComponent.java的構造器中添加如下代碼:
    associateLookup( Lookups.fixed( new Object[] { PaletteSupport.createPalette() } ) );
  3. 項目結構如下。

樣本示範:


  1. CTRL+滑鼠滾輪

修改ID

備忘:

1。以上是總結後的簡略方法,原文參見http://platform.netbeans.org/tutorials/60/nbm-visual_library.html

從原文中可以體會到每部分代碼的作用。從而對netbeans platform有更加深刻的認識。

2.有紅線的地方請使用右鍵 選擇Fix Imports。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.