Search Results

Search found 227 results on 10 pages for 'geertjan'.

Page 5/10 | < Previous Page | 1 2 3 4 5 6 7 8 9 10  | Next Page >

  • Getting Started Plugging into the "Find in Projects" Dialog

    - by Geertjan
    In case you missed it amidst all the code in yesterday's blog entry, the "Find in Projects" dialog is now pluggable. I think that's really cool. The code yesterday gives you a complete example, but let's break it down a bit and deconstruct down to a very simple hello world scenario. We'll end up with as many extra tabs in the "Find in Projects" dialog as we need, for example, three in this case:  And clicking on any of those extra tabs will, in this simple example, simply show us this: Once we have that, we'll be able to continue adding small bits of code over the next few blog entries until we have something more useful. So, in this blog entry, you'll literally be able to display "Hello World" within a new tab in the "Find in Projects" dialog: import javax.swing.JComponent; import javax.swing.JLabel; import org.netbeans.spi.search.provider.SearchComposition; import org.netbeans.spi.search.provider.SearchProvider; import org.netbeans.spi.search.provider.SearchProvider.Presenter; import org.openide.NotificationLineSupport; import org.openide.util.lookup.ServiceProvider; @ServiceProvider(service = SearchProvider.class) public class ExampleSearchProvider1 extends SearchProvider { @Override public Presenter createPresenter(boolean replaceMode) { return new ExampleSearchPresenter(this); } @Override public boolean isReplaceSupported() { return false; } @Override public boolean isEnabled() { return true; } @Override public String getTitle() { return "Demo Extension 1"; } public class ExampleSearchPresenter extends SearchProvider.Presenter { private ExampleSearchPresenter(ExampleSearchProvider1 sp) { super(sp, true); } @Override public JComponent getForm() { return new JLabel("Hello World"); } @Override public SearchComposition composeSearch() { return null; } @Override public boolean isUsable(NotificationLineSupport nls) { return true; } } } That's it, not much code, works fine in NetBeans IDE 7.2 Beta, and is easier to digest than the big chunk from yesterday. If you make three classes like the above in a NetBeans module, and you install it, you'll have three new tabs in the "Find in Projects" dialog. The only required dependencies are Dialogs API, Lookup API, and Search in Projects API. Read the javadoc linked above and then in next blog entries we'll continue to build out something like the sample you saw in yesterday's blog entry.

    Read the article

  • Sources of NetBeans Gradle Plugin

    - by Geertjan
    Here is where you can find the sources of the latest and greatest NetBeans Gradle plugin: http://java.net/projects/nb-api-samples/sources/api-samples/show/versions/7.1/misc/GradleSupport To use it, download the sources above, open the sources into the IDE (which must be 7.1.1 or above), then you'll have a NetBeans module. Right-click it to run the module into a new instance of NetBeans IDE. In the Options window's Miscellaneous tab, there's a Gradle subtab for setting the Gradle location. In the New File dialog, in the Other category, you'll find a template named "Empty Gradle file". Make sure to name it "build" and to put it in the root directory of the application (by leaving the Folder field empty, you're specifying it should be created in the root directory). You'll then be able to expand the build.gradle file: Double-click a task to run it. When you open the file, it opens in the Groovy editor, if the Groovy editor is installed. When you make changes in the file, the list of tasks, shown above, is automatically recreated. It's at a really early stage of development and it would be great if developers out there would be interested in adding more features to it.

    Read the article

  • BeanInfo Editor in NetBeans Rocks

    - by Geertjan
    Impressed by a cool feature I didn't know about. If you have some JavaBean, like my Event class below, you can right-click it and choose "BeanInfo Editor": Now, as you can see above, I don't have a BeanInfo class. So I am now asked whether the IDE should create one for me. So I say OK and then I have a new BeanInfo class, generated from my Event class, as well as a multiview editor for visually editing the BeanInfo class: Thanks Eric and Nicklas from Artificial Solutions in Stockholm for pointing this out to me today. It comes in very handy in NetBeans Platform applications when you're working with a BeanNode and want to customize the display of your properties.

    Read the article

  • What is Happening vs. What is Interesting

    - by Geertjan
    Devoxx 2011 was yet another confirmation that all development everywhere is either on the web or on mobile phones. Whether you looked at the conference schedule or attended sessions or talked to speakers at any point at all, it was very clear that no development whatsoever is done anymore on the desktop. In fact, that's something Tim Bray himself told me to my face at the speakers dinner. No new developments of any kind are happening on the desktop. Everyone who is currently on the desktop is working overtime to move all of their applications to the web. They're probably also creating a small subset of their application on an Android tablet, with an even smaller subset on their Android phone. Then you scratch that monolithic surface and find some interesting results. Without naming any names, I asked one of these prominent "ah, forget about the desktop" people at the Devoxx speakers dinner (and I have a witness): "Yes, the desktop is dead, but what about air traffic control, stock trading, oil analysis, risk management applications? In fact, what about any back office application that needs to be usable across all operating systems? Here there is no concern whatsoever with 100% accessibility which is, after all, the only thing that the web has over the desktop, (except when there's a network failure, of course, or when you find yourself in the 3/4 of the world where there's bandwidth problems)? There are 1000's of hidden applications out there that have processing requirements, security requirements, and the requirement that they'll be available even when the network is down or even completely unavailable. Isn't that a valid use case and aren't there 1000's of applications that fall into this so-called niche category? Are you not, in fact, confusing consumer applications, which are increasingly web-based and mobile-based, with high-end corporate applications, which typically need to do massive processing, of one kind or another, for which the web and mobile worlds are completely unsuited?" And you will not believe what the reply to the above question was. (Again, I have a witness to this discussion.) But here it is: "Yes. But those applications are not interesting. I do not want to spend any of my time or work in any way on those applications. They are boring." I'm sad to say that the leaders of the software development community, including those in the Java world, either share the above opinion or are led by it. Because they find something that is not new to be boring, they move on to what is interesting and start talking like the supposedly-boring developments don't even exist. (Kind of like a rapper pretending classical music doesn't exist.) Time and time again I find myself giving Java desktop development courses (at companies, i.e., not hobbyists, or students, but companies, i.e., the places where dollars are earned), where developers say to me: "The course you're giving about creating cross-platform, loosely coupled, and highly cohesive applications is really useful to us. Why do we never find information about this topic at conferences? Why can we never attend a session at a conference where the story about pluggable cross-platform Java is told? Why do we get the impression that we are uncool because we're not on the web and because we're not on a mobile phone, while the reason for that is because we're creating $1000,000 simulation software which has nothing to gain from being on the web or on the mobile phone?" And then I say: "Because nobody knows you exist. Because you're not submitting abstracts to conferences about your very interesting use cases. And because conferences tend to focus on what is new, which tends to be web related (especially HTML 5) or mobile related (especially Android). Because you're not taking the responsibility on yourself to tell the real stories about the real applications being developed all the time and every day. Because you yourself think your work is boring, while in fact it is fascinating. Because desktop developers are working from 9 to 5 on the desktop, in secure environments, such as banks and defense, where you can't spend time, nor have the interest in, blogging your latest tip or trick, as opposed to web developers, who tend to spend a lot of time on the web anyway and are therefore much more inclined to create buzz about the kind of work they're doing." So, next time you look at a conference program and wonder why there's no stories about large desktop development projects in the program, here's the short answer: "No one is going to put those items on the program until you start submitting those kinds of sessions. And until you start blogging. Until you start creating the buzz that the web developers have been creating around their work for the past 10 years or so. And, yes, indeed, programmers get the conference they deserve." And what about Tim Bray? Ask yourself, as Google's lead web technology evangelist, how many desktop developers do you think he talks to and, more generally, what his frame of reference is and what, clearly, he considers to be most interesting.

    Read the article

  • YouTube: CoffeeScript Rocks (in NetBeans IDE)

    - by Geertjan
    CoffeeScript is a handy preprocessor for JavaScript, as shown in a quick demo below on YouTube, using the CoffeeScript plugin for NetBeans IDE. Right now, the NetBeans Plugin Portal doesn't have a CoffeeScript plugin for NetBeans IDE 7.4, but not to worry, the NetBeans IDE 7.3 plugin works just fine. http://plugins.netbeans.org/plugin/39007/coffeescript-netbeans Here's a small YouTube clip I made today showing how it all works: Also read this very handy and detailed NetBeans tutorial, on which I based the demo above: https://netbeans.org/kb/docs/web/js-toolkits-jquery.html Related info: http://www.youtube.com/watch?v=QgqVh_KpVKY http://www.ibm.com/developerworks/library/wa-coffee1/ http://blog.sethladd.com/2012/01/vanilla-dart-ftw.html http://api.jquery.com/fadeOut/

    Read the article

  • Getting Started with Amazon Web Services in NetBeans IDE

    - by Geertjan
    When you need to connect to Amazon Web Services, NetBeans IDE gives you a nice start. You can drag and drop the "itemSearch" service into a Java source file and then various Amazon files are generated for you. From there, you need to do a little bit of work because the request to Amazon needs to be signed before it can be used. Here are some references and places that got me started: http://associates-amazon.s3.amazonaws.com/signed-requests/helper/index.html http://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSGettingStartedGuide/AWSCredentials.html https://affiliate-program.amazon.com/gp/flex/advertising/api/sign-in.html You definitely need to sign up to the Amazon Associates program and also register/create an Access Key ID, which will also get you a Secret Key, as well. Here's a simple Main class that I created that hooks into the generated RestConnection/RestResponse code created by NetBeans IDE: public static void main(String[] args) {    try {        String searchIndex = "Books";        String keywords = "Romeo and Juliet";        RestResponse result = AmazonAssociatesService.itemSearch(searchIndex, keywords);        String dataAsString = result.getDataAsString();        int start = dataAsString.indexOf("<Author>")+8;        int end = dataAsString.indexOf("</Author>");        System.out.println(dataAsString.substring(start,end));    } catch (Exception ex) {        ex.printStackTrace();    }} Then I deleted the generated properties file and the authenticator and changed the generated AmazonAssociatesService.java file to the following: public class AmazonAssociatesService {    private static void sleep(long millis) {        try {            Thread.sleep(millis);        } catch (Throwable th) {        }    }    public static RestResponse itemSearch(String searchIndex, String keywords) throws IOException {        SignedRequestsHelper helper;        RestConnection conn = null;        Map queryMap = new HashMap();        queryMap.put("Service", "AWSECommerceService");        queryMap.put("AssociateTag", "myAssociateTag");        queryMap.put("AWSAccessKeyId", "myAccessKeyId");        queryMap.put("Operation", "ItemSearch");        queryMap.put("SearchIndex", searchIndex);        queryMap.put("Keywords", keywords);        try {            helper = SignedRequestsHelper.getInstance(                    "ecs.amazonaws.com",                    "myAccessKeyId",                    "mySecretKey");            String sign = helper.sign(queryMap);            conn = new RestConnection(sign);        } catch (IllegalArgumentException | UnsupportedEncodingException | NoSuchAlgorithmException | InvalidKeyException ex) {        }        sleep(1000);        return conn.get(null);    }} Finally, I copied this class into my application, which you can see is referred to above: http://code.google.com/p/amazon-product-advertising-api-sample/source/browse/src/com/amazon/advertising/api/sample/SignedRequestsHelper.java Here's the completed app, mostly generated via the drag/drop shown at the start, but slightly edited as shown above: That's all, now everything works as you'd expect.

    Read the article

  • Integrating a Progress Bar into a Wizard

    - by Geertjan
    Normally, when you create a wizard, as described here, and you have your own iterator, you'll have a class signature like this: public final class MyWizardWizardIterator implements WizardDescriptor.InstantiatingIterator<WizardDescriptor> { Let's now imagine that you've got some kind of long running process your wizard needs to perform. Maybe the wizard needs to connect to something, which could take some time. Start by adding a new dependency on the Progress API, which gives you the classes that access the NetBeans Platform's progress functionality. Now all we need to do is change the class signature very slightly: public final class MyWizardWizardIterator implements WizardDescriptor.ProgressInstantiatingIterator<WizardDescriptor> { Take a look at the part of the signature above that is highlighted. I.e., use WizardDescriptor.ProgressInstantiatingIterator instead of WizardDescriptor.InstantiatingIterator. Now you will need to implement a new instantiate method, one that receives a ProgressHandle. The other instantiate method, i.e., the one that already existed, should never be accessed anymore, and so you can add an assert to that effect: @Override public Set<?> instantiate() throws IOException {     throw new AssertionError("instantiate(ProgressHandle) " //NOI18N             + "should have been called"); //NOI18N } @Override public Set instantiate(ProgressHandle ph) throws IOException {     return Collections.emptySet(); } OK. Let's now add some code to make our progress bar work: @Override public Set instantiate(ProgressHandle ph) throws IOException {     ph.start();     ph.progress("Processing...");     try {         //Simulate some long process:         Thread.sleep(2500);     } catch (InterruptedException ex) {         Exceptions.printStackTrace(ex);     }     ph.finish();     return Collections.emptySet(); } And, maybe even more impressive, you can also do this: @Override public Set instantiate(ProgressHandle ph) throws IOException {     ph.start(1000);     ph.progress("Processing...");     try {         //Simulate some long process:         ph.progress("1/4 complete...", 250);         Thread.sleep(2500);         ph.progress("1/2 complete...", 500);         Thread.sleep(5000);         ph.progress("3/4 complete...", 750);         Thread.sleep(7500);         ph.progress("Complete...", 1000);         Thread.sleep(1000);     } catch (InterruptedException ex) {         Exceptions.printStackTrace(ex);     }     ph.finish();     return Collections.emptySet(); } The screenshots above show you what you should see when the Finish button is clicked in each case.

    Read the article

  • UNESCO, J-ISIS, and the JavaFX 2.2 WebView

    - by Geertjan
    J-ISIS, which is the newly developed Java version of the UNESCO generalized information storage and retrieval system for bibliographic information, continues to be under heavy development and code refactoring in its open source repository. Read more about J-ISIS and its NetBeans Platform basis here. Soon a new version will be available for testing and it would be cool to see the application in action at that time. Currently, it looks as follows, though note that the menu bar is under development and many menus you see there will be replaced or removed soon: About one aspect of the application, the browser, which you can see above, Jean-Claude Dauphin, its project lead, wrote me the following: The DJ-Native Swing JWebBrowser has been a nice solution for getting a Java Web Browser for most popular platforms. But the Java integration has always produced from time to time some strange behavior (like losing the focus on the other components after clicking on the Browser window, overlapping of windows, etc.), most probably because of mixing heavyweight and lightweight components and also because of our incompetency in solving the issues. Thus, recently we changed for the JavaFX 2.2 WebWiew. The integration with Java is fine and we have got rid of all the DJ-Native Swing problems. However, we have lost some features which were given for free with the native browsers such as downloading resources in different formats and opening them in the right application. This is a pretty cool step forward, i.e., the JavaFX integration. It also confirms for me something I've heard other people saying too: the JavaFX WebView component is a perfect low threshold entry point for Swing developers feeling their way into the world of JavaFX.

    Read the article

  • Live Updates in PrimeFaces Line Chart

    - by Geertjan
    In the Facelets file: <p:layoutUnit position="center"> <h:form> <p:poll interval="3" update=":chartPanel" autoStart="true" /> </h:form> <p:panelGrid columns="1" id="chartPanel"> <p:lineChart xaxisLabel="Time" yaxisLabel="Position" value="#{chartController.linearModel}" legendPosition="nw" animate="true" style="height:400px;width: 1000px;"/> </p:panelGrid> </p:layoutUnit> The controler: import java.io.Serializable; import javax.inject.Named; import org.primefaces.model.chart.CartesianChartModel; import org.primefaces.model.chart.ChartSeries; @Named public class ChartController implements Serializable { private CartesianChartModel model; private ChartSeries data; public ChartController() { createLinearModel(); } private void createLinearModel() { model = new CartesianChartModel(); model.addSeries(getStockChartData("Stock Chart")); } private ChartSeries getStockChartData(String label) { data = new ChartSeries(); data.setLabel(label); for (int i = 1; i <= 20; i++) { data.getData().put(i, (int) (Math.random() * 1000)); } return data; } public CartesianChartModel getLinearModel() { return model; } } Based on this sample.

    Read the article

  • Schema Based Code Completion for NetBeans Platform Applications

    - by Geertjan
    Toni's recent blog entry provides, among several other interesting things, instructions for something I've been wanting to cover for a long time, which is schema based code completion: The above is a sample I created via Toni's tutorial, using the schema described here: http://www.w3schools.com/schema/schema_example.asp The support for the Navigator ain't bad either, especially considering I didn't do any coding at all to get all this: And here's where you can find the whole sample: http://java.net/projects/nb-api-samples/sources/api-samples/show/versions/7.2/misc/ShipOrder

    Read the article

  • Viewing the NetBeans Central Registry

    - by Geertjan
    For some fun, create a TopComponent and then add this bit of code, with thanks to Toni Epple: add(new BeanTreeView(), BorderLayout.CENTER); try { myExplorerManager.setRootContext(DataObject.find(FileUtil.getConfigRoot()).getNodeDelegate()); } catch (DataObjectNotFoundException ex) { Exceptions.printStackTrace(ex); } Run the application and you'll see the NetBeans Central Registry a.k.a. System FileSystem) of the application you're running.

    Read the article

  • Jaroslav Tulach's Report on NetBeans at OSGiCon

    - by Geertjan
    The latest NetBeans Podcast was recorded over the last few weeks and released yesterday. Aside from the NetBeans news items and interviews (interesting stuff about Joel Murach's new Java book using NetBeans, as well as the new developments in the NetBeans Groovy editor), there is, as always an "API Design Tip" of the podcast. That's really worth listening to, always of course, but especially this time because here Jaroslav Tulach talks at some length about his recent trip to OSGiCon, as well as the history and status of OSGi support in NetBeans IDE. Start listening from just before the 30th minute (i.e., the final segment) if you're interested in this particular topic: https://blogs.oracle.com/nbpodcast/entry/netbeans_podcast_60 For example, hear about how JDeveloper got faster by switching from Equinox to Netbinox. And... will Eclipse find itself on the same OSGi container too?

    Read the article

  • Gradle/NetBeans

    - by Geertjan
    The Gradle team (thanks Szczepan and others) fixed a crucial bug impacting, at least, NetBeans IDE and so now the Gradle/NetBeans plugin is coming along OK. Click to enlarge the screenshot and notice the dependencies and Gradle targets shown in the left side of the screenshot and the Groovy editor on the right hand side: Still lots of work to do, especially would like to have a Gradle file for NetBeans RCP projects, which Hans Dockter from the Gradle team is helping me with.

    Read the article

  • Where I'll Be At JavaOne 2012

    - by Geertjan
    Fun and games for me at JavaOne 2012. Below are the sessions/BOFs/tutorials I'll be attending. The items in red are the sessions and BOFs where I'll be speaking, either as the main/only speaker or as a supporting speaker in someone else's presentation, while the other items (except for the NetBeans booth duties and mini presentations, which are included below) are items I'm interested in and so will be sitting in the audience: Sunday: NetBeans Day Monday: 10:00 - 12:00 TUT4801: Make Your Clients Richer: JavaFX and the NetBeans Platform 12:20 - 12:30 Mini Presentation in OTN Lounge: What's New in NetBeans IDE? 13:00 - 14:00 CON7050: How My Life Would Have Been So Much Better If We Had Used the NetBeans Platform 14:30 - 14:40 Mini Presentation in OTN Lounge: NetBeans and Java EE 15:00 - 16:00 CON4038: Project EASEL: Developing and Managing HTML5 in a Java World 16:30 - 17:15 BOF6151: NetBeans.Next: The Roadmap Ahead 17:30 - 18:15 BOF3332: Lessons Learned in Writing a PDF-to-JavaFX Converter for NetBeans 18:30 - 19:15 BOF4920: Runtime Class Reloading for Dummies Tuesday: 9:30 - 11:30 NetBeans Booth 11:30 - 12:30 CON6139: Lessons Learned in Building Enterprise and Desktop Applications with the NetBeans IDE 13:00 - 14:00 CON4387: Bringing Mylyn to NetBeans and OSGi, Bridging Their Worlds 14:30 - 14:40 Mini Presentation in OTN Lounge: NetBeans Java Editor 15:30 - 17:30 NetBeans Booth 17:30 - 18:15 BOF3665: Custom Static Code Analysis 18:30 - 19:15 BOF5806: Doing JSF Development in the NetBeans IDE  Wednesday: 8:30 - 9:30 CON5132: NetBeans Plug-in Development: JRebel Experience Report 10:00 - 11:00 CON2987: Unlocking the Java EE 6 Platform 11:30 - 12:30 CON10140: Delivering Bug-Free, More Efficient Code for the Java Platform 13:00 - 14:00 CON3826: Patterns for Modularity: What Modules Don’t Want You to Know 14:30 - 14:40 Mini Presentation in OTN Lounge: NetBeans Platform 15:00 - 16:00 CON3160: Dynamic Class Reloading in the Wild with Javeleon Thursday: 12:30 - 13:30 CON4952: NetBeans Platform Panel Discussion 14:00 - 15:00 CON11879: Getting Started with the NetBeans Platform There are several sessions/BOFs I would have liked to be able to attend, but because of clashes with other sessions that I need to see slightly more urgently, I won't be able to attend those, unfortunately. Will be a busy but interesting time, as always! The entire list of NetBeans-oriented sessions can be found here: http://netbeans.org/community/articles/javaone/2012/index.html

    Read the article

  • Rotating a NetBeans Visual Library Widget

    - by Geertjan
    Trying to create a widget which, when clicked, rotates slightly further on each subsequent click: Above, the bird where the mouse is visible has been clicked a few times and so has rotated a bit further on each click. The code isn't quite right yet and I'm hoping someone will take this code, try it out, and help with a nice solution! public class BirdScene extends Scene {     public BirdScene() {         addChild(new LayerWidget(this));         getActions().addAction(ActionFactory.createAcceptAction(new AcceptProvider() {             public ConnectorState isAcceptable(Widget widget, Point point, Transferable transferable) {                 Image dragImage = getImageFromTransferable(transferable);                 if (dragImage != null) {                     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;                 } else {                     return ConnectorState.REJECT;                 }             }             public void accept(Widget widget, final Point point, Transferable transferable) {                 addChild(new BirdWidget(getScene(), getImageFromTransferable(transferable), point));             }         }));     }     private Image getImageFromTransferable(Transferable transferable) {         Object o = null;         try {             o = transferable.getTransferData(DataFlavor.imageFlavor);         } catch (IOException ex) {         } catch (UnsupportedFlavorException ex) {         }         return o instanceof Image ? (Image) o : null;     }     private class BirdWidget extends IconNodeWidget {         private int theta = 0;         public BirdWidget(Scene scene, Image imageFromTransferable, Point point) {             super(scene);             setImage(imageFromTransferable);             setPreferredLocation(point);             setCheckClipping(true);             getActions().addAction(ActionFactory.createMoveAction());             getActions().addAction(ActionFactory.createSelectAction(new SelectProvider() {                 public boolean isAimingAllowed(Widget widget, Point localLocation, boolean invertSelection) {                     return true;                 }                 public boolean isSelectionAllowed(Widget widget, Point localLocation, boolean invertSelection) {                     return true;                 }                 public void select(final Widget widget, Point localLocation, boolean invertSelection) {                     theta = (theta + 100) % 360;                     repaint();                     getScene().validate();                 }             }));         }         @Override         public void paintWidget() {             final Image image = getImageWidget().getImage();             Graphics2D g = getGraphics();             g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);             Rectangle bounds = getClientArea();             AffineTransform newXform = g.getTransform();             int xRot = image.getWidth(null) / 2;             int yRot = image.getWidth(null) / 2;             newXform.rotate(theta * Math.PI / 180, xRot, yRot);             g.setTransform(newXform);             g.drawImage(image, bounds.x, bounds.y, null);         }     } } The problem relates to refreshing the scene after the rotation. But it would help if someone would just take the code above, add it to their own application, try it out, see the problem for yourself, and develop it a bit further!

    Read the article

  • Eclipse Java Code Formatter in NetBeans Plugin Manager

    - by Geertjan
    Great news for Eclipse refugees everywhere. Benno Markiewicz forked the Eclipse formatter plugin that I blogged about sometime ago (here and here)... and he fixed many bugs, while also adding new features. It's a handy plugin when you're (a) switching from Eclipse to NetBeans and want to continue using your old formatting rules and (b) working in a polyglot IDE team, i.e., now the formatting rules defined in Eclipse can be imported into NetBeans IDE and everyone will happily be able to conform to the same set of formatting standards. And now you can get it directly from Tools | Plugins in NetBeans IDE 7.4: News from Benno on the plugin, received from him today: The plugin is verified by the NetBeans community and available in the Plugin Manager in NetBeans IDE 7.4 (as shown above) and also at the NetBeans Plugin Portal here, where you can also read quite some info about the plugin:  http://plugins.netbeans.org/plugin/50877/eclipse-code-formatter-for-java The issue with empty undo buffer was solved with the help of junichi11: https://github.com/markiewb/eclipsecodeformatter_for_netbeans/issues/18 The issue with the lost breakpoints remains unsolved and there was no further feedback. That is the main reason why the save action isn't activated by default. See also the open known issues at https://github.com/markiewb/eclipsecodeformatter_for_netbeans/issues?state=open Features are as follows:  Global configuration and project specific configuration.  On save action, which is disabled by default. Show the used formatter as a notification, which is enabled by default.  Finally, Benno testifies to the usefulness, stability, and reliability of the plugin: I use the Eclipse formatter provided by this plugin every day at work. Before I commit, I format the sources. It works and that's it. I am pleased with it. Here's where the Eclipse formatter is defined globally in Tools | Options: And here is per-project configuration, i.e., use the Project Properties dialog of any project to override the global settings:  Interested to hear from anyone who tries the plugin and has any feedback of any kind! 

    Read the article

  • Even More Steroids for JEditorPane

    - by Geertjan
    Got some help from Ralph today and now the JEditorPane is as I want it, e.g., code folds are now supported once you click in the JEditorPane, though there are still some side effects, since this is not how anyone anticipated NetBeans editor APIs being used. But, so far, the side effects (e.g., now the hyperlinks work, but they open a new JavaScript file when you click on one of them, instead of jumping within the JEditorPane itself) are not so terrible. Error checking is also done now, which wasn't there before, i.e., red underlines and error annotations in the right margin. And maybe it's my imagination, but the editor feels a lot snappier, e.g., in code completion, than before. I've checked in the changes, they're all in this file: http://java.net/projects/nb-api-samples/sources/api-samples/content/versions/7.3/misc/CMSBackOffice2/CMSBackOffice2-editor/src/main/java/com/mycompany/cmsbackoffice2editor/GeneralTab.java

    Read the article

  • Annotation Processor for Superclass Sensitive Actions

    - by Geertjan
    Someone creating superclass sensitive actions should need to specify only the following things: The condition under which the popup menu item should be available, i.e., the condition under which the action is relevant. And, for superclass sensitive actions, the condition is the name of a superclass. I.e., if I'm creating an action that should only be invokable if the class implements "org.openide.windows.TopComponent",  then that fully qualified name is the condition. The position in the list of Java class popup menus where the new menu item should be found, relative to the existing menu items. The display name. The path to the action folder where the new action is registered in the Central Registry. The code that should be executed when the action is invoked. In other words, the code for the enablement (which, in this case, means the visibility of the popup menu item when you right-click on the Java class) should be handled generically, under the hood, and not every time all over again in each action that needs this special kind of enablement. So, here's the usage of my newly created @SuperclassBasedActionAnnotation, where you should note that the DataObject must be in the Lookup, since the action will only be available to be invoked when you right-click on a Java source file (i.e., text/x-java) in an explorer view: import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import org.netbeans.sbas.annotations.SuperclassBasedActionAnnotation; import org.openide.awt.StatusDisplayer; import org.openide.loaders.DataObject; import org.openide.util.NbBundle; import org.openide.util.Utilities; @SuperclassBasedActionAnnotation( position=30, displayName="#CTL_BrandTopComponentAction", path="File", type="org.openide.windows.TopComponent") @NbBundle.Messages("CTL_BrandTopComponentAction=Brand") public class BrandTopComponentAction implements ActionListener { private final DataObject context; public BrandTopComponentAction() { context = Utilities.actionsGlobalContext().lookup(DataObject.class); } @Override public void actionPerformed(ActionEvent ev) { String message = context.getPrimaryFile().getPath(); StatusDisplayer.getDefault().setStatusText(message); } } That implies I've created (in a separate module to where it is used) a new annotation. Here's the definition: package org.netbeans.sbas.annotations; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; @Retention(RetentionPolicy.SOURCE) @Target(ElementType.TYPE) public @interface SuperclassBasedActionAnnotation { String type(); String path(); int position(); String displayName(); } And here's the processor: package org.netbeans.sbas.annotations; import java.util.Set; import javax.annotation.processing.Processor; import javax.annotation.processing.RoundEnvironment; import javax.annotation.processing.SupportedAnnotationTypes; import javax.annotation.processing.SupportedSourceVersion; import javax.lang.model.SourceVersion; import javax.lang.model.element.Element; import javax.lang.model.element.TypeElement; import javax.lang.model.util.Elements; import org.openide.filesystems.annotations.LayerBuilder.File; import org.openide.filesystems.annotations.LayerGeneratingProcessor; import org.openide.filesystems.annotations.LayerGenerationException; import org.openide.util.lookup.ServiceProvider; @ServiceProvider(service = Processor.class) @SupportedAnnotationTypes("org.netbeans.sbas.annotations.SuperclassBasedActionAnnotation") @SupportedSourceVersion(SourceVersion.RELEASE_6) public class SuperclassBasedActionProcessor extends LayerGeneratingProcessor { @Override protected boolean handleProcess(Set annotations, RoundEnvironment roundEnv) throws LayerGenerationException { Elements elements = processingEnv.getElementUtils(); for (Element e : roundEnv.getElementsAnnotatedWith(SuperclassBasedActionAnnotation.class)) { TypeElement clazz = (TypeElement) e; SuperclassBasedActionAnnotation mpm = clazz.getAnnotation(SuperclassBasedActionAnnotation.class); String teName = elements.getBinaryName(clazz).toString(); String originalFile = "Actions/" + mpm.path() + "/" + teName.replace('.', '-') + ".instance"; File actionFile = layer(e).file( originalFile). bundlevalue("displayName", mpm.displayName()). methodvalue("instanceCreate", "org.netbeans.sbas.annotations.SuperclassSensitiveAction", "create"). stringvalue("type", mpm.type()). newvalue("delegate", teName); actionFile.write(); File javaPopupFile = layer(e).file( "Loaders/text/x-java/Actions/" + teName.replace('.', '-') + ".shadow"). stringvalue("originalFile", originalFile). intvalue("position", mpm.position()); javaPopupFile.write(); } return true; } } The "SuperclassSensitiveAction" referred to in the code above is unchanged from how I had it in yesterday's blog entry. When I build the module containing two action listeners that use my new annotation, the generated layer file looks as follows, which is identical to the layer file entries I hard coded yesterday: <folder name="Actions"> <folder name="File"> <file name="org-netbeans-sbas-impl-ActionListenerSensitiveAction.instance"> <attr name="displayName" stringvalue="Process Action Listener"/> <attr methodvalue="org.netbeans.sbas.annotations.SuperclassSensitiveAction.create" name="instanceCreate"/> <attr name="type" stringvalue="java.awt.event.ActionListener"/> <attr name="delegate" newvalue="org.netbeans.sbas.impl.ActionListenerSensitiveAction"/> </file> <file name="org-netbeans-sbas-impl-BrandTopComponentAction.instance"> <attr bundlevalue="org.netbeans.sbas.impl.Bundle#CTL_BrandTopComponentAction" name="displayName"/> <attr methodvalue="org.netbeans.sbas.annotations.SuperclassSensitiveAction.create" name="instanceCreate"/> <attr name="type" stringvalue="org.openide.windows.TopComponent"/> <attr name="delegate" newvalue="org.netbeans.sbas.impl.BrandTopComponentAction"/> </file> </folder> </folder> <folder name="Loaders"> <folder name="text"> <folder name="x-java"> <folder name="Actions"> <file name="org-netbeans-sbas-impl-ActionListenerSensitiveAction.shadow"> <attr name="originalFile" stringvalue="Actions/File/org-netbeans-sbas-impl-ActionListenerSensitiveAction.instance"/> <attr intvalue="10" name="position"/> </file> <file name="org-netbeans-sbas-impl-BrandTopComponentAction.shadow"> <attr name="originalFile" stringvalue="Actions/File/org-netbeans-sbas-impl-BrandTopComponentAction.instance"/> <attr intvalue="30" name="position"/> </file> </folder> </folder> </folder> </folder>

    Read the article

  • Management Software in Java for Networked Bus Systems

    - by Geertjan
    Telemotive AG develops complex networked bus systems such as Ethernet, MOST, CAN, FlexRay, LIN and Bluetooth as well as in-house product developments in infotainment, entertainment, and telematics related to driver assistance, connectivity, diagnosis, and e-mobility. Devices such as those developed by Telemotive typically come with management software, so that the device can be configured. (Just like an internet router comes with management software too.) The blue AdmiraL is a development and analysis device for the APIX (Automotive Pixel Link) technology. Here is its management tool: The blue PiraT is an optimised multi-data logger, developed by Telemotive specifically for the automotive industry. With the blue PiraT the communication of bus systems and control units are monitored and relevant data can be recorded very precisely. And here is how the tool is managed: Both applications are created in Java and, as clearly indicated in many ways in the screenshots above, are based on the NetBeans Platform. More details can be found on the Telemotive site.

    Read the article

  • How to Implement Project Type "Copy", "Move", "Rename", and "Delete"

    - by Geertjan
    You've followed the NetBeans Project Type Tutorial and now you'd like to let the user copy, move, rename, and delete the projects conforming to your project type. When they right-click a project, they should see the relevant menu items and those menu items should provide dialogs for user interaction, followed by event handling code to deal with the current operation. Right now, at the end of the tutorial, the "Copy" and "Delete" menu items are present but disabled, while the "Move" and "Rename" menu items are absent: The NetBeans Project API provides a built-in mechanism out of the box that you can leverage for project-level "Copy", "Move", "Rename", and "Delete" actions. All the functionality is there for you to use, while all that you need to do is a bit of enablement and configuration, which is described below. To get started, read the following from the NetBeans Project API: http://bits.netbeans.org/dev/javadoc/org-netbeans-modules-projectapi/org/netbeans/spi/project/ActionProvider.html http://bits.netbeans.org/dev/javadoc/org-netbeans-modules-projectapi/org/netbeans/spi/project/CopyOperationImplementation.html http://bits.netbeans.org/dev/javadoc/org-netbeans-modules-projectapi/org/netbeans/spi/project/MoveOrRenameOperationImplementation.html http://bits.netbeans.org/dev/javadoc/org-netbeans-modules-projectapi/org/netbeans/spi/project/DeleteOperationImplementation.html Now, let's do some work. For each of the menu items we're interested in, we need to do the following: Provide enablement and invocation handling in an ActionProvider implementation. Provide appropriate OperationImplementation classes. Add the new classes to the Project Lookup. Make the Actions visible on the Project Node. Run the application and verify the Actions work as you'd like. Here we go: Create an ActionProvider. Here you specify the Actions that should be supported, the conditions under which they should be enabled, and what should happen when they're invoked, using lots of default code that lets you reuse the functionality provided by the NetBeans Project API: class CustomerActionProvider implements ActionProvider { @Override public String[] getSupportedActions() { return new String[]{ ActionProvider.COMMAND_RENAME, ActionProvider.COMMAND_MOVE, ActionProvider.COMMAND_COPY, ActionProvider.COMMAND_DELETE }; } @Override public void invokeAction(String string, Lookup lkp) throws IllegalArgumentException { if (string.equalsIgnoreCase(ActionProvider.COMMAND_RENAME)) { DefaultProjectOperations.performDefaultRenameOperation( CustomerProject.this, ""); } if (string.equalsIgnoreCase(ActionProvider.COMMAND_MOVE)) { DefaultProjectOperations.performDefaultMoveOperation( CustomerProject.this); } if (string.equalsIgnoreCase(ActionProvider.COMMAND_COPY)) { DefaultProjectOperations.performDefaultCopyOperation( CustomerProject.this); } if (string.equalsIgnoreCase(ActionProvider.COMMAND_DELETE)) { DefaultProjectOperations.performDefaultDeleteOperation( CustomerProject.this); } } @Override public boolean isActionEnabled(String command, Lookup lookup) throws IllegalArgumentException { if ((command.equals(ActionProvider.COMMAND_RENAME))) { return true; } else if ((command.equals(ActionProvider.COMMAND_MOVE))) { return true; } else if ((command.equals(ActionProvider.COMMAND_COPY))) { return true; } else if ((command.equals(ActionProvider.COMMAND_DELETE))) { return true; } return false; } } Importantly, to round off this step, add "new CustomerActionProvider()" to the "getLookup" method of the project. If you were to run the application right now, all the Actions we're interested in would be enabled (if they are visible, as described in step 4 below) but when you invoke any of them you'd get an error message because each of the DefaultProjectOperations above looks in the Lookup of the Project for the presence of an implementation of a class for handling the operation. That's what we're going to do in the next step. Provide Implementations of Project Operations. For each of our operations, the NetBeans Project API lets you implement classes to handle the operation. The dialogs for interacting with the project are provided by the NetBeans project system, but what happens with the folders and files during the operation can be influenced via the operations. Below are the simplest possible implementations, i.e., here we assume we want nothing special to happen. Each of the below needs to be in the Lookup of the Project in order for the operation invocation to succeed. private final class CustomerProjectMoveOrRenameOperation implements MoveOrRenameOperationImplementation { @Override public List<FileObject> getMetadataFiles() { return new ArrayList<FileObject>(); } @Override public List<FileObject> getDataFiles() { return new ArrayList<FileObject>(); } @Override public void notifyRenaming() throws IOException { } @Override public void notifyRenamed(String nueName) throws IOException { } @Override public void notifyMoving() throws IOException { } @Override public void notifyMoved(Project original, File originalPath, String nueName) throws IOException { } } private final class CustomerProjectCopyOperation implements CopyOperationImplementation { @Override public List<FileObject> getMetadataFiles() { return new ArrayList<FileObject>(); } @Override public List<FileObject> getDataFiles() { return new ArrayList<FileObject>(); } @Override public void notifyCopying() throws IOException { } @Override public void notifyCopied(Project prjct, File file, String string) throws IOException { } } private final class CustomerProjectDeleteOperation implements DeleteOperationImplementation { @Override public List<FileObject> getMetadataFiles() { return new ArrayList<FileObject>(); } @Override public List<FileObject> getDataFiles() { return new ArrayList<FileObject>(); } @Override public void notifyDeleting() throws IOException { } @Override public void notifyDeleted() throws IOException { } } Also make sure to put the above methods into the Project Lookup. Check the Lookup of the Project. The "getLookup()" method of the project should now include the classes you created above, as shown in bold below: @Override public Lookup getLookup() { if (lkp == null) { lkp = Lookups.fixed(new Object[]{ this, new Info(), new CustomerProjectLogicalView(this), new CustomerCustomizerProvider(this), new CustomerActionProvider(), new CustomerProjectMoveOrRenameOperation(), new CustomerProjectCopyOperation(), new CustomerProjectDeleteOperation(), new ReportsSubprojectProvider(this), }); } return lkp; } Make Actions Visible on the Project Node. The NetBeans Project API gives you a number of CommonProjectActions, including for the actions we're dealing with. Make sure the items in bold below are in the "getActions" method of the project node: @Override public Action[] getActions(boolean arg0) { return new Action[]{ CommonProjectActions.newFileAction(), CommonProjectActions.copyProjectAction(), CommonProjectActions.moveProjectAction(), CommonProjectActions.renameProjectAction(), CommonProjectActions.deleteProjectAction(), CommonProjectActions.customizeProjectAction(), CommonProjectActions.closeProjectAction() }; } Run the Application. When you run the application, you should see this: Let's now try out the various actions: Copy. When you invoke the Copy action, you'll see the dialog below. Provide a new project name and location and then the copy action is performed when the Copy button is clicked below: The message you see above, in red, might not be relevant to your project type. When you right-click the application and choose Branding, you can find the string in the Resource Bundles tab, as shown below: However, note that the message will be shown in red, no matter what the text is, hence you can really only put something like a warning message there. If you have no text at all, it will also look odd.If the project has subprojects, the copy operation will not automatically copy the subprojects. Take a look here and here for similar more complex scenarios. Move. When you invoke the Move action, the dialog below is shown: Rename. The Rename Project dialog below is shown when you invoke the Rename action: I tried it and both the display name and the folder on disk are changed. Delete. When you invoke the Delete action, you'll see this dialog: The checkbox is not checkable, in the default scenario, and when the dialog above is confirmed, the project is simply closed, i.e., the node hierarchy is removed from the application. However, if you truly want to let the user delete the project on disk, pass the Project to the DeleteOperationImplementation and then add the children of the Project you want to delete to the getDataFiles method: private final class CustomerProjectDeleteOperation implements DeleteOperationImplementation { private final CustomerProject project; private CustomerProjectDeleteOperation(CustomerProject project) { this.project = project; } @Override public List<FileObject> getDataFiles() { List<FileObject> files = new ArrayList<FileObject>(); FileObject[] projectChildren = project.getProjectDirectory().getChildren(); for (FileObject fileObject : projectChildren) { addFile(project.getProjectDirectory(), fileObject.getNameExt(), files); } return files; } private void addFile(FileObject projectDirectory, String fileName, List<FileObject> result) { FileObject file = projectDirectory.getFileObject(fileName); if (file != null) { result.add(file); } } @Override public List<FileObject> getMetadataFiles() { return new ArrayList<FileObject>(); } @Override public void notifyDeleting() throws IOException { } @Override public void notifyDeleted() throws IOException { } } Now the user will be able to check the checkbox, causing the method above to be called in the DeleteOperationImplementation: Hope this answers some questions or at least gets the discussion started. Before asking questions about this topic, please take the steps above and only then attempt to apply them to your own scenario. Useful implementations to look at: http://kickjava.com/src/org/netbeans/modules/j2ee/clientproject/AppClientProjectOperations.java.htm https://kenai.com/projects/nbandroid/sources/mercurial/content/project/src/org/netbeans/modules/android/project/AndroidProjectOperations.java

    Read the article

  • YouTube: Up & Running with Twitter Bootstrap

    - by Geertjan
    "Twitter Bootstrap is a free collection of tools for creating websites and web applications. It contains HTML and CSS-based design templates for typography, forms, buttons, navigation and other interface components, as well as optional JavaScript extensions. It is the most popular project on GitHub and has been used by NASA and MSNBC among others." (Wikipedia) Normally, when you read "getting started" instructions for Twitter Bootstrap, you're told to download various things from various sites. Then you're told to set up various folders and files, etc. What if it could be much simpler than that? Spend 7 minutes with me in this (silent) screencast and you'll see a complete development environment for developing applications with Twitter Bootstrap: Two things that could be added to the movie are the JavaScript debugger, the support for responsive design via switching between form factors in the embedded browser and Chrome with the NetBeans plugin, as well as how to convert the application to a native Android or iOS package via in-built Cordova support.

    Read the article

  • Implementing the NetBeans Project API on Maven in IntelliJ IDEA

    - by Geertjan
    James McGivern, one of the speakers I met at JAX London, is creating media software on the NetBeans Platform. However, he's using Maven and IntelliJ IDEA and one of the features he needs is project support, i.e., the project infrastructure that's part of NetBeans IDE. The two documents that describe the NetBeans Project API are these: http://platform.netbeans.org/tutorials/nbm-projecttype.html http://netbeans.dzone.com/how-create-maven-nb-project-type By combining the above two, you'll understand how to create a project infrastructure on top of the NetBeans Platform with Maven. However, an additional step of complexity is added when IntelliJ IDEA is included into the mix and therefore I created the following screencast which, in 15 minutes, puts all the pieces together. Be aware that I'm probably not using IntelliJ IDEA and Maven as optimally as I could and I'm publishing this at least partly so that the errors of my ways can be pointed out to me. But, first and foremost, this is especially for you James:  Note: Intentionally no sound, only callouts explaining what I'm doing. You'll probably need to pause the movie here and there to absorb the text; for details on the text, see the two links referred to above.

    Read the article

  • Sortable & Filterable PrimeFaces DataTable

    - by Geertjan
    <h:form> <p:dataTable value="#{resultManagedBean.customers}" var="customer"> <p:column id="nameHeader" filterBy="#{customer.name}" sortBy="#{customer.name}"> <f:facet name="header"> <h:outputText value="Name" /> </f:facet> <h:outputText value="#{customer.name}" /> </p:column> <p:column id="cityHeader" filterBy="#{customer.city}" sortBy="#{customer.city}"> <f:facet name="header"> <h:outputText value="City" /> </f:facet> <h:outputText value="#{customer.city}" /> </p:column> </p:dataTable> </h:form> That gives me this: And here's the filter in action: Behind this, I have: import com.mycompany.mavenproject3.entities.Customer; import java.io.Serializable; import java.util.List; import javax.annotation.PostConstruct; import javax.ejb.EJB; import javax.faces.bean.RequestScoped; import javax.inject.Named; @Named(value = "resultManagedBean") @RequestScoped public class ResultManagedBean implements Serializable { @EJB private CustomerSessionBean customerSessionBean; public ResultManagedBean() { } private List<Customer> customers; @PostConstruct public void init(){ customers = customerSessionBean.getCustomers(); } public List<Customer> getCustomers() { return customers; } public void setCustomers(List<Customer> customers) { this.customers = customers; } } And the above refers to the EJB below, which is a standard EJB that I create in all my Java EE 6 demos: import com.mycompany.mavenproject3.entities.Customer; import java.io.Serializable; import java.util.List; import javax.ejb.Stateless; import javax.persistence.EntityManager; import javax.persistence.PersistenceContext; @Stateless public class CustomerSessionBean implements Serializable{ @PersistenceContext EntityManager em; public List getCustomers() { return em.createNamedQuery("Customer.findAll").getResultList(); } } Only problem is that the columns are only sortable after the first time I use the filter.

    Read the article

  • Brain Teaser: How Did I Do This (Part 1: The Solution)

    - by Geertjan
    In Part 1: The Challenge, published this time last week, I introduced a "brain teaser". The brain teaser asks you to figure out how to allow images and other files to be meaningfully dropped onto a NetBeans Platform application, i.e., on the drop something useful should happen with the dropped file: if the file is an image, the image should open in the IDE; if the file is a PDF document, the PDF viewer should open externally; if the file is a text file, it should open as a text in the IDE, etc. Solution. And here is the solution: http://bits.netbeans.org/dev/javadoc/org-openide-windows/org/openide/windows/ExternalDropHandler.html When an implementation of the "ExternalDropHandler" class is available in the global Lookup, and an object is being dragged over some part of the main window, the window system may call the methods of this class to decide whether it can accept or reject the drag operation. And when the object is actually dropped, this class will be asked to handle the drop. OK, so go ahead and implement the above class and put it into the Lookup. Or... guess what? The NetBeans Platform has a default implementation of the above class, appropriately named "DefaultExternalDropHandler". Not only is this useful to learn about how to implement the ExternalDropHandler class (i.e., by reading the source here): you can simply include the module that contains this class in your own NetBeans Platform application and then your application will be able to receive external drag/drop events and do something meaningful with them thanks to the DefaultExternalDropHandler. Do this: Open your NetBeans Platform application in NetBeans IDE. Right-click the application in the Projects window and choose Properties. In the Libraries tab, expand the "ide" cluster, and select "User Utilities". (That's where "DefaultExternalDropHandler.java" is found and registered in the Lookup.) Now click the "Resolve" button, if it appears, because some additional related modules need to now be included, if they haven't been included yet. Again in the "ide" cluster in the Libraries tab, select "Image". That's the Image Editor. Click OK. Run the application. Drag an image or some other type of file into your application, from outside the application, and you'll see the application tries to handle the drop. If the file being dragged is an image, it will open in the Image Editor, which you included in the previous step of these instructions. Hurray, you're done. Without any programming at all, you've added a cool new feature to your application.

    Read the article

  • Savable in Widget Lookup on Move Action

    - by Geertjan
    Possible from 7.3 onwards, since Widget now implements Lookup.Provider for the first time: import java.awt.Point; import java.io.IOException; import org.netbeans.api.visual.action.ActionFactory; import org.netbeans.api.visual.action.MoveProvider; import org.netbeans.api.visual.widget.LabelWidget; import org.netbeans.api.visual.widget.Scene; import org.netbeans.api.visual.widget.Widget; import org.netbeans.spi.actions.AbstractSavable; import org.openide.util.Lookup; import org.openide.util.lookup.AbstractLookup; import org.openide.util.lookup.InstanceContent; import org.openide.windows.TopComponent; public class MyWidget extends LabelWidget { private MySavable mySavable; private Lookup lookup; private TopComponent tc; private InstanceContent ic; public MyWidget(Scene scene, String label, TopComponent tc) { super(scene, label); this.tc = tc; ic = new InstanceContent(); getActions().addAction(ActionFactory.createMoveAction(null, new MoveStrategyProvider())); } @Override public Lookup getLookup() { if (lookup == null) { lookup = new AbstractLookup(ic); } return lookup; } private class MoveStrategyProvider implements MoveProvider { @Override public void movementStarted(Widget widget) { } @Override public void movementFinished(Widget widget) { modify(); } @Override public Point getOriginalLocation(Widget widget) { return ActionFactory.createDefaultMoveProvider().getOriginalLocation(widget); } @Override public void setNewLocation(Widget widget, Point point) { ActionFactory.createDefaultMoveProvider().setNewLocation(widget, point); } } private void modify() { if (getLookup().lookup(MySavable.class) == null) { ic.add(mySavable = new MySavable()); } } private class MySavable extends AbstractSavable { public MySavable() { register(); } TopComponent tc() { return tc; } @Override protected String findDisplayName() { return getLabel(); } @Override protected void handleSave() throws IOException { ic.remove(mySavable); unregister(); } @Override public boolean equals(Object obj) { if (obj instanceof MySavable) { MySavable m = (MySavable) obj; return tc() == m.tc(); } return false; } @Override public int hashCode() { return tc().hashCode(); } } }

    Read the article

< Previous Page | 1 2 3 4 5 6 7 8 9 10  | Next Page >