DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library
Avatar

Geertjan Wielenga

Writer at Sun

Prague, CZ

Joined Sep 2007

Stats

Reputation: 70
Pageviews: 4.3M
Articles: 38
Comments: 57
  • Articles
  • Refcards
  • Comments

Articles

article thumbnail
Calling JavaFX From Java?
Putting Together the Best of Both Worlds One of the things that people like so much about JavaFx is the fact that it has a suite of powerful tools used by designers and creators to get exactly the kind of look and feel that they desire from their creations. When used properly, JavaFX will change the way that you take care of your biggest technology challenges. That is why it is such a powerful product to use, and that is also why people around the world recommend it for the value that it can add to your work. A few of the features that are included are: WebView Java APIs High-Performance Media Engine Multitouch Support Canvas API These are just a few of the things that JavaFx has going for it. Truly, it is a powerful engine that people use to help make sure their media creations are something that people will stand up for and take note of. The truth is, no matter who you are or what your intentions are for the use of Java in your life, the JavaFX combined with Java itself is the way to go. while experimenting with javafx, remember that java is never far away. in this case, let's call out to : here we go, here's all that's needed, via the scripting api, which is included in the javafx sdk: package calc; import java.io.inputstreamreader; import javax.script.scriptengine; import javax.script.scriptenginemanager; import javax.script.scriptexception; public class calculatorlauncher { public static void main(string[] args) { try { scriptenginemanager manager = new scriptenginemanager(); scriptengine engine = manager.getenginebyextension("fx"); inputstreamreader reader = new inputstreamreader(calculatorlauncher.class.getresourceasstream("calculator.fx")); engine.eval(reader); } catch (scriptexception ex) { } } } and so, here's my whole application, calling jim weaver's calculator demo: What is even better would be to be able to embed that JavaFX stage (or a panel-like part thereof?) into a JFrame. then one would have the best of both worlds: the graphic "oomph" of JavaFX, together with the daily low-level grunt work of java. that, I believe (and hope), is the promise of JavaFX for java developers (and groovy developers), as opposed to designers and similar graphic artists, who seem to be the primary target of JavaFX. Day-to-Day Grind Work One thing that people absolutely love about Java itself is that it allows them to get the day-to-day grunt work done that they need to be done. They are able to see real progress on a daily basis simply by using Java to help propel their best efforts into the world. Yes, there are not as many bells and whistles with Java as there are with JavaFx and other tools, but that just means that there is more to combine with Java to get it to do all that you want it to do. Using JavaFX and Java together can help get more done. This is an innovative approach because it means that they are able to use the bells and whistles of JavaFx incorporated into the practicality of Java itself. Bringing those two things together is a great way for everyday people to achieve results in their work that they would not normally have believed was possible. We do need to recognize the fact that there are many great resources that Java can be used for, but it is also the case that JavaFx simply gives it the extra push that it needs to be a great computing program all around. We would be remiss if we didn’t combine the two things together for optimal use. Does JavaFX Makes Sense For Business Applications? There is still a lot of debate about how much sense it makes to use JavaFX for business applications. On the one hand, there are a lot of people who prefer this as their technology of choice. However, there are some others that say that it is too buggy and can’t handle all of the data that is required for a business operation to run smoothly. What people really like about JavaFx is the fact that it can be used on a “zero installation” basis. This means that it doesn’t need to dig deep into your databases and systems in order to function the way that it is supposed to. That is a pretty big deal because you may find it quite irritating to try to deal with systems that constantly request permissions from you to get deeper and deeper into sensitive data. JavaFX doesn’t do that. However, there is a trade-off. The fact that JavaFX doesn’t need to be as deep into your company’s systems also means that it doesn’t necessarily have the computing power that you may require to fun every operation that you need it to. That means that there could be unnecessary crashes and delays when you attempt to use this system as a standalone program. Does Combining It With Java Help? Some of the issues that are seen with JavaFx may be relieved by the fact that you can also use plain old Java to help make things run a little more smoothly. That’s right, you can combine the Java platform that you are already familiar with to let it latch on to the JavaFx system and generate results that way. You may see fewer system errors and hang-ups when you use this older piece of software to aid the JavaFx system. Regular Java does require more permissions to your data, but that may be a trade-off that you are willing to make if you understand that the upsides are potentially quite enormous for you. Think about your options carefully and then make a decision. Unless you are guarding particularly sensitive data at your company, it probably makes sense to go forward with the plan to get JavaFx and Java combined into the rotation of programs that you use. Innovation Is At Your Fingertips There is plenty of excitement and buzz about the possibilities that JavaFx can bring to the world of business. People are looking at it and starting to realize that there are many ways that it may be used as an innovation machine. They are particularly excited that there are more options than ever available to them and that they can see the ways in which this system may be used to generate outsized business opportunities both for the company that they work for as well as for themselves. If you haven’t had the chance to try the JavaFx system for yourself yet, you need to give it a shot. There are a lot of people who are already benefiting from what it has to offer, and you may fall behind if you don’t try it out as well. Look at what it can do when you get the chance, and then get one for yourself and begin the process of innovation. You won’t regret taking this opportunity to expand your horizons.
July 24, 2022
· 41,113 Views · 3 Likes
article thumbnail
Interview: Ikroop Dhillon on Oracle Solaris Studio
This article was originally published on 6/29/15 For developers coding in c/c++, NetBeans IDE provides a c/c++ bundle of its set of tools. However, the NetBeans c/c++ toolset is the application platform for Oracle Studio IDE, which provides a set of features that extend the NetBeans c/c++ toolset. In this interview, we meet Ikroop Dhillon, who is the principal product manager of Oracle Solaris studio. She tells us about herself and about the Oracle Solaris studio. Speaking with the True Professionals Anytime we set up an interview with someone in space, we always want to ensure that they are someone with something interesting to say. Believe it or not, that is not always as easy to find as you might imagine. This is why we were so thrilled when we heard back from Ikroop Dhillon about our interview request. Dhillon is a great person to speak with about these matters because she is a product manager at Oracle Solaris Studio, and she has overseen countless projects in her time there. Not only that, but we find her insights and information to literally be second to none. It was our greatest pleasure to get to speak with her. As someone with a background in computer science, Dhillon is exactly the kind of person that is up-to-date and knowledgeable about the inner workings of computers and all of the latest updates in the industry. She has been continuously learning about how various processes work and what the latest updates are in the world of computers. Thus, it is with great pleasure that we were able to meet up with her and go over the latest as it was developing all around us. What we wanted to cover included topics that have not often been discussed by other teams of interviewers before. We knew that Ikroop Dhillon would provide us with the time that we needed to start getting some answers from her about what all of these changes might mean for the brave new world that we are all entering at this time. It has been an interesting and challenging time, to say the least, and we can all stand to learn something from those who are tracking the developments as they happen day by day. Dhillon is exactly the kind of person you want in your corner if that is your mission, and that is why we spent such a lengthy amount of time speaking with her at this time. We hope that you gain some useful insights from our conversation. We certainly picked up a lot of information that we wouldn’t otherwise have had access to. Hi Ikroop, thanks for taking the interview. Can you tell us a bit about who you are and what you do? Hi! Thanks for chatting with me today. I am the principal product manager for oracle Solaris studio, and I focus on business development, product strategy, and go-to-market plans. How and when did you get involved with oracle Solaris studio? I have an educational background in computer science and was a technical marketing engineer at Intel prior to joining oracle. I have always had an interest in application development and started product management of oracle Solaris studio development tools about seven years ago. What are the key aims of oracle Solaris studio? Oracle Solaris studio is an advanced c, c++, and Fortran development environment. It runs on both Oracle Solaris and Oracle Linux operating systems, and with remote development support, developers can build, debug, analyze and optimize applications from virtually any laptop or desktop environment. Oracle Solaris studio delivers a complete and comprehensive tool suite aimed at simplifying the development of high-performance, secure, reliable, and robust enterprise applications. So, it doesn't run on windows? If you go to the oracle Solaris studio download page, then you'll see downloads for Linux and Solaris. http://www.oracle.com/technetwork/server-storage/solarisstudio/downloads/index-jsp-141149.html but a tar file can be downloaded as well, and on any java-aware oses, the user can run GUI tools in "remote mode": https://blogs.oracle.com/d/entry/using_the_solaris_studio_ide What do you consider to be the most awesome and unique features of oracle Solaris studio? Oracle Solaris studio contains some very powerful application analysis tools. The oracle Solaris studio performance analyzer helps you optimize your application by enabling you to easily identify and fix performance bottlenecks. It has an intuitive and easy-to-use interface that allows you to visualize performance data from various angles and easily drill down and isolate performance issues. The code analyzer is another great component of oracle Solaris studio that helps you protect your application from memory access issues, including memory leaks. In addition to the analysis tools, Oracle Solaris studio also has an award-winning IDE. Based on the NetBeans platform. The IDE is specifically geared for c/c++ developers and is optimized to handle large enterprise applications very well. We focus on making sure that the IDE has a low memory footprint when handling large applications and fast response times. Under what conditions should oracle Solaris studio be used instead of the c/c++ tools that come with NetBeans IDE? Oracle Solaris studio delivers advanced performance, memory, and thread analysis tools in addition to those provided by NetBeans IDE. These powerful analysis tools help optimize application performance and improve software reliability and quality. In addition, Oracle Solaris studio delivers highly optimized c, c++, and Fortran compilers and performance libraries for compute-intensive applications. If you are looking for a complete and comprehensive c/c++ and Fortran development tool suite, it is recommended that you use Oracle Solaris studio. What kinds of customers are using Oracle Solaris studio, and what are they doing with it? Our customers include leading companies in finance, telecommunications, and defense. We also work closely with top oracle ISVs and partners. Our customers rely on oracle Solaris studio for the development of their mission-critical enterprise applications, and most Oracle applications are built using Oracle Solaris studio. Can you tell us a bit about the social media and related sites that are important for those using Oracle Solaris studio? The oracle technology network contains the product download (oracle Solaris studio free to use in production) and learning resources, including technical articles, whitepapers, and how-to videos: http://www.oracle.com/technetwork/server-storage/solarisstudio/overview/index.html The oracle.com site includes the datasheet, product briefs, and customer quotes: oracle.com/goto/solarisstudio You can also follow us on Facebook or Twitter for product and content updates: https://www.facebook.com/oraclesolarisstudio https://twitter.com/solarisstudio Anything else you'd like to share with the NetBeans community? I just recorded some videos that highlight some important features of oracle Solaris studio. The oracle Solaris studio performance analyzer also supports java and does a terrific job of optimizing java application performance. It is quite useful if you have a mixed c/c++ and java application.
June 29, 2015
· 3,132 Views
article thumbnail
NetBeans IDE 8.0.1 Now Available for Download
The NetBeans Team has released NetBeans IDE 8.0.1, with significant enhancements to features relating to HTML5, JavaScript, and CSS3. An update to NetBeans IDE 8.0, this release includes the following notable changes: Modularity and enterprise JavaScript development support via integration of RequireJS Tools for working seamlessly with Grunt, Karma, and Bower Enhanced Java Editor, PHP Editor, and Git Tools Support for new versions of WebLogic, GlassFish, Tomcat, WildFly, and PrimeFaces Performance improvements and bug fixes Complete list of features: http://wiki.netbeans.org/NewAndNoteworthyNB801 To get the recent changes: Download and install NetBeans 8.0.1, which includes the recently released GlassFish 4.1 OR If you already have NetBeans IDE 8.0 installed, launch the IDE and an update notification will appear. Alternatively, choose Help | Check for Updates. Click the alert-box to install the updates. For details on upgrading, see the YouTube screencast "How to Upgrade to NetBeans IDE 8.0.1 from NetBeans IDE 8.0" on the NetBeans YouTube channel. NetBeans IDE 8.0.1 is available in English, Brazilian Portuguese, Japanese, Russian, and Simplified Chinese. We welcome feedback about your use of NetBeans software. Share your thoughts on the NetBeans mailing lists and forums; and keep track of NetBeans news by subscribing to the NetBeans Weekly Newsletter and following NetBeans on Twitter, Facebook, and YouTube.
September 10, 2014
· 36,715 Views
article thumbnail
Business Process Modeling in NetBeans IDE
gaurav gupta is a senior software engineer working on the bpmn workflow engine. he's created several plugins for netbeans ide, notably the js css minify compress plugin ( here ) and the jbpmn plugin, which is the topic of this interview. the plugin provides netbeans ide tools for working with business process modeling notation (bpmn). the plugin can be accessed here, including for netbeans ide 7.4 and 8.0 beta, together with screencasts and tutorials: http://plugins.netbeans.org/plugin/50735/jbpmn hi, gaurav, why did you create the bpmn plugin? business process modeling notation is an increasingly important standard for process modelling and has enjoyed high levels of adoption, so the specific intent of the jbpmn plugin is to create a bpmn modeler that supports the complete bpmn specification and can be integrated by multiple bpmn engine vendors into netbeans ide. as a result, different bpmn engine vendors will not need to create separate bpmn modelers for netbeans ide. another reason i created this plugin was to bring the netbeans community closer to the bpm community because bpmn has become the de-facto standard for business process modeling. also, when we talk about "netbeans vs eclipse", the basic conclusion is that netbeans is much more intuitive and easy to use, while eclipse has a wider range of third-party plugins support from more companies. in that context, i have taken this initiative to create the bpm plugin to help the netbeans community. what would you consider to be the best features of the bpmn plugin? the jbpmn nb modeler is a graphical modelling tool which allows the creation and editing of bpmn process diagrams. it provides debugging supports for jbpm 5.0. it is bpmn engine vendor neutral, can be used by any vendor or generated xml, and can run on any bpmn engine which adopts the bpmn 2.0 standard. here's another screenshot: what are the future development plans for this plugin? to cover the complete bpmn ssecification with user friendly gui and properties support. jbpmn currently supports only the bpmn process model, it will also support the bpmn conversation model. it will also provide support to extends the modeller with your own palette elements, properties, and generated xml tags. it will provides debugging supports for jbpm 6.0, activities, and also extensions so that any bpmn engine vendor can integrate debugging functionality within jbpmn. it will also provide a netbeans modeler platform api, which any business modeller can use to easily build solutions such as a bpmn conversation model.
January 26, 2014
· 15,741 Views
article thumbnail
8 New & Beefed Up NetBeans Keyboard Shortcuts!
My colleague Tom McGinn recently published 10 Time Savers in NetBeans, an excellent overview of tips that everyone using NetBeans should read. For those of us who are keyboard oriented (i.e., we hate the mouse because it breaks our workflow), here is an appendix to Tom's article, listing the very newest keyboard shortcuts, available in NetBeans IDE 7. Most are new or changed in NetBeans IDE 7.2, while the last one is new but unchanged from NetBeans IDE 7.1. Alt + Scroll Up/Down. Increase/decrease the font size. Font resizing, which was first introduced in NetBeans IDE 7.1, was initially done by holding down the Ctrl key while scrolling. However, this conflicted with other actions, as explained in issue 212484. Following discussions with the NetBeans community, the Ctrl key was changed for the Alt key, and now, when you hold down the Alt key and then scroll up/down, in any file, the font size will increase/decrease. Alt + Shift + Page Up/Down. Quickly move entire code elements, i.e., statements and class members, up or down. Take the following situation. The cursor is on the first line below; if you were to use the standard Alt + Shift + Down, only the line would be moved down, which would immediately create an error in the editor because now the class cannot be compiled anymore. However, if you use Alt + Shift + Page Down instead (i.e., Page Down instead of simply Down), the entire method will move downwards, over the method below that, and will then appear below the method that is currently below it. In other words, the move action now has semantic knowledge of the code being moved, as well as semantic knowledge of the code around it. A similarly semantic-aware keyboard shortcut, though not new in NetBeans IDE 7, is Alt + Shift + Period, which lets you semantically expand the selection from the currently selected word to the next level of semantic knowledge, e.g., method or class, and back again via Alt + Shift + Comma. Alt + Backspace. Quickly remove the enclosing parts of a nested statement. Put the cursor within the word "for", or "if", or "else", for example, then press Alt + Backspace and the popup below is displayed. Mouse down or up in the list and then press Enter to confirm. Ctrl + Shift + M. Add/remove a bookmark to/from the Bookmarks Window. As always, you can set bookmarks in your code. However, now, when you do so, the bookmarks are, in addition to being marked in the file, added to the new Bookmarks Window (available via Window | Navigating | Bookmarks). From the Bookmarks Window, you can now jump across all your files and all your projects so that you can, for example, create a task-oriented track through your projects: In a related change, when you now use Ctrl + Shift + Period or Ctrl + Shift + Comma, to toggle back and forward between bookmarks, this handy popup appears, listing all the bookmarks found within the Bookmarks Window: Alt + Shift + F. The "Reformat" action can now be used across multiple projects, packages, and classes, for the first time. That means that when you use the old Alt + Shift + F while multiple nodes are selected in the Projects window, all files within the selected nodes will be reformatted at the same time. Ctrl + Z. The "Undo" keyboard shortcut now applies to refactorings too, for the first time. In previous releases, you needed to use a separate action especially for undoing refactorings, which was very hidden in the Refactoring menu and therefore hard to find, and therefore not frequently used because typically you wouldn't know it existed. Ctrl + Space. Once you have pressed Ctrl-F or Ctrl-H to open the Find bar or the Search bar at the bottom of any file (not only Java source files, but also HTML files, for example), you can press Ctrl + Space which lets you use code completion within the Find field, which can be very useful to get a quick overview of the items you could be trying to find. In the Debugger, the same is true in the New Breakpoint dialog. Ctrl + Shift + R. Change the cursor to a block selector. Then put the cursor next to the top left of the block and Shift+Click its bottom right corner. You now have a block, which you can manipulate, e.g., move or cut or copy or delete or change all the lines within the block. Start typing while having a block selected and all the lines will change simultaneously. Applies to all file types, not only Java source files, as can be seen here: Note: And, a final tip, if you go to the Help menu in NetBeans IDE, you'll find the updated NetBeans IDE Keyboard Shortcut Card in PDF format, ideal for printing out and hanging in a nice frame in your workspace!
August 19, 2012
· 54,845 Views
article thumbnail
Interview: Troy Giunipero, Author of NetBeans E-commerce Tutorial
Troy Giunipero (pictured, right) is a student at the University of Edinburgh studying toward an MSc in Computer Science. Formerly, he was one of the NetBeans Docs writers based in Prague, Czech Republic, where he spent most of his time writing Java web tutorials. In this interview, Troy introduces you to The NetBeans E-commerce Tutorial. This is a very detailed tutorial describing just about everything you need to know when creating an e-commerce web application in Java. It has received a lot of very positive feedback. Let's find out about the background of this tutorial and what Troy learnt in writing it. Hi Troy! During your time on the NetBeans team, you wrote a very large tutorial describing how to create an e-commerce site. How and why did you start writing it? Well, there’s a short answer and a long answer to this. The short answer is that I was lucky to take part in Sun’s SEED (Sun Engineering Enrichment and Development) program. I wanted to focus on technical aspects, so I based my curriculum on developing an e-commerce application using Java technologies. I documented my efforts and applied them toward deliverables for the IDE’s 6.8 and 6.9 releases, resulting in the 13-part NetBeans E-commerce Tutorial. The long answer is that I had previously been tasked with creating an e-commerce application for my degree project (I was studying toward a BSc in IT and Computing), and ran into loads of trouble trying to integrate the various technologies into a cohesive, functioning application. I was coming from a non-technical background and found there was a steep learning curve involved in web development. My work was fraught with problems which I can now attribute to poor time-management, and a lack of good, practical, hands-on learning resources. So in a way, working on the AffableBean project (this is the project used in the NetBeans E-commerce Tutorial) was a way for me to go back and attempt to do the whole thing right. With the tutorial, I had two goals in mind: one, I wanted to consolidate my understanding of everything by writing about it, and two, I wanted to help others avoid the problems and pitfalls that I’d earlier ran into by designing a piece of documentation that puts everything together. Can you run us through the basic parts and what they provide? Certainly. First I want to point out that there’s a live demo application (http://dot.netbeans.org:8080/AffableBean/) which I managed to get up and running with help from Honza Pirek from the NetBeans Web Team (thanks Honza!): The application is modeled on the well-known MVC architecture: The tutorial refers to the above diagram at various points, and covers a bunch of different concepts and technologies along the way, including: Project design and planning (unit 2) Designing a data model (using MySQL WorkBench) (unit 4) Forward-engineering the data model into a database schema (unit 4) Database connectivity (units 3, 4, 6) Servlet, JSP/EL and JSTL technologies (units 3, 5, 6) EJB 3 and JPA 2 technologies (unit 7), and transactional support (unit 9) Session management (i.e., for the shopping cart mechanism) (unit 8) Form validation and data conversion (unit 9) Multilingual support (unit 10) Security (i.e., using form-based authentication and encrypted communication) (unit 11) Load testing with JMeter (unit 12) Monitoring the application with the IDE’s Profiler (unit 12) Tips for deployment to a production server (units 12, 13) Also, the tutorial aims to provide ample background information on the whole “Java specifications” concept, with an introduction to the Java Community Process, how final releases include reference implementations, and how these relate to the tutorial application using the IDE’s bundled GlassFish server (units 1, 7). Finally, the tutorial is as much about the above concepts and technologies as it is about learning to make best use of the IDE. I really tried to squeeze as much IDE-centric information in there as possible. So for example you’ll find: An introduction to the IDE’s main windows and their functions (unit 3) A section dedicated to editor tips and tricks (unit 5), and abundant usage of keyboard shortcuts in steps throughout the tutorial Use of the debugger (unit 8) Special “tip boxes” that discuss IDE functionality that is sometimes difficult to fit into conventional documentation. For example, there are tips on using the IDE’s Template Manager (unit 5), GUI support for database tables (unit 6), Javadoc support (unit 8), and support for code templates (unit 9). Did you learn any new things yourself while writing it? Yes! Three things immediately come to mind: EJB 3 technology. Initially this was a big hurdle for me. Using EJB 3 effectively seems to be something of an art form. If you know what you’re doing and understand exactly how to use the EntityManager to handle persistence operations on a database, EJB lets you do some amazingly smart things with just a few lines of code. But there seems to be a lack of good free documentation online—especially since EJB 3 is a significant departure from EJB 2. Therefore, almost all of the tutorial’s information on EJB comes from the very excellent book, EJB in Action by Debu Panda and Reza Rahman. Interpreting the NetBeans Profiler. The final hands-on unit, Testing an Profiling, was the most difficult for me to write, primarily because I just wasn’t familiar with the Profiler at all. I spent an unhealthy amount of time just watching the Telemetry graph run against my JMeter test plan, which is only slightly more stimulating than watching water come to boil. That being said, I feel that by just examining the graphs and other windows over time, critical logical associations start to jump out at you after a while. Likewise with JMeter. Hopefully unit 12 was able to capture and relay some of these. How to search online for decent articles and learning materials. The old Sun Technical Articles site was a great resource. Many of the links in the See Also sections at the bottom of tutorial units were found by adding site:java.sun.com/developer/technicalArticles/ to a Google search. Also the official forums (found at forums.sun.com) became a good place for questions I couldn’t find ready answers to. I had both the Java EE 5 and 6 Tutorials bookmarked. And Marty Hall’s Core Servlets and JavaServer Pages became an invaluable resource for the first half of the tutorial. What are your personal favorite features of the technologies discussed in the tutorial? I particularly liked learning about session management—using the HttpSession object to carry user-specific data between requests, and working with JSP’s corresponding implicit objects in the front-end pages. Session management is a defining aspect for e-commerce applications, as they need to provide some sort of shopping cart mechanism... ...and so the Managing Sessions unit (unit 8) was a key chapter in the tutorial. It’s extremely useful to be able to suspend the debugger on a portion of code that includes session-scoped variables, then hover the mouse over a given variable in the editor to determine its current value. I used the debugger continuously during this phase, and so I went so far as to incorporate use of the debugger throughout the Managing Sessions unit. What kind of background does someone starting the tutorial need to have? Someone can come to the tutorial with little or absolutely no experience using NetBeans. I’ve tried to be particularly careful in providing clear and easy-to-follow instructions in this respect. But one would be best off having some background or knowledge in basic web technologies, and at least some exposure to relational databases. With this foundation, I think that the topics covered in the second half of the tutorial, like applying entity classes and session beans, language support and security, won’t seem too daunting. I’ve noticed that the vast majority of feedback that comes in relates to the first half of the tutorial, and I sometimes get the impression that people feel they need to follow the tutorial units consecutively. Not so. The units are 90% modular. In other words, if somebody just wants to run through the security unit (unit 11), they can do so by downloading the associated project snapshot, follow the setup instructions, and then just follow along without needing to even look at other parts of the tutorial. What will they be able to do at the end of it? Naturally, anybody who completes individual tutorial units will be able to apply the concepts and technologies to their own work. But anyone who completes the tutorial in its entirety will gain an insight into the development process as a whole, and I think will also get a certain confidence that comes with knowing how “all the pieces fit together”—from gathering customer requirements all the way to deployment of the completed app to a production server. They’ll also have gained a solid familiarity with the NetBeans IDE, and be in a good position to explore popular Java web frameworks that work on top of servlet technology or impose an MVC architecture on their own, such as JSF, Spring, Struts, or Wicket. Do you see any problems in the technologies discussed and what would be your suggestions for enhancements? Well there’s one thing that comes to mind. When I started working on this project, I was studying the Duke’s BookStore example from the Java EE 5 Tutorial. A wonderful example that demonstrates how to progressively implement the same application using various technologies and combinations thereof. So for example you start out with an all-servlet implementation, then move on to a JSP/servlet version. Then there’s a JSTL implementation and ultimately, a version using JavaServer Faces. It’s great learning material, but also terrifically outdated. Right around this time, Sun was gearing up for the big Java EE 6 release (Dec. 2009), and I was also trying to learn about the new upcoming technologies, namely CDI, JSF 2, and EJB 3, for my regular NetBeans documentation work. I was getting the definite sense that JSP and JSTL were slowly being pushed aside—in the case of JavaServer Faces, Facelets templating was the new page authoring technology. So really, the E-commerce Tutorial application has become a sort of EE 5/EE 6 hybrid by combining JSP/JSTL with EJB 3 and JPA 2. Now the problem I see from the perspective of a student trying to learn this stuff from scratch, is that the leap from basic servlet technology to a full-blown JSF/EJB/JPA solution is tremendous, and cannot readily be taught through a single tutorial. Naturally, others may disagree with me here. I’m not sure if there’s a solution other than to compensate by producing a lot of quality learning material that covers lots of different use-cases. I’d suggest that the E-commerce Tutorial puts one in a very advantageous position to begin learning about Java-based frameworks, such as GWT, Spring, and JSF, which is a natural course of action for people looking to get a job with this knowledge. Planning any more parts to the tutorial or a new one? No more parts. The E-commerce Tutorial is done. Upon committing the final installments and changes last November, I rejoiced. However, I’m still actively responding to feedback [the ‘Send Us Your Feedback’ links at the bottom of tutorials] and plan to maintain it indefinitely, so if anyone spots any typos, has questions or comments, recommendations for improvement, etc., please write in! :-)
January 9, 2011
· 30,186 Views
article thumbnail
Microchip's Embedded Software Development on the NetBeans Platform
Vince Sheard (pictured right) is the Manager of the MPLAB® Integrated Development Environment (IDE) team at Microchip Technology Inc. He has been working at Microchip for more than 10 years, and was the lead architect for the MPLAB X IDE version 1.0, prior to stepping into the management roll. This, the port of MPLAB to the NetBeans Platform, is the sixth major architecture change of the MPLAB IDE since its inception in 1992. Microchip Technology Inc., headquartered in Chandler, Arizona, was spun off from General Instrument in 1989. The Company went public in 1993, and is a leading provider of microcontroller, analog, and Flash-IP solutions, providing low-risk product development, lower total system cost and faster time to market for thousands of diverse customer applications worldwide. Headquartered in Chandler, Arizona, Microchip offers outstanding technical support along with dependable delivery and quality. For more information, visit the Microchip website at http://www.microchip.com. (The MPLAB X landing page is http://www.microchip.com/mplabx, which will be available in the next few days.) Hi, Vince. What's MPLAB, in a nutshell? MPLAB® is an integrated development environment or IDE. It is similar to other IDEs, but there are two important differences. The first difference is that the MPLAB IDE is our customers’ window into Microchip’s PIC® microcontrollers embedded in their designs. Many people believe they understand their PC, because it is “right here.” An embedded device is more difficult to get a handle on. It’s the brain of a product “over there.” It’s not a computer, it’s a thing. The MPLAB IDE gives embedded developers an opportunity to dig into the brain of that thing. The second important difference is that the MPLAB IDE seamlessly covers Microchip’s entire portfolio of more than 700 8-bit, 16-bit and 32-bit PIC microcontrollers. The differences between these devices are massive, from a tiny 6-pin, 8-bit microcontroller that could fit under your fingernail, to a huge 32-bit microcontroller that is much more powerful than the iconic IBM mainframe of last century. The MPLAB IDE provides a consistent and supportive environment in which to debug our customers’ original, creative works of software that differentiate their products. What are the MPLAB IDE’s main features and how does it distinguish itself from its competitors? Integrated development environments share many features: project creation and management, programmers’ editor, language tool integration and build tools, image preparation and programming, and debug facilities. These are the MPLAB X IDE’s main features, too. A large difference comes in the presentation of an embedded target, rather than a PC target, which presents a developer with a less coupled and less easily controlled object for their development. That tightens the focus, but there are other IDEs that support embedded development. The MPLAB X IDE is distinguished by its seamless and timely support of Microchip devices, the vast ecosystem of tightly integrated compilers and hardware tools that also support those devices, and the evolutionary grace of a tool that has grown with our customers and technologies until the three form a smooth and supportive system for developing innovative embedded products. What are the typical technical challenges of an application of this kind? The principal challenge we face is how to provide the facilities developers need in the most intuitive and useful way possible. It’s easy to provide tons and tons of features, but with the GUI technologies of today, one can only present a small fraction of what is provided and available for use. One of the gauges for how well we’ve done our job is when our customers present a fine point of usage that we’ve already discussed and disagreed on how to implement. Those "complaints" are really wonderful because they come from expert tool users who understand the tools they are using. Of course, we are always hustling to present new Microchip devices in the same light that we present established devices. We’re also challenged to exploit the advanced debug facilities of new devices in a way that is most beneficial for our customers. What's the architecture of the application and why did you make the choices that you did? We’re moving away from a Windows OS-only, COM-based architecture. As our customers’ development sophistication has grown, so have their needs. Our customers now require Linux, Mac, and Windows support. Microchip is a worldwide company with customers who may only be fluent in a single language, so that impacts our choices. We also have a number of educational institutions who place interesting demands on the IDE, along with a number of advanced customers who are very forward-looking and are really pushing the envelope of what was previously thought possible. The most telling choice we had to make, though, was the choice of NetBeans as a fully capable, modern, lightweight and flexible platform for our next-generation MPLAB X IDE: Where does the NetBeans Platform fit into all of this? NetBeans is unique among current open-source IDE platform offerings, in that it is the most advanced for addressing our primary challenge, which I described above. The NetBeans IDE presents standard operations in a way that really minimizes hunting around and wasting time, to find out how to accomplish what you need to do. Take, for instance, the classic edit, compile, debug “cycle.” In NetBeans, like in other IDEs, the edit part is pretty easy: open the source file in the programmers’ editor and make the changes you need. It’s really not much different than editing a document with a word processor. The next step is where the difference really shows. In some IDEs, you have to compile or build an image and then figure out how to load it and start a debugging session. In some IDEs, that’s just brutal to figure out, especially in embedded systems where, as we said, the target is not “right here,” it’s “over there.” In NetBeans, it’s a single button press (DebugRun), even in an embedded context like ours. After that, the rest of the steps are taken care of. If any errors occur during the sequence, we take it home by capturing the errors and placing the user in context for an easy solution; and the ability to move on. That’s just one example. NetBeans is way ahead of the curve compared to other menu/toolbar/property sheet IDEs. What are the 3 main benefits of the NetBeans Platform, in this context? First and foremost is the ability to really optimize developers’ time. That’s a major factor in our customers’ focus. Second is the fact that NetBeans is a modern, lightweight and fully capable IDE platform. It doesn’t suffer from the bloat and outdated aspects of some other IDE platforms. Included with these benefits are the abilities to localize the IDE and to utilize it on multiple operating systems. Last, but not least, is the huge benefit of a professionally executed development, maintained by a focused organizing committee and maintained by a tight-knit development community—all headed by the Oracle contributions. That’s a significant departure from some other high-profile, open-source platforms that are available. How did you end up choosing the NetBeans Platform over its alternatives? When you consider all of the benefits I just mentioned, I think it’s pretty much a no-brainer. How did you get started with it? We first discussed the concepts with Sun Microsystems, as we wanted to provide a benefit to the overall NetBeans IDE from an embedded side. We created a proof of concept by plugging in our existing debuggers to the NetBeans IDE on a Windows operating system. We were fortunate to find someone who previously worked within Sun Microsystems on the NetBeans Platform, who came in on contract and gave us some one-on-one training. This was mainly because we had an aggressive schedule and wanted to be able to get up to speed faster. Any tips and tricks for others going down the same road? The mail lists are very helpful. We found many things we wanted to do being asked by others on the mailing lists. Many of the developers monitor these lists frequently, and respond more often than not in a timely fashion. The documentation suite, videos, written documents and interaction with the community are all extremely helpful in getting to the root of any matter quickly. The IDE is well organized and uses common techniques within the code base, which quickly become familiar. Other platforms treat information as job security. Some people may know, but they want you to pay for the information, in one way or another. Not so with NetBeans; everyone involved is completely open and collaborative. Any specific things that surprised you about the NetBeans Platform (in a good or bad way)? NetBeans prevents development with any form of interdependency between modules. For instance, you cannot have A->B and B->A. This really is a good thing and ensures that you break your modules up more to create a common module. The way JUnit is integrated into the IDE makes it so seamless to create your unit tests while developing the code. Source-code revision control worked quite smoothly from within the IDE. A hindrance for us is that there is no way to view a block of memory in hex form, when running under Java (using the JVM debugger). This is something often required when doing embedded development. Since we are developing code for our debug tools, we wanted to see the code blocks being transported from the IDE to the tool in hex, but could not. Anything else you'd like to share? It is great how fully featured the editor is. We are often so deep in developing what is required for the embedded side that we still discover things the editor does that we hadn’t come across. We are using the NetBeans IDE to create our own IDE, which is a completely new, yet compatible, incarnation of our IDE. The NetBeans developers at Oracle/Sun are extremely open to assist in getting value added to the current IDE, which makes our job even easier.
December 3, 2010
· 20,910 Views · 10 Likes
article thumbnail
Real-Time Charts on the Java Desktop
Devoxx, and all similar conferences, is a place where you make new discoveries, continually. One of these, in my case, at last week's Devoxx, started from a discussion with Jaroslav Bachorik from the VisualVM team. He had presented VisualVM's extensibility in a session at Devoxx. I had heard that, when creating extensions for VisualVM, one can also create new charts using VisualVM's own charting API. Jaroslav confirmed this and we created a small demo together to prove it, i.e., there's a charting API in VisualVM. Since VisualVM is based on the NetBeans Platform, I went further and included the VisualVM charts in a generic NetBeans Platform application. Then I wondered what the differences are between JFreeChart and VisualVM charts, so asked the VisualVM chart architect, Jiri Sedlacek. He sent me a very interesting answer: JFreeCharts are great for creating any kind of static graphs (typically for reports). They provide support for all types of existing chart types. The benefit of using JFreeChart is fully customizable appearance and export to various formats. The only problem of this library is that it's not primarily designed for displaying live data. You can hack it to display data in real time, but the performance is poor. That's why I've created the VisualVM charts. The primary (and so far only) goal is to provide charts optimized for displaying live data with minimal performance and memory overhead. You can easily display a fullscreen graph and it will still scroll smoothly while running and adding new values (when running on physical hardware, virtualized environment may give slightly worse results). There's a real rendering engine behind the charts which ensures that only the changed areas of the chart are repainted (no full-repaints because of a 1px change). Scrolling the chart means moving the already rendered image and only painting the newly displayed area. Last but not least, the charts are optimized for displaying over a remote X session - rendering is automatically switched to low-quality ensuring good response times and interactivity. The Tracer engine introduced in VisualVM 1.3 further improves performance of the charts. I've intensively profiled and optimized the charts to minimize the cpu cycles/memory allocations for each repaint. As of now, I believe that the VisualVM charts are the fastest real time Java charts with the lowest cpu/memory footprint. Best of all is that everything described above is in the JDK. That's because VisualVM is in the JDK. Here's a small NetBeans Platform application (though you could also use the VisualVM chart API without using the NetBeans Platform, just include these JARs on your classpath: org-netbeans-lib-profiler-charts.jar, com-sun-tools-visualvm-charts.jar, com-sun-tools-visualvm-uisupport.jar and org-netbeans-lib-profiler-ui.jar) that makes use of the VisualVM chart API outlined above: The chart that you see above is updated in real time and you can change to full screen and you can scroll through it and, at the same time, there is no lag and it is very performant. Below is all the code (from the unit test package in the VisualVM sources) that you see in the JPanel above: public class Demo extends JPanel { private static final long SLEEP_TIME = 500; private static final int VALUES_LIMIT = 150; private static final int ITEMS_COUNT = 8; private SimpleXYChartSupport support; public Demo() { createModels(); setLayout(new BorderLayout()); add(support.getChart(), BorderLayout.CENTER); } private void createModels() { SimpleXYChartDescriptor descriptor = SimpleXYChartDescriptor.decimal(0, 1000, 1000, 1d, true, VALUES_LIMIT); for (int i = 0; i < ITEMS_COUNT; i++) { descriptor.addLineFillItems("Item " + i); } descriptor.setDetailsItems(new String[]{"Detail 1", "Detail 2", "Detail 3"}); descriptor.setChartTitle("Demo Chart"); descriptor.setXAxisDescription("X Axis [time]"); descriptor.setYAxisDescription("Y Axis [units]"); support = ChartFactory.createSimpleXYChart(descriptor); new Generator(support).start(); } private static class Generator extends Thread { private SimpleXYChartSupport support; public void run() { while (true) { try { long[] values = new long[ITEMS_COUNT]; for (int i = 0; i < values.length; i++) { values[i] = (long) (1000 * Math.random()); } support.addValues(System.currentTimeMillis(), values); support.updateDetails(new String[]{1000 * Math.random() + "", 1000 * Math.random() + "", 1000 * Math.random() + ""}); Thread.sleep(SLEEP_TIME); } catch (Exception e) { e.printStackTrace(System.err); } } } private Generator(SimpleXYChartSupport support) { this.support = support; } } } Here is the related Javadoc. To get started using the VisualVM charts in your own application, read this blog, and then look in the "lib" folder of the JDK to find the JARs you will need. And then have fun with real-time data in your Java desktop applications.
November 20, 2010
· 71,789 Views
article thumbnail
Step-by-Step Instructions for Integrating DJ Native Swing into NetBeans RCP
Here's how to integrate DJ Native Swing into a NetBeans RCP application. We will create multiple operating-system specific modules, each with the JARs and supporting classes needed for the relevant operating system. Then, in a module installer, we will enable only the module that is relevant for the operating system in question. I.e., if the user is on Windows, only the Windows module will be enabled, while all other modules will be disabled. Many thanks to Aljoscha Rittner for all of the code and each of the steps below. Any errors are my own, his instructions are perfect. 1. Download DJ Native Swing. 2. Go to download.eclipse.org/eclipse/downloads/drops/R-3.6-201006080911/. There, under the heading "SWT Binary and Source", download and extract the os-specific ZIPs that you want to support. 3. Unzip your downloaded ZIPs. Rename your swt.jar in the unzipped files to the full name of the zip. For example, instead of multiple "swt.jar" files, you'll now have JAR names such as "swt-3.6-gtk-linux-x86_64.jar" and "swt-3.6-win32-win32-x86_64.jar". Because these JARs will be in the same cluster folder in the NetBeans Platform application, they will need to have different names. 4. Let's start with Linux. Put the two DJ Native Swing JARs ("DJNativeSwing.jar" and "DJNativeSwing-SWT.jar") into a NetBeans library wrapper module named "com.myapp.nativeswing.linux64". Also put the "swt-3.6-gtk-linux-x86_64.jar" into the library wrapper module, while checking the "project.xml" and making sure there's a classpath extension entry for each of the three JARs in your library wrapper module. 5. Do the same for all the operating systems you're supporting, i.e., create a new library wrapper module like the above, with the operating-system specific SWT Jar, together with the two DJ Native Swing JARs. 6. Create a new module named "DJNativeSwingAPI", with code name base "com.myapp.nativeswing.api". 7. In the above main package, create a subpackage "browser", where you'll create an API to access the different implementations: public interface Browser { public JComponent getBrowserComponent(); public void browseTo (URL url); public void dispose(); } public interface BrowserProvider { public Browser createBrowser(); } 8. Make the "browser" package public and let all the operating-system specific library wrapper modules depend on the API module. 9. In each of the operating-system specific modules, create an "impl" subpackage with the following content, here specifically for Windows 64 bit: package com.myapp.nativeswing.windows64.impl; import chrriis.dj.nativeswing.swtimpl.NativeInterface; import com.myapp.nativeswing.api.browser.Browser; import com.myapp.nativeswing.api.browser.BrowserProvider; import org.openide.util.lookup.ServiceProvider; @ServiceProvider(service = BrowserProvider.class) public class Win64BrowserProvider implements BrowserProvider { private boolean isInitialized; @Override public Browser createBrowser() { initialize(); return new Win64Browser(); } private synchronized void initialize() { if (!isInitialized) { NativeInterface.open(); isInitialized = true; } } } import chrriis.dj.nativeswing.NSComponentOptions; import chrriis.dj.nativeswing.swtimpl.components.JWebBrowser; import com.myapp.nativeswing.api.browser.Browser; import java.net.URL; import javax.swing.JComponent; class Win64Browser implements Browser { private JWebBrowser webBrowser; public Win64Browser() { //If not this, browser component creates exceptions when you move it around, //this flag is for the native peers to recreate in the new place: webBrowser = new JWebBrowser(NSComponentOptions.destroyOnFinalization()); } public JComponent getBrowserComponent() { return webBrowser; } public void browseTo(URL url) { webBrowser.navigate(url.toString()); } public void dispose() { webBrowser.disposeNativePeer(); webBrowser = null; } } 10. Copy the above two classes into all your other operating-system specific library wrapper modules. Rename the classes accordingly. 11. In the DJ Native Swing API module, create a new subpackage named "utils", with this class, which programmatically enables/disables modules using the NetBeans AutoUpdate API: import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.Set; import org.netbeans.api.autoupdate.OperationContainer; import org.netbeans.api.autoupdate.OperationContainer.OperationInfo; import org.netbeans.api.autoupdate.OperationException; import org.netbeans.api.autoupdate.OperationSupport; import org.netbeans.api.autoupdate.OperationSupport.Restarter; import org.netbeans.api.autoupdate.UpdateElement; import org.netbeans.api.autoupdate.UpdateManager; import org.netbeans.api.autoupdate.UpdateUnit; import org.openide.LifecycleManager; import org.openide.modules.ModuleInfo; import org.openide.util.Exceptions; import org.openide.util.Lookup; /** * Der ModuleHandler ist eine Hilfsklasse zum programatischen (de)aktivieren * von Modulen und der Analyse von installierten aktiven Modulen. * @author rittner */ public class ModuleHandler { private boolean restart = false; private OperationContainer oc; private Restarter restarter; private final boolean directMode; public ModuleHandler() { this (false); } public ModuleHandler(boolean directMode) { this.directMode = directMode; } /** * Gibt eine sortierte Liste der Codename-Base aller aktiven installierten * Module zurück. * * Es handelt sich dabei explizit um einen aktuellen Zwischenstand, der sich * jeder Zeit verändern kann. * @param startFilter Es werden nur die Module zurückgegeben, die mit dem Startfilter-Namen anfangen (oder null für alle) * @param includeDisabled Wenn true, werden auch alle inaktiven Module ermittelt. * @return Sortierte Liste der Codename-Base */ public List getModules(String startFilter, boolean includeDisabled) { List activatedModules = new ArrayList(); Collection lookupAll = Lookup.getDefault().lookupAll(ModuleInfo.class); for (ModuleInfo moduleInfo : lookupAll) { if (includeDisabled || moduleInfo.isEnabled()) { if (startFilter == null || moduleInfo.getCodeNameBase().startsWith(startFilter)) { activatedModules.add(moduleInfo.getCodeNameBase()); } } } Collections.sort(activatedModules); return activatedModules; } /** * Führt einen Neustart der Anwendung durch, wenn der vorherige setModulesState * ein Flag dafür gesetzt hat. mit force, kann der Restart erzwungen werden. * * Man sollte nicht davon ausgehen, dass nach dem Aufruf der Methode * zurückgekehrt wird. * @param force */ public void doRestart(boolean force) { if (force || restart) { if (oc != null && restarter != null) { try { oc.getSupport().doRestart(restarter, null); } catch (OperationException ex) { Exceptions.printStackTrace(ex); } } else { LifecycleManager.getDefault().markForRestart(); LifecycleManager.getDefault().exit(); } } } /** * Aktiviert oder deaktivert die Liste der Module * @param enable * @param codeNames * @return true, wenn ein Neustart zwingend erforderlich ist */ public boolean setModulesState (boolean enable, Set codeNames) { boolean restartFlag; if (enable) { restartFlag = setModulesEnabled(codeNames); } else { restartFlag = setModulesDisabled(codeNames); } return restart = restart || restartFlag; } private boolean setModulesDisabled(Set codeNames) { Collection toDisable = new HashSet(); List allUpdateUnits = UpdateManager.getDefault().getUpdateUnits(UpdateManager.TYPE.MODULE); for (UpdateUnit unit : allUpdateUnits) { if (unit.getInstalled() != null) { UpdateElement el = unit.getInstalled(); if (el.isEnabled()) { if (codeNames.contains(el.getCodeName())) { toDisable.add(el); } } } } if (!toDisable.isEmpty()) { oc = directMode ? OperationContainer.createForDirectDisable() : OperationContainer.createForDisable(); for (UpdateElement module : toDisable) { if (oc.canBeAdded(module.getUpdateUnit(), module)) { OperationInfo operationInfo = oc.add(module); if (operationInfo == null) { continue; } // get all module depending on this module Set requiredElements = operationInfo.getRequiredElements(); // add all of them between modules for disable oc.add(requiredElements); } } try { // get operation support for complete the disable operation OperationSupport support = oc.getSupport(); // If support is null, no element can be disabled. if ( support != null ) { restarter = support.doOperation(null); } } catch (OperationException ex) { Exceptions.printStackTrace(ex); } } return restarter != null; } private boolean setModulesEnabled(Set codeNames) { Collection toEnable = new HashSet(); List allUpdateUnits = UpdateManager.getDefault().getUpdateUnits(UpdateManager.TYPE.MODULE); for (UpdateUnit unit : allUpdateUnits) { if (unit.getInstalled() != null) { UpdateElement el = unit.getInstalled(); if (!el.isEnabled()) { if (codeNames.contains(el.getCodeName())) { toEnable.add(el); } } } } if (!toEnable.isEmpty()) { oc = OperationContainer.createForEnable(); for (UpdateElement module : toEnable) { if (oc.canBeAdded(module.getUpdateUnit(), module)) { OperationInfo operationInfo = oc.add(module); if (operationInfo == null) { continue; } // get all module depending on this module Set requiredElements = operationInfo.getRequiredElements(); // add all of them between modules for disable oc.add(requiredElements); } } try { // get operation support for complete the enable operation OperationSupport support = oc.getSupport(); if (support != null) { restarter = support.doOperation(null); } return true; } catch (OperationException ex) { Exceptions.printStackTrace(ex); } } return false; } } 12. Create a ModuleInstall class in the API module. In this class, we need to create a map, connecting all the operating systems to the related code name base of the module relevant to the specific operating system. For this, we use "os.arch" and "os.name". Then we create an enable list and a disable list for the code name base. We create two handlers, one to disable everything, the other to enable just the relevant module. public class Installer extends ModuleInstall { @Override public void restored() { Map modelMap = new HashMap(); modelMap.put("Windows.64", "com.myapp.nativeswing.windows64"); modelMap.put("Linux.64", "com.myapp.nativeswing.linux64"); String osArch = System.getProperty("os.arch"); if ("amd64".equals(osArch)) { osArch = "64"; } else { osArch = "32"; } String osName = System.getProperty("os.name"); if (osName.startsWith("Windows")) { osName = "Windows"; } if (osName.startsWith("Mac")) { osName = "Mac"; } Map osNameMap = new HashMap(); osNameMap.put("Windows", "Windows"); osNameMap.put("Linux", "Linux"); osNameMap.put("Mac", "Mac"); String toEnable = modelMap.get(osNameMap.get(osName) + "." + osArch); Set toDisable = new HashSet(modelMap.values()); if (toEnable != null) { toDisable.remove(toEnable); } ModuleHandler disabler = new ModuleHandler(true); disabler.setModulesState(false, toDisable); ModuleHandler enabler = new ModuleHandler(true); enabler.setModulesState(true, Collections.singleton(toEnable)); } } 13. Finally, create yet another module, where the TopComponent will be found that will host the browser from DJ Native Swing. So, create a new module, add a window where the browser will appear, and set a dependency on the DJ Native Swing API module. In the constructor of the window add the following: setLayout(new BorderLayout()); BrowserProvider bp = Lookup.getDefault().lookup(BrowserProvider.class); if (bp!=null){ Browser createBrowser = bp.createBrowser(); add(createBrowser.getBrowserComponent(), BorderLayout.CENTER); } 14. By default, library wrapper modules are set to "1.4" source code level and to "autoload". You will need to change "1.4" to "1.6" (since you're using annotations above). You will also need to change "autoload" to "regular", otherwise they will never be loaded, since no module depends on them. 15. On Linux, at least on Ubuntu, make sure you have done something like this: export MOZILLA_FIVE_HOME=/usr/lib/mozilla export LD_LIBRARY_PATH=$MOZILLA_FIVE_HOME On Linux (at least on Ubuntu), you also need to set an impl dependency on the "JNA" module. 16. In "platform.properties", add this line: run.args.extra=-J-Dsun.awt.disableMixing=true Hurray, you're done, once you run the application: Note: above I followed these instructions to remove the tab in the browser window.
October 18, 2010
· 52,042 Views
article thumbnail
How to Create JavaHelp in a Mavenized NetBeans Platform Application
There isn't a JavaHelp template for Maven-based NetBeans Platform modules, hence you need to set up JavaHelp yourself. It's a bit tricky, involving several different parts that can go wrong easily (which is why a JavaHelp template is so handy). Here's instructions on how to set up JavaHelp in your Maven-based NetBeans Platform modules. Do the following: In each module that needs to provide a JavaHelp set, add this line to the manifest: OpenIDE-Module-Requires: org.netbeans.api.javahelp.Help In the POM of the container project (i.e., NOT the application project and NOT a functionality module project), add the "dependencies" section in the definition of the "org.codehaus.mojo", while setting the "version" to 3.0: org.codehaus.mojo nbm-maven-plugin 3.0 true javax.help javahelp 2.0.02 ${brandingToken} foobar Note that the "version" is set to 3.0. I could not get JavaHelp to work for 3.1 or 3.2 (the default in 6.9+) and had to revert to 3.0. Maybe someone can correct me on this point somehow. Make sure that the POMs in the other projects (i.e., application project and functionality module projects) do not have their own definition of "org.codehaus.mojo". I.e., the container project should handle this definition for the whole application. You have now configured the application to use JavaHelp and have indicated each module that will provide JavaHelp. In each of those modules, you now need to provide JavaHelp content. The simplest approach for this is to create an Ant-based NetBeans Platform module. Then, use the wizard available for Ant-based NetBeans Platform projects for the creation of JavaHelp sets. Then copy the files that are generated into your Maven-based NetBeans Platform project: Note the following in the screenshot above. The "resources" folder contains the "module1-helpset.xml" file, which references the files in the "src/main/javahelp" folder by means of having the following content: And note that the "layer.xml" file above has this folder added: The folder "src/main/javahelp" is new, I created that myself, by copying that folder from the Ant-based NetBeans Platform module. That's the place where you will now create all your help topics within the Mavenized application. The Map file lists the identifying keys of the help topics, the TOC lists those keys that define the table of contents, and the Index does the same to define the index of the helpset. That's all you need. Now you have JavaHelp working in your Mavenized NetBeans Platform application:
September 25, 2010
· 13,454 Views
article thumbnail
How to Create a Custom Project Type in a Mavenized NetBeans Platform Application
Let's take the NetBeans Project Type Module Tutorial and port it to a Maven-based NetBeans Platform application. In contrast to the Hello World Maven NetBeans RCP article, we'll now use the NetBeans IDE's tooling, since the aforementioned article has laid the foundation that we need for using the NetBeans IDE's Maven tooling intelligently. Take the following steps: Create the project as follows: Right-click on the node with the orange icon ("NetBeans Platform based application"), which is the application node, and choose "Build with Dependencies". Right-click the application node and choose Run. Here's your application: Copy the three Java classes from the "NetBeans Project Type Module Tutorial" into "TextAnalyzerProjectType NetBeans Module", which is the functionality module. Specifically, put them into the main package within "Source Packages", which is "com.text.analyzer". Copy the two icons into "Other Sources", specifically into "src/main/resources/com.text.analyzer". Make sure that you change the location of the icons in the two Java classes where they are used, otherwise they will not be found when you run the application. In the POM file of the functionality module, define the "dependencies" section as follows: org.netbeans.api org-openide-util ${netbeans.version} org.netbeans.api org-netbeans-modules-projectuiapi RELEASE691 org.netbeans.api org-openide-util-lookup RELEASE691 org.netbeans.api org-netbeans-modules-projectapi RELEASE691 org.netbeans.api org-openide-filesystems RELEASE691 org.netbeans.api org-openide-loaders RELEASE691 org.netbeans.api org-openide-nodes RELEASE691 In the POM file of the application node, add this dependency: org.netbeans.modules org-netbeans-modules-projectui RELEASE691 The above is needed because we're depending on the Project UI API (see step 5 above). In that particular API, the "OpenIDE-Module-Needs" key is used in the manifest to specify that "ActionsFactory", "OpenProjectsTrampoline", and "ProjectChooserFactory" are needed by this module. Therefore, a module that implements and provides those classes is required, which is the Project UI module, which implements Project UI API. To ensure that that module will be available at runtime, you specify the dependency above as described, in the POM file of the application node. For details, go here. Repeat steps 2 and 3 above. Then open the Favorites window and browse to a folder that has a subfolder named "texts". Right-click on the folder that has a subfolder named "texts" and then click "Open Project". Here's your application, with the project opened: Congrats, you've now ported the sample to a Maven based NetBeans Platform application.
September 24, 2010
· 15,450 Views
article thumbnail
Let's Create... Our Own SQL Editor
Isn't it time you gained full control of your SQL work environment? Stop being limited by the tools foisted upon you and start creating your own. Not hard at all, either. Here's a complete tutorial for creating your very own SQL editor, which will look like this: OK. Now, let's create it from scratch. Start up NetBeans IDE and use this template to create a basis for your application. Just click through it and you'll have new folders and files on disk that represent your project: When you've clicked Next above, you'll be able to provide the name of your project: And when you click Finish, the Projects window will show you your application structure: You've now got a basic application that includes all the infrastructure you need (a module system, window system, file system, actions system, and more), without any content. Let's now add the content. Now right-click the "SQLEditor" node above (i.e., the orange icon) and choose Properties. In the Project Properties dialog, expand the "java" node and then include the SQL Editor: Click "Resolve" above and the IDE will include all the related modules. I.e., the SQL Editor module depends on other modules. Via the "Resolve" button, those dependencies will be identified and registered in your project. Next, let's include support for Java DB: Click "Resolve" again. Hurray, we're done. All the functionality for our own SQL editor is now available in our application. Now we'll add a new module, just so that we can perform a few tweaks to our application. In other words, this will be a branding module. Right-click the "Modules" node and choose "Add New": Name it something, such as "SQLBranding": Provide a unique identifier for your new module and make sure to include a layer.xml file, which you'll use to mask out the default menus and toolbars you don't need in your application: Click Finish above. Then right-click on the main package that is created in the module and choose New | Other. There you'll be able to create a new Module Install class, which will initialize the module when the application starts up: What we want is to force the Services window in the application (i.e., this is a window in NetBeans IDE for working with databases) to open when the application starts. So, we will provide code in the Module Install class (which you created above) for finding that window and opening it. The code we will need comes from the Window System API. Right-click the Libraries node in the module, as shown below, and choose "Add Module Dependency": Then browse to Window System API and click OK: Tip: In the Projects window, right-click the module's "Libraries" node. Choose "Add Dependency" and set a dependency on the "Window System API". That's what we need to use the window system code in the snippet below: Now, in the Module Install class, provide the following code: public class Installer extends ModuleInstall { @Override public void restored() { WindowManager.getDefault().invokeWhenUIReady( new Runnable() { @Override public void run() { TopComponent svcWindow = WindowManager.getDefault(). findTopComponent("services"); svcWindow.open(); svcWindow.requestActive(); } }); } } Now the window we need will be forced to open when the application starts. Let's turn to some other ancillary matters now. We can change the default splash screen, via "Branding", which is a menu item that you see when you right-click on the application's node in the Projects window, producing the Branding Editor below: And we can search all the strings in the modules that come from the NetBeans Platform, so that we can change the string "Services" to "Databases", for example. Or to some other custom string. You can also hide the menu items and toolbar buttons that you don't need and perform similar wrap-up tasks to really customize the application to your specific business needs. Let's now, just for fun, also include a file browser in our application. So, back in the Project Properties dialog of your application, choose Favorites under the "platform" node. While you're there, also enable the two AutoUpdate modules, so that the end user will be able to install plugins (i.e., new features and patches) that you or the community of your SQL editor will provide: The application is now complete. Let's create a ZIP distribution for our end users, while noticing we can also create a Mac distribution or one for web starting the application: After doing the above, the Files window shows your new ZIP distribution: If you prefer, you can also create an installer for your application: Once the application is unzipped or installed, click the launcher in the bin folder. Then you'll have the application with which this article started. Look in the Tools menu and, guess what? You find that you have a "Plugins" menu item, enabling extensions (i.e., features and patches) to be installed into the application. Many thanks to Tim Sparg from CoreFreight in Johannesburg for inspiring this article.
September 4, 2010
· 24,439 Views · 1 Like
article thumbnail
Interview: Music Composer on the NetBeans Platform
Steven Yi (pictured right) is a programmer and composer living in Rochester, NY. He studied music composition in college and became a programmer afterwards. He started off as a Flash and server side developer (which he did for about 7 years), and has spent the past few years at his current company doing mobile development with J2ME, Android, and iPhone, as well as server-side development with Spring, Hibernate, etc. He started learning and using Java and Swing for personal work in 2000 and has been using it since then for the development of blue, the focus of the interview that follows below. In the interview, Steven talks about the "blue" music composer, how it works, and how the NetBeans Platform and Python form the basis of this cool open-sourced Java music composer. What's "blue"? blue is a music composition environment I started in the fall of 2000. It was actually my very first Java program! At the time, I had started using the music software Csound (http://www.csounds.com) to compose, but found it slow to work with when it came to accomplishing what I was interested in musically. I had the idea to create a simple program that would have a timeline and the ability to scale musical score material in time. Fast forward many years later: in trying to solve other musical problems, and responding to feedback from the community of users, I've expanded blue's features a great deal. It now includes things like a mixer and effects system, a GUI builder tool for creating synthesizer interfaces, embedded Jython processing of musical scripts, and more. It's been quite satisfying to create a tool that can express my musical interests and to find a community of users who have found value in this program for their own musical work. Some screenshots: The Orchestra manager shows a BlueSynthBuilder instrument being edited. The "Reson 6" instrument is shown in edit mode. The BSB Object Properties panel shows the properties for the selected knob: The Score timeline shows a project using multiple parameter automations. The values automated include things like volume, panning, and a time pointer for a phase-vocoder instrument. All BlueSynthBuilder instruments, Effects, and the Mixer volume sliders can be automated: The Score timeline showing the author's composition "Reminiscences". The timeline shows multiple Python SoundObjects used. The SoundObject Editor shows the editor for the selected SoundObject in the timeline. The SoundObject Properties panel shows different properties for the selected SoundObject: The Score timeline showing a Tracker SoundObject being used. The timeline is configured to snap at every 4 beats and the time bar has been configured to show in numbers rather than time: The Score timeline showing a PianoRoll SoundObject being used. The PianoRoll is unique in that it is microtonal, meaning it can adapt the number of steps per "octave", depending on the values configured from a tuning file. In this screenshot, the scale loaded was a Bohlen-Pierce scale, which has 13-tones per tritave (octave and a half): The blue Mixer is shown docked into the bottom bar and in an open state. The interfaces for user-created Chorus and Reverb effects are shown. The interfaces were created using the same GUI builder tool that is found in the BlueSynthBuilder instrument: It's got a very special appearance. How did that come about? blue's custom look and feel started off one day when I was using my Palm PDA. I remember thinking that I enjoyed the look of the device with the backlight on, and so I wanted to recreate that kind of look for my program. Later, I modified the color scheme to tone it down in some ways, but I also introduced more colors than white and cyan to highlight secondary and tertiary features. Maybe now it is now more like Tron than it is like Palm. :) Overall, I enjoy the darker look of the application when I'm working on music. I tend to work on music when I have free time, and that is usually only late at night—I've found having a darker screen has been easier on my eyes. Also, if anyone was wondering, yes, blue is my favorite color. The blue look and feel is encapsulated in a module named "blue-plaf" and is available in the "blue" Mercurial repository (http://bluemusic.hg.sourceforge.net/hgweb/bluemusic/blue). The look and feel is quite hacked up (redoing it properly has been another item on my todo list), but it can be dropped into another application and it should work, as shown below with the CRUD Sample (which can be created from a tutorial found here): Can you explain how blue's timeline works? blue has a concept of SoundLayers and SoundObjects. SoundObjects are objects that primarily produce notes and have a start and duration. There are many different types of SoundObjects in blue and each has an editor (viewed in the SoundObject Editor TopComponent when a SoundObject is selected), and a BarRenderer, which is used to draw the content area of the bar on the timeline. A PolyObject is a special SoundObject. It consists of SoundLayers, which contain SoundObjects. The root timeline is itself just a PolyObject that you can add as many layers to as you like. You can also group individual SoundObjects into their own PolyObjects, and then use the resulting PolyObjects just like any other SoundObject on the timeline. If you double-click a PolyObject, the timeline is then reset with the timeline of the PolyObject you selected. As a result, PolyObjects allow timelines to be embedded within other timelines. If you think about how music is grouped into motives, phrases, sections, and even larger groupings, you can see how PolyObjects might represent these kinds of musical abstractions. For the component design, the ScoreTopComponent starts off with a JSplitPane to split between a SoundLayerListPanel on the left and a JScrollPane on the right. The JScrollPane has a ScoreTimeCanvas (the main timeline) in the main viewPort's view, a panel with the the time bar and tempo editor in the column header, and the corner is used to open up an extra panel to modify properties for the timeline. The JScrollPane has customized JScrollBars used to add the ± buttons that perform zooming on the timeline. There are a number of other features involved that are implemented amongst a number of classes, but the details of how viewPorts are synchronized (among other things) may be a bit too technical to discuss here. For those who are interested, the code can be viewed within the blue.ui.core.score package within the blue-ui-core module. How did blue come to find itself atop the NetBeans Platform? I first started to be interested in NetBeans IDE around the time 4.1 came out, but didn't really get into using it until the release of 5.0. At that time, I had hand-written Swing components for about 4-5 years (I don't really remember when 5.0 was released), and I found Matisse to be quite nice and began using it here and there. I had looked at the NetBeans Platform as an RCP at that time, but found it to be quite a bit to understand. However, I still kept it on my radar. Around the time 6.0 or 6.5 came out, I started to reconsider migrating to the NetBeans Platform once again. By this time, I had moved over to using NetBeans IDE full time for blue development and had been using NetBeans IDE more in general—particularly Java Web development and Ruby on Rails. One of the biggest things I found attractive about NetBeans IDE is its windowing system... and the things I read about in the platform development articles I'd seen online made me curious once again to see what the NetBeans Platform offered. I still felt that there was going to be a big learning curve to learn the NetBeans Platform, but the NetBeans Platform tutorials online were really quite helpful, as were the members of the NetBeans Platform mailing list, and there were also many more books available to help me get started. I think I ultimately spent about 6-8 months migrating blue to using the NetBeans Platform. Granted, it was a busy time in my life and I was working on this only in my spare time, so I think in the end it was a reasonable amount of time. Users have been very positive about the new blue interface and application as a whole, and I think it has been worth spending the time to use the NetBeans Platform. blue's window layout is quite unexpected for a NetBeans Platform application. By the time I had started migrating blue to the NetBeans Platform, the application was already some 7-8 years old. The interface I designed for blue in pure Swing was influenced by my experiences in using Flash, looking at other music composition environments (Digital Audio Workstations and Sequencing Programs), and evaluating the different aspects of working with Csound. Mapping the components from the Swing-based application to the NetBeans Platform was a little tricky in that I couldn't quite get the exact same design of panels as I had in pure Swing. In the end, I tried to think about where most of the components resided physically, and created TopComponents and placed them in the center, left, right, or bottom parts of the main window. I kept some of the dialogs from the old codebase as-is, but I migrated others to be TopComponents so that they could be docked, opened, or dragged out into a dialog as the user wished. In the end, the GUI is different and took a little getting used to after years of using and building the old interface, but I quickly adjusted to the changes and I think there is much greater consistency and usability now. The users have responded very positively to the general polish of the application and to being able to customize their environment. I myself have very much enjoyed being able to dock all of the windows as well as using full-screen mode, especially when I am on my netbook and composing. Excellent! What features of the NetBeans Platform are you using and what do you find to be most useful? Currently, I am using only a very small part of the NetBeans Platform. By the time I started to move my code to the NetBeans Platform, the codebase was already some 7 or 8 years old. I took the approach recommended to me on the mailing list and started off small, focusing primarily on migrating my project to using the Windows System API, the Options API, and a few other utility API's like IO and Dialogs. Having an old codebase, I found that I spent most of my time during migration just reorganizing my UI into TopComponents and working out communications between the components. I also spent time looking at API's that I had developed myself and seeing which ones could be replaced with API's provided by the NetBeans Platform. At this time, the application is still using a number of API's I wrote from the old codebase, but over time I would like to migrate more of the appplication to use the Nodes and Visual Library API's. I think migrating a codebase of this size in phases really worked out well. In the first phase, I was able to take advantage of the Window System API and have a very visible result on the application and gained a lot for usability. Also, a big part of the migration involved moving the codebase from a monolithic source tree and partitioning it into logical modules. I think there really is a great deal of benefit to working with a codebase with modular design, and that too is a very positive result of working with the NetBeans Platform. Please say something about how Jython relates to this application, how you are using it (what the benefits are), and your general opinions on Jython. I have had a Python SoundObject in blue for quite some time—I think since 2002. For me, it is one of the most important tools in blue when it comes to accomplishing what I want musically. With computer music, we have a lot of tools for what I call Common Practice computer music: PianoRolls, Pattern Editors, and Notation Objects. For computer musicians who are interested in Uncommon Practice music, the ability to use a scripting language opens up a number of ways to express musical ideas that cannot be easily conveyed using those other tools. In blue, Jython is primarily used to allow users to write scripts that will generate notes. For myself, I use Python scripts to model orchestral composition, creating Performer and PerformerGroup objects that I write in Python. I also write performance functions, usually per-project, to perform different musical material in different ways. Other users have used Python scripts in exploring things like algorithmic composition and genetic algorithms in their work. A blue project can contain any number of Python objects. The score generated by each Python object is translated and scaled in time by moving and resizing the SoundObject in the timeline. This allows a user who may want to use scripting to create musical material to also take advantage of blue's timeline to organize how the different musical objects will work together. One of the things I most appreciate about Jython (and scripting languages on the JVM in general) is that it is embeddable within a Java application. By packaging and embedding the Jython interpreter within the blue application, users can rest assured that the Python scripts they write can be interpreted anywhere that blue is installed. It's an extra assurance that their musical projects will be long-lasting, but they can still take advantage of a full programming language like Python in their work. Overall, I think that Jython is a fine piece of software and I hope that it will continue to grow and develop for years to come. Is the application open source and are you looking for code contributions and, if so, in which areas? Yes, the application is available under the GPL v2 license, and the source code can be viewed from the Mercurial repository on SourceForge at http://bluemusic.hg.sourceforge.net/hgweb/bluemusic/blue/. I am a strong proponent of open source, especially for creative work. In the same way that we can today look at and study musical works by composers of the past (like Josquin and Bach), I would like to imagine that the work composers and other artists are now creating with computers will also be open and available for study in the future. I believe that using open source software for creative work greatly helps in making musical projects available for the years ahead. I have done most of the development of blue myself, and over the years I've certainly built up a long list of things that I would like to implement. Users have also made wonderful feature requests that I would love to see in the program—but unfortunately, there are only so many hours in the day. It would certainly be nice to have others contributing code! Beyond new features, there are a number of infrastructural things that would be nice to address. The codebase is many years old, and while the application has been refactored multiple times over its lifetime, there are still some areas of the application that could be much more cleanly implemented. Also, in moving over to the NetBeans Platforms, I only really took the first steps. There are a number of components within the application that could probably be better served by migrating to using more of the NetBeans API's. For internal work, things like modifying the timeline to implement zooming to use Graphics2d and transforms, implementing a better waveform renderer for audio files, and further enhancing the instrument GUI builder are all things I'd like to see. I'd also love to get help in migrating all of the tables and trees to using the Nodes API, something that I have not yet had the time to do. It would also be nice to get the manual (currently in HTML and PDF, generated from DocBook) integrated into the application as JavaHelp, but this is another thing that I have had to postpone due to lack of time. For features, some interesting things I'd love to see are a Notation SoundObject, a separate graphical instrument builder using the Visual Library API, and a Sampler instrument. There's also a sound drawing SoundObject, enhancements to existing SoundObjects, and more I'd love to see moving forward. Maybe someone will find these kinds of things interesting and will take a look at blue's code sometime! Thanks Steven and happy music making with blue!
May 25, 2010
· 17,888 Views
article thumbnail
Complete List of Macro Keywords for the NetBeans Java Editor
In NetBeans IDE's Java editor, you can create macros by clicking the "Start Macro Recording" button, performing some actions you'd like to record, then clicking the "Stop Macro Recording" button. The Macro Editor then pops up and you can finetune the macro and also assign a keyboard shortcut to it. (You can also edit macros in the Options window, in the Editor | Macros tab.) A special macro syntax is used to define these macros. For example, if you want to clear the current line in the editor from the cursor, your macro definition would be as follows: selection-end-line remove-selection Then you could assign "Ctrl+L" as the keyboard shortcut for this macro. Whenever you'd then press that key combination, the whole line, from the position of the cursor, would be deleted. But the only way for the syntax to be useful is for it to be made publicly available. I've seen in various places on-line that people are complaining about a lack of documentation in this area. I asked the developers from the NetBeans Java editor team and their advice was: "it should not be that hard to create an action, which will get EditorKit from the JEditorPane in an opened editor, call EK.getActions() and dump Action.NAME property of each action to System.out". That's what I did (together with Action.SHORT_DESCRIPTION) and here is the result: abbrev-debug-line -- Debug Filename and Line Number adjust-caret-bottom -- Move Insertion Point to Bottom adjust-caret-center -- Move Insertion Point to Center adjust-caret-top -- Move Insertion Point to Top adjust-window-bottom -- Scroll Insertion Point to Bottom adjust-window-center -- Scroll Insertion Point to Center adjust-window-top -- Scroll Insertion Point to Top all-completion-show -- Show All Code Completion Popup annotations-cycling -- Annotations Cycling beep -- Beep build-popup-menu -- Build Popup Menu build-tool-tip -- Build Tool Tip caret-backward -- Insertion Point Backward caret-begin -- Insertion Point to Beginning of Document caret-begin-line -- Insertion Point to Beginning of Text on Line caret-begin-word -- Insertion Point to Beginning of Word caret-down -- Insertion Point Down caret-end -- Insertion Point to End of Document caret-end-line -- Insertion Point to End of Line caret-end-word -- Insertion Point to End of Word caret-forward -- Insertion Point Forward caret-line-first-column -- Insertion Point to Beginning of Line caret-next-word -- caret-next-word caret-previous-word -- caret-previous-word caret-up -- Insertion Point Up collapse-all-code-block-folds -- Collapse All Java Code collapse-all-folds -- Collapse All collapse-all-javadoc-folds -- Collapse All Javadoc collapse-fold -- Collapse Fold comment -- Comment complete-line -- Complete Line complete-line-newline -- Complete Line and Create New Line completion-show -- Show Code Completion Popup copy-selection-else-line-down -- Copy Selection else Line down copy-selection-else-line-up -- Copy Selection else Line up copy-to-clipboard -- Copy cut-to-clipboard -- Cut cut-to-line-begin -- Cut from Insertion Point to Line Begining cut-to-line-end -- Cut from Insertion Point to Line End default-typed -- Default Typed delete-next -- Delete Next Character delete-previous -- Delete Previous Character documentation-show -- Show Documentation Popup dump-view-hierarchy -- Dump View Hierarchy expand-all-code-block-folds -- Expand All Java Code expand-all-folds -- Expand All expand-all-javadoc-folds -- Expand All Javadoc expand-fold -- Expand Fold fast-import -- Fast Import find-next -- Find Next Occurrence find-previous -- Find Previous Occurrence find-selection -- Find Selection first-non-white -- Go to First Non-whitespace Char fix-imports -- Fix Imports format -- Format generate-code -- Insert Code generate-fold-popup -- Generate Fold Popup generate-goto-popup -- Generate Goto Popup generate-gutter-popup -- Margin goto -- Go to Line... goto-declaration -- Go to Declaration goto-help -- Go to Javadoc goto-implementation -- Go to Implementation goto-source -- Go to Source goto-super-implementation -- Go to Super Implementation in-place-refactoring -- Instant Rename incremental-search-backward -- Incremental Search Backward incremental-search-forward -- Incremental Search Forward insert-break -- Insert Newline insert-date-time -- Insert Current Date and Time insert-tab -- Insert Tab introduce-constant -- Introduce Constant... introduce-field -- Introduce Field... introduce-method -- Introduce Method... introduce-variable -- Introduce Variable... java-next-marked-occurrence -- Navigate to Next Occurrence java-prev-marked-occurrence -- Navigate to Previous Occurrence jump-list-last-edit -- Last edit jump-list-next -- Forward jump-list-prev -- Back last-non-white -- Go to Last Non-whitespace Char make-getter -- Replace Variable With its Getter make-is -- Replace Variable With its is* Method make-setter -- Replace Variable With its Setter match-brace -- Insertion Point to Matching Brace move-selection-else-line-down -- Move Selection else Line down move-selection-else-line-up -- Move Selection else Line up org.openide.actions.PopupAction -- Show Popup Menu page-down -- Page Down page-up -- Page Up paste-formated -- Paste Formatted paste-from-clipboard -- Paste redo -- Redo reindent-line -- Re-indent Current Line or Selection remove-line -- Delete Line remove-line-begin -- Delete Preceding Characters in Line remove-selection -- Delete Selection remove-tab -- Delete Tab remove-trailing-spaces -- Remove Trailing Spaces remove-word-next -- remove-word-next remove-word-previous -- remove-word-previous replace -- Replace run-macro -- Run Macro scroll-down -- Scroll Down scroll-up -- Scroll Up select-all -- Select All select-element-next -- Select Next Element select-element-previous -- Select Previous Element select-identifier -- Select Identifier select-line -- Select Line select-next-parameter -- Select Next Parameter select-word -- Select Word selection-backward -- Extend Selection Backward selection-begin -- Extend Selection to Beginning of Document selection-begin-line -- Extend Selection to Beginning of Text on Line selection-begin-word -- Extend Selection to Beginning of Word selection-down -- Extend Selection Down selection-end -- Extend Selection to End of Document selection-end-line -- Extend Selection to End of Line selection-end-word -- Extend Selection to End of Word selection-first-non-white -- Extend Selection to First Non-whitespace Char selection-forward -- Extend Selection Forward selection-last-non-white -- Extend Selection to Last Non-whitespace Char selection-line-first-column -- Extend Selection to Beginning of Line selection-match-brace -- Extend Selection to Matching Brace selection-next-word -- selection-next-word selection-page-down -- Extend Selection to Next Page selection-page-up -- Extend Selection to Previous Page selection-previous-word -- selection-previous-word selection-up -- Extend Selection Up shift-line-left -- Shift Line Left shift-line-right -- Shift Line Right split-line -- Split Line start-macro-recording -- Start Macro Recording start-new-line -- Start New Line stop-macro-recording -- Stop Macro Recording switch-case -- Switch Case to-lower-case -- To Lowercase to-upper-case -- To Uppercase toggle-case-identifier-begin -- Switch Capitalization of Identifier toggle-comment -- Toggle Comment toggle-highlight-search -- Toggle Highlight Search toggle-line-numbers -- Toggle Line Numbers toggle-non-printable-characters -- Toggle Non-printable Characters toggle-toolbar -- Toggle Toolbar toggle-typing-mode -- Toggle Typing Mode tooltip-show -- Show Code Completion Tip Popup uncomment -- Uncomment undo -- Undo word-match-next -- Next Matching Word word-match-prev -- Previous Matching Word Now that this list is public, I am looking forward to many new and interesting (and useful) macros being published (maybe even here on NetBeans Zone).
March 31, 2010
· 21,110 Views
article thumbnail
Top 10 Interesting NetBeans IDE Java Shortcuts I Never Knew Existed
I'm working on updating the NetBeans IDE Keyboard Shortcut Card (which you can always find under the "Help" menu in the IDE) and have learned about a lot of shortcuts I never knew about before. Here's a grab bag of things I have added to the shortcut card (some new, some old that hadn't been included before) that you might find interesting too. Type "fcom" (without the quotes, same as all the rest below) and then press Tab. You now have this, i.e., a brand new code fold: // // Type "bcom" and then press Tab to create the start of a new set of comments in your code: /**/ Type "runn" and press Tab and you'll have all of this: Runnable runnable = new Runnable() { public void run() { } }; If I have this: String something = ""; ...and then below that type "forst" and press Tab, I now have this: String something = ""; for (StringTokenizer stringTokenizer = new StringTokenizer(something); stringTokenizer.hasMoreTokens();) { String token = stringTokenizer.nextToken(); } Also, experiment with "forc", "fore", "fori", "forl", and "forv"! I always knew that "sout" turns into "System.out.println("");" but did you know that (again assuming you first have a string something like above) if you type "soutv" you end up with this: System.out.println("something = " + something); Thanks Tom Wheeler for this tip. Next, here are the new shortcuts that are new from NetBeans IDE 6.9 onwards: as - assert=true; su - super db - double sh - short na - native tr - transient vo - volatile I knew that "ifelse" would resolve to an if/else block. But did you know that if you don't need an 'else', you can simply type "iff", press Tab, and then end up with this: if (exp) { } From NetBeans IDE 6.9 onwards, the "sw" shortcut expands to the following: switch (var) { case val: break; default: throw new AssertionError(); } If you're using while loops, experiment with "whileit", "whilen", and "whilexp". Always remember these: "im" expands to "implements; "ex" to "extends". Other tips along these lines are more than welcome here on NetBeans Zone!
February 19, 2010
· 97,900 Views · 4 Likes
article thumbnail
Interview: Intelligence Gathering Software on the NetBeans Platform
Chris Bohme is the chief software architect at Pinkmatter Solutions – a small, specialized software development company in South Africa. Pinkmatter has been working with a company called Paterva for the past few years to build Maltego - a tool for data visualization, reconnaissance and intelligence gathering. Maltego is used by law enforcement and intelligence agencies, network security professionals and large corporates to discover and analyze information. In a nutshell, how does Maltego work? Maltego models information as entities (e.g., persons, e-mail addresses) and relationships between them. Relationships are discovered by running pluggable functions (called transforms) on the entities. For example, when running a social network transform on my e-mail address, one would discover my Facebook and LinkedIn profiles. Out of the box, Maltego ships with over 150 transforms that mainly relate to open source intelligence. However, an organization using Maltego user can easily create their own transforms that run on their internal data. The concept of transforms makes data gathering very quick and easy which is one of the aspects that sets it apart from some of its competitors like Analyst Notebook, which has been the de-facto tool for investigation and intelligence analysis. Why and how did you choose to use the NetBeans Platform as the basis of this application? We have actually been using the NetBeans Platform at Pinkmatter since 2002, back in the days of NetBeans 3.2, when the NetBeans Platform was not really separate from the IDE and the only real documentation for NetBeans Platform users was the source code. Back then Pinkmatter was building a network security management tool we called “Palantir”, which was never released but which would later form the basis framework for Maltego. (Ironically one of Maltego’s competitors is now made by a company called Palantir Tech.) I was using Forte (Sun’s customized version of NetBeans) as my IDE for Java development and realized that I would need very similar features in Palantir – global selection management, runtime composition (i.e., modules), copy/paste/undo/redo, auto-update, property grid, window manager, system palette etc. So I began reading through the sources and building Palantir as a NetBeans module while trying to remove as much of the IDE parts as possible. I immediately fell in love with its design and complexity (yes, complexity – no matter how long you have been using the NetBeans Platform, there is something new you can learn every day) – but there was a definite beauty to it and I knew that following its architecture guidelines would save me from the certain “spaghetti-death” to which all large UI applications I had seen thus far were doomed from the start. What are the main advantages of the NetBeans Platform to you? On a personal level, working with the NetBeans Platform early on in my developer career has shaped my mindset around application design. As such, the NetBeans Platform source code was one of my most influential teachers when it comes to API design and architecture of large complex applications. I started looking for similar patterns in the frameworks I was building using other programming languages and it has helped me identify designs that are “right” and those that are “wrong”. (When it comes to API design I believe that “truth, like beauty, is not a matter of opinion” :-) ) On the level of Maltego, I think the benefits are fairly obvious – there is a platform that comes with lots “free stuff” right out of the box. And hey, the best thing is, someone else improves, fixes and supports all this free stuff while you can focus on your specific problem domain. If I were to rephrase the question to read “what in the NetBeans Platform couldn’t I live without?” – well, it would be the features related to runtime composition. The fact that components can be registered declaratively (for example in layer files) and are added as modules that get loaded at runtime shapes the overall design and maintainability and is something a modern application cannot do without. As Maltego matures, instead of removing the dependency on some NetBeans APIs and replacing them with our own, we tend to use more and more of what the NetBeans Platform (and even the IDE) has to offer. This is a very good indication to me that a) NetBeans Platform was the right choice to build Maltego on and b) that the evolution of the NetBeans Platform is in line with the needs of its users (well, at least for us). Continue to part 2 of this interview... Were there things that pleasantly surprised you while working with the NetBeans Platform? There were many.... but let’s start with backward compatibility. A lot of the Palantir code from 2002 can still run in NetBeans 6 – that is 3 major versions and 8 years later! – not a small feat to achieve for an API designer. As another example, for the upcoming 3.0 of Maltego we redesigned our underlying information model to allow a user to model entities with a multitude of properties. We needed to allow the user to configure these using many kinds of weird and wonderful type editors... and actually the good old PropertySheet works well for that, can be highly customized and takes up very little screen real estate. In general I am amazed every time how efficiently NetBeans can handle so many modules (and merged layer files)! What could be improved? Well, I have this gripe with the wizard framework. Although sufficient for the IDE, there is a lot to be desired from wizards when used in other applications. How about re-using wizard panels for editing something in a dialog (panels as tabbed panes for example)? Or quick and dirty mechanisms to disable the Cancel button or intercept it to cancel a background thread? (I know, I know, stop complaining, Chris, and contribute something of that sort – yes... one day when Maltego has grown up and I am no longer working nights.) But in the end I think that in spite of all the great efforts that have been made, documentation is still a limiting factor when it comes to the adoption and effective use of the NetBeans Platform. There are a number of really good books, blogs and tutorials, however, I feel there is a need for something like “An Architect’s Guide for Designing Applications for the NetBeans Platform” – something that focuses more on core design decisions that have to be made before getting started. For example, “how is your global selection management to work?” and “what mechanisms does the NetBeans Platform provide for that?” Any tips or tricks for other NetBeans Platform developers? Read every book that has ever been published about the NetBeans Platform. Read and take note of tips published on blogs – you might not need them today but in 6 months time you will remember that there is a smart way to do something. I check planetnetbeans.org every day for interesting articles. Keep a copy of the NetBeans Platform sources around (you can download them in a handy ZIP file and don’t even have to do a checkout). Whenever there is something that you don’t understand or that seemingly does not work, grep the sources for the relevant classes. Don’t feel you have to make use of NetBeans APIs all the time. Sometimes it makes sense to just use a JTable instead of creating a Node implementation with OutlineView. As that component gets more full featured, you can always refactor it and replace it with a suitable View. The default lookup is your friend! Finish this sentence: "If I had known..." Actually, if I had known that it is possible (and easy) to replace the default implementation of ContextGlobalProvider I would have more hair left on my head! (Before I read Tim’s blog entry, activating a TopComponent would amount to changing the global selection – something that is not valid for all applications – and boy did I struggle...) What's the future of the application? We are close to releasing Maltego 3.0 – the next big milestone in the life of our beloved baby. This release brings many new features with it, not least of all a slick new look (thanks to some of the beautiful work done by the likes of Gunnar Reinseth, Mikael Tollefsen and Kirill Grouchnikov): Our ultimate vision is to evolve Maltego into an autonomous information monitoring system – something like an IDS (intrusion detection system), but for information. The threats to organizations (or governments) on the internet are no longer constrained to attacks on their network infrastructure (the origin of the term IDS) but information about them, their competitors or employees floating around on the internet can seriously harm them. Think of it as a highly customizable, intelligent Google Alert, which is fed from the internet as well as private, internal databases. Subsequent releases will bring us closer to that vision with geo-spatial data, time base analyses and live, real time data feeds.
February 15, 2010
· 38,861 Views
article thumbnail
How to Create a Swing CRUD Application on NetBeans Platform 6.8
this article shows you how to integrate a java db database into a netbeans platform application. we start by exploring a java db database, from which we create entity classes. next, we wrap the entity classes into a module, together with modules for the related jpa jars. note: these instructions are not applicable to java db only. rather, they are relevant to any relational database, such as oracle or mysql. several applications on the netbeans platform, many of which are listed here , use these databases too. java db was chosen for this article because it is easiest to get started with, since it comes with the jdk. once the above modules are part of our application, we create a new module that provides the user interface for our application. the new module gives the user a tree hierarchy showing data from the database. we then create another module that lets the user edit the data displayed by the first module. by separating the viewer from the editor in distinct modules, we will enable the user to install a different editor for the same viewer, since different editors could be created by external vendors, some commercially and some for free. it is this flexibility that the modular architecture of the netbeans platform makes possible. when we have a module for our editor, we begin adding crud functionality. first, the "r", standing for "read", is handled by the viewer described above. next, the "u" for "update" is handled, followed by the "c" for "create", and the "d" for "delete". at the end of the article, you will have learned about a range of netbeans platform features that help you in creating applications of this kind. for example, you will have learned about the undoredo.manager and the explorermanager , as well as netbeans platform swing components, such as topcomponent and beantreeview . contents setting up the application integrating the database creating entity classes from a database wrapping the entity class jar in a module creating other related modules designing the user interface setting dependencies running the prototype integrating crud functionality read update create delete the application you create in this article will look as follows: source code: http://kenai.com/projects/nbcustomermanager once you're at the stage shown above, you can simply download a netbeans module that provides office laf support ( ), add it to your application, and then when you redeploy the application, you will see this: note: it is advisable to watch the screencast series top 10 netbeans apis before beginning to work on this article. many of the concepts addressed in this article are discussed in more detail within the screencast series. setting up the application let's start by creating a new netbeans platform application. choose file > new project (ctrl+shift+n). under categories, select netbeans modules. under projects, select netbeans platform application. click next. in the name and location panel, type dbmanager in the project name field. click finish. the ide creates the dbmanager project. the project is a container for all the other modules you will create. run the application and notice that you have quite a few features out of the box already. open some of the windows, undock them, and get to know the basic components that the netbeans platform provides without you doing any work whatsoever: integrating the database in order to integrate the database, you need to create entity classes from your database and integrate those entity classes, together with their related jars, into modules that are part of your netbeans platform application. creating the entity classes in this section, you generate entity classes from a selected database. for purposes of this example, use the services window to connect to the sample database that is included with netbeans ide: note: alternatively, use any database you like and adapt the steps that follow to your particular use case. in the case of mysql, see connecting to a mysql database . in the ide, choose file | new project, followed by java | java class library to create a new library project named customerlibrary. in the projects window, right-click the library project and choose file | new file, followed by persistence | entity classes from database. in the wizard, select your database and the tables you need. here we choose "customer", and then "discount code" is added automatically, since there is a relationship between these two tables. specify the persistence strategy, which can be any of the available options. here, since we need to choose something, we'll choose eclipselink: specify "demo" as the name of the package where the entity classes will be generated. click finish. once you have completed this step, look at the generated code and notice that, among other things, you now have a persistence.xml file in a folder called meta-inf, as well as entity classes for each of your tables: build the java library and you will have a jar file in the library project's "dist" folder, which you can view in the files window: wrapping the entity class jar in a module in this section, you add your first module to your application! the new netbeans module will wrap the jar file you created in the previous section. right-click the dbmanager's modules node in the projects window and choose add new library. select the jar you created in the previous subsection and complete the wizard, specifying any values you like. let's assume the application is for dealing with customers at shop.org, in which case a unique identifier "org.shop.model" is appropriate for the code name base: you now have your first custom module in your new application, wrapping the jar containing the entity classes and the persistence.xml file: creating other related modules in this section, you create two new modules, wrapping the eclipselink jars, as well as the database connector jar. do the same as you did when creating the library wrapper for the entity class jar, but this time for the eclipselink jars, which are in the "customerlibrary" java library that you created earlier: note: in the library wrapper module wizard, you can use ctrl-click to select multiple jars. next, create yet another library wrapper module, this time for the java db client jar, which is available in your jdk distribution, at db/lib/derbyclient.jar. designing the user interface in this section, you create a simple prototype user interface, providing a window that uses a jtextarea to display data retrieved from the database. right-click the dbmanager's modules node in the projects window and choose add new. create a new module named customerviewer, with the code name base org.shop.ui. in the projects window, right-click the new module and choose new | window component. specify that it should be created in the editor position and that it should open when the application starts. set customer as the window's class name prefix. use the palette (ctrl-shift-8) to drag and drop a jtextarea on the new window: add this to the end of the topcomponent constructor: entitymanager entitymanager = persistence.createentitymanagerfactory("customerlibrarypu").createentitymanager(); query query = entitymanager.createquery("select c from customer c"); list resultlist = query.getresultlist(); for (customer c : resultlist) { jtextarea1.append(c.getname() + " (" + c.getcity() + ")" + "\n"); } note: since you have not set dependencies on the modules that provide the customer object and the persistence jars, the statements above will be marked with red error underlines. these will be fixed in the section that follows. above, you can see references to a persistence unit named "customerlibrarypu", which is the name set in the persistence.xml file. in addition,there is a reference to one of the entity classes, called customer, which is in the entity classes module. adapt these bits to your needs, if they are different to the above. setting dependencies in this section, you enable some of the modules to use code from some of the other modules. you do this very explicitly by setting intentional contracts between related modules, i.e., as opposed to the accidental and chaotic reuse of code that tends to happen when you do not have a strict modular architecture such as that provided by the netbeans platform. the entity classes module needs to have dependencies on the derby client module as well as on the eclipselink module. right-click the customerlibrary module, choose properties, and use the libraries tab to set dependencies on the two modules that the customerlibrary module needs. the customerviewer module needs a dependency on the eclipselink module as well as on the entity classes module. right-click the customerviewer module, choose properties, and use the libraries tab to set dependencies on the two modules that the customerviewer module needs. open the customertopcomponent in the source view, right-click in the editor, and choose "fix imports". the ide is now able to add the required import statements, because the modules that provide the required classes are now available to the customertopcomponent. you now have set contracts between the modules in your application, giving you control over the dependencies between distinct pieces of code. running the prototype in this section, you run the application so that you can see that you're correctly accessing your database. start your database server. run the application. you should see this: you now have a simple prototype, consisting of a netbeans platform application that displays data from your database, which you will extend in the next section. integrating crud functionality in order to create crud functionality that integrates smoothly with the netbeans platform, some very specific netbeans platform coding patterns need to be implemented. the sections that follow describe these patterns in detail. read in this section, you change the jtextarea, introduced in the previous section, for a netbeans platform explorer view. netbeans platform explorer views are swing components that integrate better with the netbeans platform than standard swing components do. among other things, they support the notion of a context, which enables them to be context sensitive. representing your data, you will have a generic hierarchical model provided by a netbeans platform node class, which can be displayed by any of the netbeans platform explorer views. this section ends with an explanation of how to synchronize your explorer view with the netbeans platform properties window. in your topcomponent, delete the jtextarea in the design view and comment out its related code in the source view: entitymanager entitymanager = persistence.createentitymanagerfactory("customerlibrarypu").createentitymanager(); query query = entitymanager.createquery("select c from customer c"); list resultlist = query.getresultlist(); //for (customer c : resultlist) { // jtextarea1.append(c.getname() + " (" + c.getcity() + ")" + "\n"); //} right-click the customerviewer module, choose properties, and use the libraries tab to set dependencies on the nodes api and the explorer & property sheet api. next, change the class signature to implement explorermanager.provider: final class customertopcomponent extends topcomponent implements explorermanager.provider you will need to override getexplorermanager() @override public explorermanager getexplorermanager() { return em; } at the top of the class, declare and initialize the explorermanager: private static explorermanager em = new explorermanager(); note: watch top 10 netbeans apis for details on the above code, especially the screencast dealing with the nodes api and the explorer & property sheet api. switch to the topcomponent design view, right-click in the palette, choose palette manager | add from jar. then browse to the org-openide-explorer.jar, which is in platform11/modules folder, within the netbeans ide installation directory. choose the beantreeview and complete the wizard. you should now see beantreeview in the palette. drag it from the palette and drop it on the window. create a factory class that will create a new beannode for each customer in your database: import demo.customer; import java.beans.introspectionexception; import java.util.list; import org.openide.nodes.beannode; import org.openide.nodes.childfactory; import org.openide.nodes.node; import org.openide.util.exceptions; public class customerchildfactory extends childfactory { private list resultlist; public customerchildfactory(list resultlist) { this.resultlist = resultlist; } @override protected boolean createkeys(list list) { for (customer customer : resultlist) { list.add(customer); } return true; } @override protected node createnodeforkey(customer c) { try { return new beannode(c); } catch (introspectionexception ex) { exceptions.printstacktrace(ex); return null; } } } back in the customertopcomponent, use the explorermanager to pass the result list from the jpa query in to the node: entitymanager entitymanager = persistence.createentitymanagerfactory("customerlibrarypu").createentitymanager(); query query = entitymanager.createquery("select c from customer c"); list resultlist = query.getresultlist(); em.setrootcontext(new abstractnode(children.create(new customerchildfactory(resultlist), true))); //for (customer c : resultlist) { // jtextarea1.append(c.getname() + " (" + c.getcity() + ")" + "\n"); //} run the application. once the application is running, open the properties window. notice that even though the data is available, displayed in a beantreeview, the beantreeview is not synchronized with the properties window, which is available via window | properties. in other words, nothing is displayed in the properties window when you move up and down the tree hierarchy. synchronize the properties window with the beantreeview by adding the following to the constructor in the topcomponent: associatelookup(explorerutils.createlookup(em, getactionmap())); here we add the topcomponent's actionmap and explorermanager to the lookup of the topcomponent. run the application again and notice that the properties window is now synchronized with the explorer view: now you are able to view your data in a tree hierarchy, as you would be able to do with a jtree. however, you're also able to swap in a different explorer view without needing to change the model at all because the explorermanager mediates between the model and the view. finally, you are now also able to synchronize the view with the properties window. update in this section, you first create an editor. the editor will be provided by a new netbeans module. so, you will first create a new module. then, within that new module, you will create a new topcomponent, containing two jtextfields, for each of the columns you want to let the user edit. you will need to let the viewer module communicate with the editor module. whenever a new node is selected in the viewer module, you will add the current customer object to the lookup. in the editor module, you will listen to the lookup for the introduction of customer objects. whenever a new customer object is introduced into the lookup, you will update the jtextfields in the editor. next, you will synchronize your jtextfields with the netbeans platform's undo, redo, and save functionality. in other words, when the user makes changes to a jtextfield, you want the netbeans platform's existing functionality to become available so that, instead of needing to create new functionality, you'll simply be able to hook into the netbeans platform's support. to this end, you will need to use the undoredomanager, together with the savecookie. create a new module, named customereditor, with org.shop.editor as its code name base. right-click the customereditor module and choose new | window component. make sure to specify that the window should appear in the editor position and that it should open when the application starts. in the final panel of the wizard, set "editor" as the class name prefix. use the palette (ctrl-shift-8) to add two jlabels and two jtextfields to the new window. set the texts of the labels to "name" and "city" and set the variable names of the two jtextfields to jtextfield1 and jtextfield2. in the gui builder, the window should now look something like this: go back to the customerviewer module and change its layer.xml file to specify that the customertopcomponent window will appear in the explorer mode. note: right-click the application project and choose "clean", after changing the layer.xml file. why? because whenever you run the application and close it down, the window positions are stored in the user directory. therefore, if the customerviewer was initially displayed in the editor mode, it will remain in the editor mode, until you do a "clean", thus resetting the user directory (i.e., thus deleting the user directory) and enabling the customerviewer to be displayed in the position currently set in the layer.xml file. also check that the beantreeview in the customerviewer will stretch horizontally and vertically when the user resizes the application. check this by opening the window, selecting the beantreeview, and then clicking the arrow buttons in the toolbar of the gui builder. run the application and make sure that you see the following when the application starts up: now we can start adding some code. firstly, we need to show the currently selected customer object in the editor: start by tweaking the customerviewer module so that the current customer object is added to the viewer window's lookup whenever a new node is selected. do this by creating an abstractnode, instead of a beannode, in the customerchildfactory class. that enables you to add the current customer object to the lookup of the node, as follows (note the "lookups.singleton(c)" below): @override protected node createnodeforkey(customer c) { node node = new abstractnode(children.leaf, lookups.singleton(c)); node.setdisplayname(c.getname()); node.setshortdescription(c.getcity()); return node; // try { // return new beannode(c); // } catch (introspectionexception ex) { // exceptions.printstacktrace(ex); // return null; // } } now, whenever a new node is created, which happens when the user selects a new customer in the viewer, a new customer object is added to the lookup of the node. let's now change the editor module in such a way that its window will end up listening for customer objects being added to the lookup. first, set a dependency in the editor module on the module that provides the entity class, as well as the module that provides the persistence jars. next, change the editortopcomponent class signature to implement lookuplistener: public final class editortopcomponent extends topcomponent implements lookuplistener override the resultchanged so that the jtextfields are updated whenever a new customer object is introduced into the lookup: @override public void resultchanged(lookupevent lookupevent) { lookup.result r = (lookup.result) lookupevent.getsource(); collection coll = r.allinstances(); if (!coll.isempty()) { for (customer cust : coll) { jtextfield1.settext(cust.getname()); jtextfield2.settext(cust.getcity()); } } else { jtextfield1.settext("[no name]"); jtextfield2.settext("[no city]"); } } now that the lookuplistener is defined, we need to add it to something. here, we add it to the lookup.result obtained from the global context. the global context proxies the context of the selected node. for example, if "ford motor co" is selected in the tree hierarchy, the customer object for "ford motor co" is added to the lookup of the node which, because it is the currently selected node, means that the customer object for "ford motor co" is now available in the global context. that is what is then passed to the resultchanged, causing the text fields to be populated. all of the above starts happening, i.e., the lookuplistener becomes active, whenever the editor window is opened, as you can see below: @override public void componentopened() { result = utilities.actionsglobalcontext().lookupresult(customer.class); result.addlookuplistener(this); resultchanged(new lookupevent(result)); } @override public void componentclosed() { result.removelookuplistener(this); result = null; } since the editor window is opened when the application starts, the lookuplistener is available at the time that the application starts up. finally, declare the result variable at the top of the class, like this: private lookup.result result = null; run the application again and notice that the editor window is updated whenever you select a new node: however, notice what happens when you switch the focus to the editor window: because the node is no longer current, the customer object is no longer in the global context. this is the case because, as pointed out above, the global context proxies the lookup of the current node. therefore, in this case, we cannot use the global context. instead, we will use the local lookup provided by the customer window. rewrite this line: result = utilities.actionsglobalcontext().lookupresult(customer.class); to this: result = windowmanager.getdefault().findtopcomponent("customertopcomponent").getlookup().lookupresult(customer.class); the string "customertopcomponent" is the id of the customertopcomponent, which is a string constant that you can find in the source code of the customertopcomponent. one drawback of the approach above is that now our editortopcomponent only works if it can find a topcomponent with the id "customertopcomponent". either this needs to be explicitly documented, so that developers of alternative editors can know that they need to identify the viewer topcomponent this way, or you need to rewrite the selection model, as described here by tim boudreau. if you take one of the above approaches, you will find that the context is not lost when you switch the focus to the editortopcomponent, as shown below: note: since you are now using abstractnode, instead of beannode, no properties are shown in the properties window. you need to provide these yourself, as described in the nodes api tutorial . secondly, let's work on the undo/redo functionality. what we'd like to have happen is that whenever the user makes a change to one of the jtextfields, the "undo" button and the "redo" button, as well as the related menu items in the edit menu, become enabled. to that end, the netbeans platform makes the undoredo.manager available. declare and instantiate a new undoredomanager at the top of the editortopcomponent: private undoredo.manager manager = new undoredo.manager(); next, override the getundoredo() method in the editortopcomponent: @override public undoredo getundoredo() { return manager; } in the constructor of the editortopcomponent, add a keylistener to the jtextfields and, within the related methods that you need to implement, add the undoredolisteners: jtextfield1.getdocument().addundoableeditlistener(manager); jtextfield2.getdocument().addundoableeditlistener(manager); run the application and show the undo and redo functionality in action, the buttons as well as the menu items. the functionality works exactly as you would expect. you might want to change the keylistener so that not all keys cause the undo/redo functionality to be enabled. for example, when enter is pressed, you probably do not want the undo/redo functionality to become available. therefore, tweak the code above to suit your business requirements. thirdly, we need to integrate with the netbeans platform's save functionality: by default, the "save all" button is available in the netbeans platform toolbar. in our current scenario, we do not want to save "all", because "all" refers to a number of different documents. in our case, we only have one "document", which is the editor that we are reusing for all the nodes in the tree hirerarchy. remove the "save all" button and add the "save" button instead, by adding the following to the layer file of the customereditor module: when you now run the application, you will see a different icon in the toolbar. instead of the "save all" button, you now have the "save" button available. set dependencies on the dialogs api and the nodes api. in the editortopcompontn constructor, add a call to fire a method (which will be defined in the next step) whenever a change is detected: public editortopcomponent() { ... ... ... jtextfield1.getdocument().adddocumentlistener(new documentlistener() { public void insertupdate(documentevent arg0) { fire(true); } public void removeupdate(documentevent arg0) { fire(true); } public void changedupdate(documentevent arg0) { fire(true); } }); jtextfield2.getdocument().adddocumentlistener(new documentlistener() { public void insertupdate(documentevent arg0) { fire(true); } public void removeupdate(documentevent arg0) { fire(true); } public void changedupdate(documentevent arg0) { fire(true); } }); //create a new instance of our savecookie implementation: impl = new savecookieimpl(); //create a new instance of our dynamic object: content = new instancecontent(); //add the dynamic object to the topcomponent lookup: associatelookup(new abstractlookup(content)); } ... ... ... here are the two methods referred to above. first, the method that is fired whenever a change is detected. an implementation of the savecookie from the nodes api is added to the instancecontent whenever a change is detected: public void fire(boolean modified) { if (modified) { //if the text is modified, //we add savecookie impl to lookup: content.add(impl); } else { //otherwise, we remove the savecookie impl from the lookup: content.remove(impl); } } private class savecookieimpl implements savecookie { @override public void save() throws ioexception { confirmation message = new notifydescriptor.confirmation("do you want to save \"" + jtextfield1.gettext() + " (" + jtextfield2.gettext() + ")\"?", notifydescriptor.ok_cancel_option, notifydescriptor.question_message); object result = dialogdisplayer.getdefault().notify(message); //when user clicks "yes", indicating they really want to save, //we need to disable the save action, //so that it will only be usable when the next change is made //to the jtextarea: if (notifydescriptor.yes_option.equals(result)) { fire(false); //implement your save functionality here. } } } run the application and notice the enablement/disablement of the save button: note: right now, nothing happens when you click ok in the dialog above. in the next step, we add some jpa code for handling persistence of our changes. next, we add jpa code for persisting our change. do so by replacing the comment "//implement your save functionality here." the comment should be replaced by all of the following: entitymanager entitymanager = persistence.createentitymanagerfactory("customerlibrarypu").createentitymanager(); entitymanager.gettransaction().begin(); customer c = entitymanager.find(customer.class, customer.getcustomerid()); c.setname(jtextfield1.gettext()); c.setcity(jtextfield2.gettext()); entitymanager.gettransaction().commit(); note: the "customer" in customer.getcustomerid() is currently undefined. add the line "customer = cust;" in the resultchanged (as shown below), after declaring customer customer; at the top of the class, so that the current customer object sets the customer, which is then used in the persistence code above to obtain the id of the current customer object. @override public void resultchanged(lookupevent lookupevent) { lookup.result r = (lookup.result) lookupevent.getsource(); collection c = r.allinstances(); if (!c.isempty()) { for (customer customer : c) { customer = cust; jtextfield1.settext(customer.getname()); jtextfield2.settext(customer.getcity()); } } else { jtextfield1.settext("[no name]"); jtextfield2.settext("[no city]"); } } run the application and change some data. currently, we have no "refresh" functionality (that will be added in the next step) so, to see the changed data, restart the application. here, for example, the tree hierarchy shows the persisted customer name for "toyota motor co": fourthly, we need to add functionality for refreshing the customer viewer. you might want to add a timer which periodically refreshes the viewer. however, in this example, we will add a "refresh" menu item to the root node so that the user will be able to manually refresh the viewer. in the main package of the customerviewer module, create a new node, which will replace the abstractnode that we are currently using as the root of the children in the viewer. note that we also bind a "refresh" action to our new root node. public class customerrootnode extends abstractnode { public customerrootnode(children kids) { super(kids); setdisplayname("root"); } @override public action[] getactions(boolean context) { action[] result = new action[]{ new refreshaction()}; return result; } private final class refreshaction extends abstractaction { public refreshaction() { putvalue(action.name, "refresh"); } public void actionperformed(actionevent e) { customertopcomponent.refreshnode(); } } } add this method to the customertopcomponent, for refreshing the view: public static void refreshnode() { entitymanager entitymanager = persistence.createentitymanagerfactory("customerlibrarypu").createentitymanager(); query query = entitymanager.createquery("select c from customer c"); list resultlist = query.getresultlist(); em.setrootcontext(new customerrootnode(children.create(new customerchildfactory(resultlist), true))); } now replace the code above in the constructor of the customertopcomponent with a call to the above. as you can see, we are now using our customerrootnode instead of the abstractnode. the customerrootnode includes the "refresh" action, which calls the code above. in your save functionality, add the call to the method above so that, whenever data is saved, an automatic refresh takes place. you can take different approaches when implementing this extension to the save functionality. for example, you might want to create a new module that contains the refresh action. that module would then be shared between the viewer module and the editor module, providing functionality that is common to both. run the application again and notice that you have a new root node, with a "refresh" action: make a change to some data, save it, invoke the refresh action, and notice that the viewer is updated. you have now learned how to let the netbeans platform handle changes to the jtextfields. whenever the text changes, the netbeans platform undo and redo buttons are enabled or disabled. also, the save button is enabled and disabled correctly, letting the user save changed data back to the database. create in this section, you allow the user to create a new entry in the database. right-click the customereditor module and choose "new action". use the new action wizard to create a new "always enabled" action. the new action should be displayed anywhere in the toolbar and/or anywhere in the menu bar. in the next step of the wizard, call the action newaction. note: make sure that you have a 16x16 icon available, which the wizard forces you to select if you indicate that you want the action to be invoked from the toolbar. in the new action, let the topcomponent be opened, together with emptied jtextfields: import java.awt.event.actionevent; import java.awt.event.actionlistener; public final class newaction implements actionlistener { public void actionperformed(actionevent e) { editortopcomponent tc = editortopcomponent.getdefault(); tc.resetfields(); tc.open(); tc.requestactive(); } } note: the action implements the actionlistener class, which is bound to the application via entries in the layer file, put there by the new action wizard. imagine how easy it will be when you port your existing swing application to the netbeans platform, since you'll simply be able to use the same action classes that you used in your original application, without needing to rewrite them to conform to action classes provided by the netbeans platform! in the editortopcomponent, add the following method for resetting the jtextfields and creating a new customer object: public void resetfields() { customer = new customer(); jtextfield1.settext(""); jtextfield2.settext(""); } in the savecookie, ensure that a return of null indicates that a new entry is saved, instead of an existing entry being updated: public void save() throws ioexception { confirmation message = new notifydescriptor.confirmation("do you want to save \"" + jtextfield1.gettext() + " (" + jtextfield2.gettext() + ")\"?", notifydescriptor.ok_cancel_option, notifydescriptor.question_message); object result = dialogdisplayer.getdefault().notify(msg); //when user clicks "yes", indicating they really want to save, //we need to disable the save button and save menu item, //so that it will only be usable when the next change is made //to the text field: if (notifydescriptor.yes_option.equals(result)) { fire(false); entitymanager entitymanager = persistence.createentitymanagerfactory("customerlibrarypu").createentitymanager(); entitymanager.gettransaction().begin(); if (customer.getcustomerid() != null) { customer c = entitymanager.find(customer.class, cude.getcustomerid()); c.setname(jtextfield1.gettext()); c.setcity(jtextfield2.gettext()); entitymanager.gettransaction().commit(); } else { query query = entitymanager.createquery("select c from customer c"); list resultlist = query.getresultlist(); customer.setcustomerid(resultlist.size()+1); customer.setname(jtextfield1.gettext()); customer.setcity(jtextfield2.gettext()); //add more fields that will populate all the other columns in the table! entitymanager.persist(customer); entitymanager.gettransaction().commit(); } } } run the application again and add a new customer to the database. delete in this section, let the user delete a selected entry in the database. using the concepts and code outlined above, implement the delete action yourself. create a new action, deleteaction. decide whether you want to bind it to a customer node or whether you'd rather bind it to the toolbar, the menu bar, keyboard shortcut, or combinations of these. depending on where you want to bind it, you will need to use a different approach in your code. read the article again for help, especially by looking at how the "new" action was created, while comparing it to the "refresh" action on the root node. get the current customer object, return an 'are you sure?' dialog, and then delete the entry. for help on this point, read the article again, focusing on the part where the "save" functionality is implemented. instead of saving, you now want to delete an entry from the database. see also this concludes the article. you have learned how to create a new netbeans platform application with crud functionality for a given database. you have also seen many of the netbeans apis in action. for more information about creating and developing applications on the netbeans platform, see the following resources: netbeans platform learning trail netbeans api javadoc
December 8, 2009
· 232,045 Views
article thumbnail
How to Split an Application into Modules?
When you're new to modular architectures, a question that is likely to arise (sooner, rather than later) is: "How should I determine the best way to split an application into modules?" I asked NetBeans Dream Team member Tom Wheeler this question, in relation to his contribution to advice given during a training session described here. Below follows his response, which could apply to any modular system (based on OSGi bundles, NetBeans modules, or anything comparable). There's really no right answer for knowing how to split your application into multiple modules. In general, it's better to have lots of small modules instead of a few big ones. In general, I definitely prefer to have lots of little modules than a few big ones. If you're designing a new app from scratch, it's easy to achieve "smallness" in your modules and you'll have a better design (less coupling) because of it. If you're porting an existing application to the NetBeans platform, then you'll probably just have one or two big modules at first and you'll have to achieve smallness as you make things more modular over time. One rule of thumb is that you can often split the application into modules based on package boundaries. Thus, if you have the following packages: com.tomwheeler.app.gui com.tomwheeler.app.data com.tomwheeler.app.logic You might refactor this into a GUI module, a data module and a logic module. As you continue development, you might find that these could be split even further. For example, your data module might have objects representing customer data and product data, so you could create a customer data module and a product data module. Making your application modular actually makes refactoring easier because it's clear exactly what you've exposed as a public API. For any given feature, I almost always strive to separate API, implementation and client code into separate modules. This allows me to develop iteratively -- I can first concentrate on the API, then write a very basic implementation of it. I can then develop additional (or better) implementations of that API as time allows. One example might be a reporting subsystem for an application. I could create an API that defines what's needed to generate a report, but the API won't focus on details like file format. I can then create the simplest possible implementation of that API; it might create a plain text version of the report. I can later create a new module which creates a better report, perhaps in Excel or PDF format. While I could simply replace the first version, I could also easily add a little code to let the user select the desired report format. In addition to reducing coupling in your application's design, having smaller modules gives you more flexibility. When your application is modular, it's very easy to build different versions of the application with different sets of features, kind of like the "basic", "standard" and "enterprise" versions of software you sometimes see. Doing that with a monolithic application is usually pretty difficult. If you, reading this article, have experience in this area, i.e., modularization, please share your thoughts on this topic in the comments below, since doing so would be very useful to others starting on this path!
December 1, 2009
· 84,101 Views
article thumbnail
War Fighter on the NetBeans Platform
Agile Client is a NetBeans Platform application developed by Northrop Grumman in partnership with the Defense Information System Agency (DISA). It brings the war fighter a 3-D common operational picture (COP) workstation designed for greater efficiency and mission effectiveness. This efficiency is empowered by its ability to be installed and upgraded on demand. Its mission effectiveness is permitted by the ability to tailor the user’s application with only the capabilities and data they need for their specific mission. The interview below is with Charlie Black, who runs the team using the NetBeans Platform at Northrop Grumman. Hi Charlie, who are you and what do you do? My name is Charlie Black and I have worked for Northrop Grumman since 1998. Over that time I have been working as a software engineer on a Global Command and Control System (GCCS) program supporting data fusion, dissemination and display technologies. I am currently running a team that uses the NetBeans Platform for a product called Agile Client, which is now part of GCCS. Team: Greg Gibsen, Charlie Black, Brice Bingman and James Maloney What are the technical specifics of Agile Client? The Agile Client uses several commercial off the shelf (COTS) products that make up its core feature set: It uses the NetBeans Platform, which provides the services common to almost all large desktop applications: window management, menus, settings and storage, an update manager, and file access. For map and visual rendering, Agile Client uses NASA’s World Wind product, enabling the retrieval of geospatial data via open standards that are embraced by the international community. For providing data services, Agile Client uses Gemstone GemFire, which provides ultra low-latency distributed caching with high availability and no data loss. Here's a screenshot of Agile Client in action: Agile Client is also integrated with GCCS COP Collaboration. This allows one or more war fighters to work simultaneously on a single map. They can collaboratively create GCCS Overlays, share files and communicate by instant messaging and Voice over IP. This is all done with the Extensible Messaging and Presence Protocol (XMPP), which is a set of open XML technologies for presence and real-time communication. What are the two or three things that you are happiest about, relating to this application? Since the NetBeans Platform is based on standard Java UI technologies, we are able to integrate existing Java windows directly, without any issues. This has accelerated our development substantially. Using Sun UI guidelines and reusable components in any new development, we have actually made an application that is embraced by our customers as looking modern. Underneath this application is the NetBeans Platform. Why? The main reason for going with a rich client platform such as the NetBeans Platform was the module system. It will help with our deployment of a large scale application on an enterprise level. I can envision a future where there will be hundreds of modules deployed in the application. Then, using the update center, we can keep those applications up to date. How did you find out about it? When? Why did you start using it? We have known about NetBeans for a long time. However it was used mainly as a developer tool. It wasn’t until NetBeans 6.0 that we started using it as our platform for basing new work on. What are the main things you gained from the NetBeans Platform? Using the NetBeans Platform, we decreased our time to develop our application by using existing window components. Also, the automatic updates are integral to our final application. In the past, it would have taken months or even years to get a patch to our end users. That said, the most significant gain has been the community! Which APIs have you used? Which ones are your favorites and why? We actually use several API sets, with just about every one enabled. The Windows API is incredible, as that is what the end user sees that allows them to tailor their display. With the customization of toolbars, the end-user can make their own ad-hoc workflow. The other API that we have been impressed with is the Nodes API, providing a view to our layers on the 3D globe. What could be improved about the NetBeans Platform? In our community OSGi is a big item, so if NetBeans could formally handle them for module deployment that would be a monumental win. Imagine a module of business intelligence that can be deployed in Glassfish and in the NetBeans Platform. I realize that some work has already been done in this area, but to see it on an official roadmap would be remarkable. After that, the Properties window could use something to make it more appealing. We are thinking of dropping our own Properties window in favor of the NetBeans implementation. Overall, we have been really happy with the NetBeans Platform and the features it provides. Do you have some tips and tricks for a complete newbie, who is getting started with the NetBeans Platform? When new team members join, I customarily distribute to them a book on the NetBeans Platform. For further aid, I point them to the NetBeans Developer Wiki. There is an amazing amount of information available, detailing not only what the NetBeans Platform can do for you, but what can you do with the NetBeans Platform as well. If more assistance is needed, I recommend just asking the community. Someone can usually help in answering any level of questions. How have customers responded to this application and what are your plans for its future? Our customers are very pleased with the application and they are moving forward with plans to base future work on the Agile Client. Internally, we have made Agile Client with the goal of releasing portions back to the community. However, before that can be done, we have to figure out what that means from our customer’s standpoint.
March 31, 2009
· 37,591 Views
article thumbnail
Using IntelliJ IDEA for NetBeans Platform Development
On jetbrains.com there's a rather impressive article entitled Using IntelliJ IDEA for Eclipse RCP development. Let's take a look at what the NetBeans Platform equivalent would look like. We'll start with one of the standard NetBeans Platform sample applications distributed with NetBeans IDE, the Paint Application. The application consists of an application module that provides a canvas for painting, with some 3rd party libraries wrapped into supporting modules. In other words, a very realistic example representing a real life scenario. We're going to (1) open that application into IntelliJ and then (2) deploy it from IntelliJ, with this result: In the picture above, take a look at the application structure, as well as the running application itself. That's what we're going to be creating in the steps that follow. I.e., we will make full use of the NetBeans Platform, while using IntelliJ to do so. Create the Application. Open NetBeans IDE and create the Paint Application, which you can find in the New Project dialog. Import the Application into IntelliJ. Open IntelliJ and choose File | New Project | Create project from scratch. Click Next. In "Project files location", set the "PaintApp" root folder. Type "PaintApp" in "Name". Click Next and keep clicking Next until you can click Finish. I.e., don't change any of the defaults. Now the application is open in IntelliJ. Add the NetBeans Platform to the Classpath. Right-click the main "PaintApp" node and choose "Module Settings". In Dependencies, create a new project library that contains all the JARs that you can find in the NetBeans installation directory's 'platform9' folder. Make sure to look in the 'core', 'lib', and 'modules' folders. You should end up with a very long list of JARs. Also make sure to add 'ColorChooser.jar' (which is in 'release/modules/ext' within the Color Chooser module) in the same way. Create a Runtime Configuration. In the toolbar, click 'Edit Configurations'. Create a new configuration, named 'NetBeans' (for example, but name it whatever you like). Set 'org.netbeans.Main' as the 'Main class' (you should be able to browse to it in 'boot.jar'). in 'VM parameters', pass in some VM options for setting the user directory of the application (which would normally be set via etc/netbeans.conf when NetBeans IDE starts up, which it won't do in our case), as well as the home directory. The user directory can be anywhere, while the home directory must be the cluster that is created by the build process: -Dnetbeans.user="/home/geertjan/idea/paint-userdir" -Dnetbeans.home="/home/geertjan/idea/PaintApp/build/cluster" The above implies that the cluster exists, which implies that a build has been performed. That's why I do the build from NetBeans IDE. That creates the cluster and then the above VM option works. Instead of VM options, you can also use other approaches to ensure that the application knows where the installation and the user directory are, as discussed here in the comments. Turn Folders into Source Folders. Go back to the Module Settings and then use the Sources tab to set 'branding' and 'build' as sources. (After you do this, the folders will turn blue.) The 'Paint/src' should already be marked as sources. Now run the application, using the runtime configuration you defined earlier and you should see your application deployed. Now do the same to the FeedReader Application, which is also distributed with NetBeans IDE, and you should end up with a successful result, following the principles outline above. Finally, what's the benefit of all this? Well, for far too long IntelliJ users have been excluded from the wonderfulness of the NetBeans Platform. Now, following these instructions, you can at least get started. You'd use NetBeans IDE for generating the project structure and API stubs, as well as for the Matisse GUI Builder's support for the TopComponent class (and other UI classes), after which you'd do your coding in the IntelliJ Java editor. (And the IntelliJ XML editor has better support for the NetBeans Platform layer.xml file than NetBeans IDE does.) Or you'd have different developers working in different IDEs, sharing the same codebase in the way outlined above. An interesting discovery is that a NetBeans Platform application deploys much more quickly from IntelliJ than it does from NetBeans IDE.
March 4, 2009
· 30,380 Views
article thumbnail
How to Create Modular Groovy Applications in 5 Steps!
let's create a modular groovy application! why?! modularity is an enabler of scaleability. as your groovy application increases in size, you increasingly need to manage code dependencies, structure your code in units that are larger than packages, and distribute pieces of your application to developers located in different locations and conflicting time zones. welcome to modularity. the netbeans platform already provides it (plus, osgi is coming to the netbeans platform ). beyond modularity, there are specific features that the netbeans platform provides that will remain unique, such as a shared filesystem for intermodular communication and the concept of "context" (i.e., netbeans lookup), which not only applications have (as with the jdk 6 serviceloader class), but netbeans platform objects such as windows themselves. welcome to loosely coupled modularity. now, let's get started. start up netbeans ide 6.5. go to this page and download the groovy console template and use the plugin manager (in the tools menu) to install it into the ide. now, in the new project dialog, you should see this new project template: click next, give your new application a name (such as "helloworld") and a location on disk, and then click finish. expand a few folders and you should now see this: briefly, the template gives you a groovy pojo, with this content: package org.my.app public class demopojo { def foo } the template also gives you a moduleinstall class, which handles the lifecycle of the module: package org.my.app import org.openide.modules.moduleinstall as mi public class installer extends mi { @override public void restored() { for(int i = 0; i < 10; i++) { demopojo dp = new demopojo() dp.setfoo(i) println("number: " + dp.getfoo()) } } } so, we have some standard groovy constructs here, simply to get you started in the ecosystem of the netbeans platform. the module also includes a properties file for internationalization purposes and a layer.xml file, for the module's contributions to the shared filesystem. run the application (i.e., without doing anything at all, no tweaking, no post processing, nothing at all, just run it). look in the output window of netbeans ide and you will see this: so, you can see that you only have the absolute minimum set of modules to start with. also you're using the groovy compiler (thanks to an additional target that's added to the demo module's build.xml file). that's how to get started with modular groovy applications. have fun with groovy on the netbeans platform!
February 14, 2009
· 21,846 Views
article thumbnail
Integrate OpenOffice with Java without Installing OpenOffice
Until a few days ago, I've always needed to work with the rather cumbersome Office Bean and UNO Runtime when integrating OpenOffice into a Java application. I also had to configure a whole bunch of things to force OpenOffice to play nicely with the Java integration. Two days ago, however, I found out about ODF Toolkit. It seems to be a relatively new project, independent since last year some time, though I could be wrong. What's especially interesting is the ODFDOM: ''ODFDOM is an OpenDocument (ODF) framework. It's purpose is to provide an easy common way to create, access and manipulate ODF files, without requiring detailed knowledge of the ODF specification. It is designed to provide the ODF developer community an easy lightwork programming API, portable to any object-oriented language.'' Here's a snippet of it in action: public static void main(String[] args) { try { OdfDocument odfDoc = OdfDocument.loadDocument(new File("/home/geertjan/test.ods")); OdfFileDom odfContent = odfDoc.getContentDom(); XPath xpath = odfDoc.getXPath(); DTMNodeList nodeList = (DTMNodeList) xpath.evaluate("//table:table-row/table:table-cell[1]", odfContent, XPathConstants.NODESET); for (int i = 0; i < nodeList.getLength(); i++) { Node cell = nodeList.item(i); if (!cell.getTextContent().isEmpty()) { System.out.println(cell.getTextContent()); } } } catch (Exception ex) { //Handle... } } Let's assume that the 'test.ods' file above has this content: From the above, the code listing would print the following: Cuthbert Algernon Wilbert And, as a second example, here's me reading the first paragraph of an OpenOffice Text document: public static void main(String[] args) { try { OdfDocument odfDoc = OdfDocument.loadDocument(new File("/home/geertjan/chapter2.odt")); OdfFileDom odfContent = odfDoc.getContentDom(); XPath xpath = odfDoc.getXPath(); OdfParagraphElement para = (OdfParagraphElement) xpath.evaluate("//text:p[1]", odfContent, XPathConstants.NODE); System.out.println(para.getFirstChild().getNodeValue()); } catch (Exception ex) { //Handle... } } On my classpath I have "odfdom.jar" and "xerces-2.8.0.jar". I don't necessarily have OpenOffice installed, which means I can very easily process a whole bunch of spreadsheets (or other OpenOffice output) without (a) installing OpenOffice and (b) faster than I would otherwise do, since OpenOffice doesn't need to be started up, via the Office Bean or otherwise. In fact, Aljoscha Rittner from Sepix, who told me about this project and who is using it in his commercial applications, reports that his processing has sped up to a fraction of the original, also because he doesn't need to handle the situation where OpenOffice would crash randomly in the middle of long running processes, such as during the night when there's no human interaction for restarting it.
February 7, 2009
· 50,464 Views
article thumbnail
Hello EclipseLink on the NetBeans Platform
Let's use EclipseLink to set up some very basic database interaction in a NetBeans Platform application. Though it will be the ultimate 'Hello World' scenario, it should show how to get started with database interactivity on the NetBeans Platform, while also yet again showing the benefit of the NetBeans Platform's modular architecture. Of course, feel free to adapt these instructions to your needs, for example, instead of EclipseLink, use TopLink, or Hibernate, or whatever. You should also be surprised by how easy it is, once you know how. We'll simply access a database and display what we find there: Our application will look as follows: Notice that we will have 4 separate modules, which will enable us to easily provide alternative database providers, as well as alternative persistence providers, because the UI module uses generic code that could make use of any alternative backing modules. Let's get started. Create a Java Library and Generate Entity Classes from the Database. Firstly, create a Java Library project. Then use the Entity Classes from Database wizard to generate entity classes from your database. In the wizard, select EclipseLink in the step where you use the wizard to generate a persistence unit. Look at the generated code and notice that, among other things, you have a persistence.xml file in a folder called META-INF, thanks to the wizard. In my case, I chose a Sample database that comes with the IDE, and then I specified I want an entity class for the Customer table, which resulted in the IDE also creating an entity class for the related DiscountCode table: Build the Java Library and you will have a JAR file in the above application's "dist" folder. As you will read in the next step, that JAR file needs to be added as a library wrapper module to the application you will start creating in the next step. Create a NetBeans Platform Application. In the New Project dialog, specify that you want to create a new NetBeans Platform Application. Once you've created it, right-click the Modules node in the Projects window and choose Add New Library. Then select the JAR you created in the previous step. You now have your first custom module in the new application. Create Supporting Library Wrappers. Do the same as you did when creating the library wrapper for the entity class JAR, but this time for the EclipseLink JARs (which are in your GlassFish distro, make sure to include the persistence JAR that you find there too and, if you don't know which ones to include, go back to the Java Library shown in the previous screenshot and then expand the Libraries folder, which will show you which libraries you need). Next, create yet another library wrapper module... for the DerbyClient JAR. Create the UI Module. The final module you will need will provide the UI. So, create a new module (not a Library Wrapper Module, but just a plain NetBeans Module) and add a Window Component via the New Window Component wizard. Set Dependencies. You now have lots of classes all neatly separated into distinct modules. In order to be able to use code from one module in another module, you'll need to set dependencies, i.e., very explicit contracts (as opposed to accidental reuse of code in one place from another place, resulting in unmaintainable chaos). First, the entity classes module needs to have dependencies on the DerbyClient module, as well as on the EclipseLink module. Then, the UI module needs a dependency on the EclipseLink module as well as the entity classes module. (You could split things further so that the EclipseLink module is not a dependency of the UI module, by putting the persistence JAR in one module, with the other EclipseLink JARs separated in a different module.) Now, finally, let's do some coding. Not much needed, though. Add a JTextArea to the TopComponent in the UI module. Then add this to the end of the TopComponent constructor: EntityManager entityManager = Persistence.createEntityManagerFactory("EntityLibPU").createEntityManager(); Query query = entityManager.createQuery("SELECT c FROM Customer c"); List resultList = query.getResultList(); for (Customer c : resultList) { jTextArea1.append(c.getName() + " (" +c.getCity() + ")" + "\n"); } Above, you can see I am referring to a persistence unit named "EntityLibPU", which is the name set in the persistence.xml file. In addition, I am referring to one of the entity classes, called Customer, which is in the entity classes module. Adapt these bits to your needs. Deploy the Application. Start your database server and then run the application. You should see this: Congrats, you've just managed to set up JPA via EclipseLink in a modular NetBeans Platform application... and you only typed 6 lines of code.
January 17, 2009
· 34,383 Views
article thumbnail
A Farewell to Heavyweight/Lightweight Conflicts
Problems resulting from the mixing of Swing and AWT components have been a constant source of confusion to Java newbies. This quote explains the reason for the difference very well: Most of the issues related to mixing AWT and Swing components are related to the mixing of so-called heavyweight and lightweight components. A heavyweight component is one that is associated with its own native screen resource (commonly known as a peer). A lightweight component is one that "borrows" the screen resource of an ancestor (which means it has no native resource of its own -- so it's "lighter"). From: Mixing Heavy and Light Components The lightweight approach, taken by Swing, is the preferred, since it consumes less resources. However, there are cases where one might need to mix the two in the same application, which can result in undesired side effects. A case in point, from the same article and where all the code used below is found, goes as follows. The menu on the right behaves correctly, while the menu on the left does not: The reason for the difference is that the badly displayed menu in the second screenshot is Swing and lightweight, while the other menu is AWT, and therefore heavyweight. The Button is an AWT component too, therefore being heavyweight. Unless one forces a lightweight component, via setDefaultLightWeightPopupEnabled(false), to behave like a heavyweight component, unwanted side effects such as the above will result. But all that is old news, of course. The new news is that already with the early access release of JDK 6 Update 12 one can, without needing to do anything at all, obtain the desired effect, which is as follows: This is exactly what one would want: the rendering of a lightweight component over a heavyweight component. Though the major features of the EA release are slated as "Windows 2008 Support" and "Java Plug-In now supports 64-bit browsers", it is this heavyweight/lightweight fix that I find the most useful (since I am neither a Windows- nor a 64-bit browser-user). If one looks through the list of issues fixed in the current JDK 6 Update 12 build, one notices that a lot of fixing has been done in the Swing & AWT packages. The final screenshot above was taken on JDK 6 Update 12, using the code from the article referenced at the start. I.e., without doing anything special at all, no fiddling with z-order or the like, the behavior was exactly as an end user would expect it to be. Hurray!
December 16, 2008
· 20,841 Views
article thumbnail
Taking the New Swing Tree Table for a Spin
Announcing the new Swing Tree Table yesterday, Tim Boudreau writes: Usage is incredibly easy - you just provide a standard Swing TreeModel of whatever sort you like, and an additional RowModel that can be queried for the other columns contents, editability and so forth. I found an example from some time ago, by Tim, and have been playing with it to get used to this new development. The result is as follows: To get started, I simply download the latest NetBeans IDE development build from netbeans.org and then attached the platform8/org-netbeans-swing-outline.jar to my Java SE project. For the rest, I wasn't required to do anything with NetBeans, necessarily. I could have attached the JAR to a project in Eclipse or anywhere else. Then I created a JFrame. To work with this Swing tree table, you need to provide the new "org.netbeans.swing.outline.Outline" class with the new "org.netbeans.swing.outline.OutlineModel" which, in turn, is built from a plain old javax.swing.tree.TreeModel, together with the new "org.netbeans.swing.outline.RowModel". Optionally, to change the default rendering, you can use the new "org.netbeans.swing.outline.RenderDataProvider". Let's first create a TreeModel for accessing files on disk. We will receive the root of the file system as a starting point: private static class FileTreeModel implements TreeModel { private File root; public FileTreeModel(File root) { this.root = root; } @Override public void addTreeModelListener(javax.swing.event.TreeModelListener l) { //do nothing } @Override public Object getChild(Object parent, int index) { File f = (File) parent; return f.listFiles()[index]; } @Override public int getChildCount(Object parent) { File f = (File) parent; if (!f.isDirectory()) { return 0; } else { return f.list().length; } } @Override public int getIndexOfChild(Object parent, Object child) { File par = (File) parent; File ch = (File) child; return Arrays.asList(par.listFiles()).indexOf(ch); } @Override public Object getRoot() { return root; } @Override public boolean isLeaf(Object node) { File f = (File) node; return !f.isDirectory(); } @Override public void removeTreeModelListener(javax.swing.event.TreeModelListener l) { //do nothing } @Override public void valueForPathChanged(javax.swing.tree.TreePath path, Object newValue) { //do nothing } } The above could simply be set as a JTree's model and then you'd have a plain old standard JTree. It would work, no problems, it would be a normal JTree. However, it wouldn't be a tree table since you'd only have a tree, without a table. Therefore, let's now add two extra columns, via the new "org.netbeans.swing.outline.RowModel" class, which will enable the creation of a tree table instead of a tree: private class FileRowModel implements RowModel { @Override public Class getColumnClass(int column) { switch (column) { case 0: return Date.class; case 1: return Long.class; default: assert false; } return null; } @Override public int getColumnCount() { return 2; } @Override public String getColumnName(int column) { return column == 0 ? "Date" : "Size"; } @Override public Object getValueFor(Object node, int column) { File f = (File) node; switch (column) { case 0: return new Date(f.lastModified()); case 1: return new Long(f.length()); default: assert false; } return null; } @Override public boolean isCellEditable(Object node, int column) { return false; } @Override public void setValueFor(Object node, int column, Object value) { //do nothing for now } } Now, after dragging-and-dropping an Outline object onto your JFrame (which is possible after adding the beans from the JAR to the NetBeans IDE Palette Manager) which, in turn, automatically creates a JScrollPane as well, this is how you could code the JFrame's constructor: public NewJFrame() { //Initialize the ui generated by the Matisse GUI Builder, which, //for example, adds the JScrollPane to the JFrame ContentPane: initComponents(); //Here I am assuming we are not on Windows, //otherwise use Utilities.isWindows() ? 1 : 0 //from the NetBeans Utilities API: TreeModel treeMdl = new FileTreeModel(File.listRoots()[0]); //Create the Outline's model, consisting of the TreeModel and the RowModel, //together with two optional values: a boolean for something or other, //and the display name for the first column: OutlineModel mdl = DefaultOutlineModel.createOutlineModel( treeMdl, new FileRowModel(), true, "File System"); //Initialize the Outline object: outline1 = new Outline(); //By default, the root is shown, while here that isn't necessary: outline1.setRootVisible(false); //Assign the model to the Outline object: outline1.setModel(mdl); //Add the Outline object to the JScrollPane: jScrollPane1.setViewportView(outline1); } Alternatively, without the NetBeans Matisse GUI Builder and NetBeans Palette Manager, i.e., simply using a standard Java class, you could do something like this: private Outline outline; public NewJFrame() { setDefaultCloseOperation(EXIT_ON_CLOSE); getContentPane().setLayout(new BorderLayout()); TreeModel treeMdl = new FileTreeModel(File.listRoots()[0]); OutlineModel mdl = DefaultOutlineModel.createOutlineModel( treeMdl, new FileRowModel(), true); outline = new Outline(); outline.setRootVisible(false); outline.setModel(mdl); getContentPane().add(new JScrollPane(outline),BorderLayout.CENTER); setBounds(20, 20, 700, 400); } At this point, you can run the JFrame, with this result: So, we see a lot of superfluous info that doesn't look very nice. Let's implement "org.netbeans.swing.outline.RenderDataProvider", as follows: private class RenderData implements RenderDataProvider { @Override public java.awt.Color getBackground(Object o) { return null; } @Override public String getDisplayName(Object o) { return ((File) o).getName(); } @Override public java.awt.Color getForeground(Object o) { File f = (File) o; if (!f.isDirectory() && !f.canWrite()) { return UIManager.getColor("controlShadow"); } return null; } @Override public javax.swing.Icon getIcon(Object o) { return null; } @Override public String getTooltipText(Object o) { File f = (File) o; return f.getAbsolutePath(); } @Override public boolean isHtmlDisplayName(Object o) { return false; } } Now, back in the constructor, add the renderer to the outline: outline1.setRenderDataProvider(new RenderData()); Run the JFrame again and the result should be the same as in the first screenshot above. Look again at the rendering code and note that, for example, you have tooltips:
June 4, 2008
· 83,982 Views
article thumbnail
Interview: Game Over for the JDK's Date and Time Classes
JSR 310 aims to modernize the date and calendar classes. The goal is to provide a more advanced and comprehensive model for date and time than those found in the Date and Calendar APIs. The JSR's leaders, Stephen Colebourne and Michael Nascimento, are presenting their work at JavaOne and give an overview below. Firstly, please briefly introduce yourselves. Michael Nascimento. I'm a senior technical consultant at Summa technologies and the founder of the Genesis open source project. I have also served as an expert on a few JSRs, such as the Common Annotations for the Java Platform (JSR-250). Stephen Colebourne. I am employed building travel e-commerce booking engines and am involved with many open source projects, such as Apache Commons and JodaTime. I am involved in this JSR because of my JodaTime project. JodaTime? What's that? Stephen: JodaTime provides a complete replacement of the date and time classes in the JDK: public boolean isAfterPayDay(DateTime datetime) { if (datetime.getMonthOfYear() == 2) { // February is month 2!! return datetime.getDayOfMonth() > 26; } return datetime.getDayOfMonth() > 28; } public Days daysToNewYear(LocalDate fromDate) { LocalDate newYear = fromDate.plusYears(1).withDayOfYear(1); return Days.daysBetween(fromDate, newYear); } public boolean isRentalOverdue(DateTime datetimeRented) { Period rentalPeriod = new Period().withDays(2).withHours(12); return datetimeRented.plus(rentalPeriod).isBeforeNow(); } public String getBirthMonthText(LocalDate dateOfBirth) { return dateOfBirth.monthOfYear().getAsText(Locale.ENGLISH); } What are the main things that are wrong with the current date and time classes? Stephen: The existing classes are pretty bad—probably the worst APIs in the JDK. They're buggy, mutable, cumbersome, many bugs, and they tend not to be threadsafe. Michael: The original date class comes from JDK 1.0. At the time, James Gosling tried to follow the related functions in C and didn't put much force into designing them from scratch. For example, they can't be internationalized and only local timezones are supported. Stephen: Right. The Gregorian calendar class is a direct port of the C-class, such as "January = 0". So, if you enter the month "12", the month is January because the algorithm wraps around. The algorithm performs calculations such as this that you don't expect. For example, with the Gregorian calendar class, getYear(), getMonth(), and getDay() are quick, while if you call combinations of getyear(), setyear() (and getMonth() setMonth(), and so on), performance will be bad because lots of calculations are done unexpectedly. Politely put, one can describe these classes as exhibiting "unusual performance characteristics". Why has it taken so long to fix these various problems? Stephen: People have known of these problems for several years. Some attempts have been made to fix the Calendar class, but it only got worse. Fixing these issues once and for all has never been a high enough priority. So why now and why you? Stephen: I started JodaTime in 2000/2001 and gradually solved the standard date and time class problems, releasing it in 2003. My solution has been picked up across the board, from small applications to the largest advertizing systems in the world. The point is that I wanted the solution to exist a few years as JodaTime, before heading into a JSR so that all the issues would have been identified in preparation for the JSR. In a nutshell, what does JodaTime offer me? Michael: Firstly, a better quality API. Stephen: Secondly, JodaTime supports a number of additional concepts. Firstly, "periods", such as if you wanted to store the concept of 5 weeks and 3 days. Secondly, "intervals", so that you'll be able to store the interval between the start of JavaOne and its end, i.e., for example, from Monday May 5, 9 a.m. to May 9, 3 p.m. Thirdly, an updated timezone implementation to make it easy to pick up timezone changes, which could even be on an annual basis. Finally, handling of different calendar systems, such as Islamic calendar systems / Coptic calendar systems, and so on, which don't exist in the standard JDK. Michael: The third point is why I got interested in this JSR in the first place. I'm from Brazil where the daylight saving systems change each year and there's always one or two weeks of chaos. I asked myself why things go wrong every year around this issue. Stephen. Possibly we could offer a solution consisting of a JAR file with the latest set of rules, which you could then put on the classpath. However, sometimes you'd need both sets of rules at the same time. We're still thinking about these situations and ought to be able to come up with something. By the way, where does the name "Joda" come from? Stephen: "Joda" was a 4 letter domain name starting with "J" that was free in 2003. I simply typed random things beginning with "J" and found that that one was free... Where is the JSR process now? Michael: We are progressing it in an open manner. All discussions are on public mailing lists and Wikis. All repositories are open and Issuezilla is open. Stephen: We are using java.net to build a reference implementation and a testing kit in Subversion. People can go there and try it out. It is all "work in progress". The basic API is there. Right now, parsing needs to be finished and some loose ends need to be tidied up. Parsing, intervals, and multiple calendar systems are missing at the moment. Can you say something about the JSR's timeline? Stephen: We hope that we'll be in Java 7, but given that there's no date for it, there's no guarantee that we'll finish in time. We received a little bit of funding from the OpenJDK challenge to get to early draft review by August. Michael: It's really important that people get involved, the last chance to influence design aspects is the early draft review, scheduled for August, which is coming near. Two previous attempts have been made for rewriting these classes and it's unlikely there'll be another one after ours. So it is really important to let your voice be heard because the more feedback we get the better. Stephen: There's been good quality feedback. We've had suggestions consisting of sample implementations of intervals, people pointing to different ISO specifications, and suggestions to expand into areas outside our scope. People should take a look at the algorithms too. Maybe someone could come up with better algorithms than those that we already have. Michael: We've also been nominated for a JCP Program Award, probably because we're the main examples of individuals, rather than a company, leading a JSR. The results will be announced on Tuesday during JavaOne. Will you present something around your JSR at JavaOne? Michael: Our technical session on Thursday at 1.30 is completely full and there's a repeat session on Friday at the same time, that is, at 1.30. In the session, we will cover all the basic classes, show examples of the code and how to get started with it. Stephen: There'll be little bit of explanation around the design principles, with examples of how bad the current date and time classes are. There'll also be a small puzzler, asking participants to identify the number of bugs in an existing bit of JDK code... Further Reading JSR 310 JSR 310 Technical Sessions at JavaOne JSR 310 General Purpose Area for Anyone to Leave Messages JSR 310 Mailing List Stephen Colebourne's blog Michael Nascimento's blog JCP Program's Award Nominations
May 5, 2008
· 13,254 Views
article thumbnail
Visual Debugging for Swing Apps
Two days ago, the 1.0 release of the Swing Explorer was announced. It is a handy tool for examining an application's component hierarchies, properties, events, and threads. Swing Explorer, yet another cool application available on dev.java.net, is handy when debugging your Swing application. In some ways, it is comparable to an AST Viewer, except that it displays component hierarchies instead of an abstract syntax tree. Just as an AST view is crucial when working with the internals of a language, so the Swing explorer is essential in understanding the relationships between components in a Swing application. Below is a case in point, the explorer view on the left showing the complete hierarchy of the application under observation: Of course, an IDE or GUI Builder would provide a similar view. The difference is that, in this case, the above application is deployed from a JAR outside of an IDE. In other words, the application is not in development/production mode, although it could be too. The Swing Explorer starts up your application with this command: java -javaagent:swag.jar -Xbootclasspath/a:swag.jar -cp swexpl.jar; org.swingexplorer.Launcher And that's it. Your own application then starts up, as does the Swing Explorer. Then you can explore the application in the way shown above. Not only the component hierarchy of the application is then exposed, but also all its properties, such as its layout and borders. The tabs at the bottom are very useful too. The "Player" tab lets you observe the order in which the application is constructed and the content is drawn. Some questions that you can have answered by means of the Swing Explorer: "I do not see a component on my JFrame. However, it should be there." "My colleague developed a panel two years ago. I have no idea how it is constructed. I'd like to figure out why a component appears on this place? Why it is shifted 5 pixels to the left?" "I want to debug my application in a Java debugger step by step and watch what each step produces on the screen when I add components into my JFrame." "I see a small dot in the upper right corner, why it is there?" For info on these and related usecases, see Getting Started with Swing Explorer. The "AWT Events" and the "EDT Monitor" tabs are new, providing useful information on AWT and EDT, with further finegrained filtering planned for future releases. Here's the EDT Monitor in action: The plan to provide plugins for Eclipse and NetBeans IDE is also an interesting one. Swing user interface debugging--seems like this tool is perfectly attuned to this need.
April 16, 2008
· 21,891 Views
article thumbnail
1st Binary Release of Java Music Composer
Today marks the availability of the first binary release of the open source JFugue Music NotePad. The core basic functionality of the tool is available and ready to be tried out. After downloading and unzipping the archive, you need to specify the location of the JDK (JDK 5 or above, so Mac users are welcome too), in etc/mnotepad.conf, which is in the unzipped archive's main directory. The binary can be downloaded here: mnotepad_9April2008.zip Once you have done so, you can launch it, which should result in the following main window at start up: Here it is on the Mac: Then choose File | New, to define a new composition: Click Finish and you can begin composing music. To do so, choose notes from the toolbar and point/click to add them to the composition. Currently you can't add notes between existing notes. However, select one/more notes with your mouse, the notes turn red to show they are selected, and then use up/down to move notes up the scale and left/right to decrease/increase their length. While doing this part of the work, compositions typically look something like this: You can change instruments by right-clicking one in the Instruments window and choosing "Select". Finally, click Play to play the music or Save to save it. Compositions are saved to disk in midi format, the status bar shows where they are saved to, in the installation directory. Architecture. Instead of dealing directly with the Midi API, the JFugue API is used instead. The JFugue API provides an extremely transparent, simple, yet surprisngly powerful layer of functionality on top of the complexities of typical Midi programming. The user interface is pure Swing on top of the NetBeans Platform, therefore the application has a very mature window system (max/minimize, dock/undock) and is pluggable out of the box, among other features. User Comments. One of the user comments thus far: "It's definitely very cool! And as promised, you already got a whole bunch of subtle features for free from the NetBeans Platform (windowing, favorites, etc). :-D It already looks more stable and trustworthy than any other app with the same amount of work invested, just because of the solid and consistent windowing system." Known Issues. Amongst others, the following: several usability issues, such as that it isn't easy to know/see from the ui that notes can be changed by selecting them and moving up/down/left/right. Should be able to specify where saved midi file should be saved to. Some users report not being able to change instruments. Keyboard window currently unused. Playing of tune blocks the ui. Feedback Welcome. The JFugue Music NotePad is an open source project at https://nbjfuguesupport.dev.java.net/. You are welcome to join, especially if you are able to offer time/insight to add missing features. Especially programmers who are also musicians are welcome. For example, this application could do with a metronome, which could be provided by a separate plugin...
April 9, 2008
· 12,771 Views
article thumbnail
Spring: How to Create Decoupled Swing Components
The Spring Framework's applicability in the context of Swing seems to be underhighlighted, at least when one looks around on the web.
April 5, 2008
· 61,734 Views
article thumbnail
How to Create a Pluggable Photo Album in Java
Here you see a simple photo album I created in Java Swing. It is, by no definition of the term, a great photo album. However, the point is that none of the photos you see are provided by the application itself. Nor do they come from the web. So... where do they come from and how did they end up in my photo album? Read on to find out... Here's a clue. All that you would need to provide in order to add photos to my photo album is a Java application that is structured as follows: The images "demo1.png" and "demo2.png" are two of the four photos you see in the first screenshot, i.e., the screenshot of my photo album. The other two photos you see there come from another Java application, which is structured in exactly the same way as the above. "Ah," you might now think. "This article is all about the Java SE 6 java.util.ServiceLoader class. I guess I'll need to be using Java SE 6 and then I'll be able to construct small applications structured like the above and then I'll be able to plug into your photo album." Wrong. You don't need Java SE 6 at all. Although, you're close. Here's the definition of the VacPhotos class that you see in the illustration above: package com.example.vacphotos; import javax.swing.Icon; import javax.swing.ImageIcon; import photoalbumapp.Photo; public class VacPhotos implements Photo { ImageIcon icon1 = new ImageIcon(getClass().getResource("/com/example/vacphotos/demo1.png")); ImageIcon icon2 = new ImageIcon(getClass().getResource("/com/example/vacphotos/demo2.png")); public VacPhotos() { } @Override public Icon[] getPhoto() { Icon[] icons = new Icon[]{icon1, icon2}; return icons; } @Override public String[] getDescription() { String[] descs = new String[]{"pic 1", "pic2"}; return descs; } } In other words, you simply need to extend the photoalbumapp.Photo class, which the photo album itself makes available, meaning you need its JAR on your plugin's classpath. The photo album is an empty application shell that exposes the Photo class, with its two methods getPhoto and getDescription. You therefore need to create a Java class that implements those two methods, returning arrays of Icons and Strings for the photos you'd like to integrate into the photo album. Finally, you need to create a file in your META-INF.services folder, with the name of the class that you are implementing, which in this case is photoalbumapp.Photo. Within that file you need nothing more than one line, which is the FQN of your implementation class: com.example.vacphotos.VacPhotos And that's all. Now, when the JAR of your app is on the classpath of the photo album, your photos and descriptions will automatically be integrated with all the photos provided by all the other implementations of the same class. The cool thing is that the photo album is an implementation of JSR-296, the Swing Application Framework, so that lifecycle management and persistance, as well as other typical application services, are dealt with by the framework itself. For example, I don't need to provide any code for the user's resizings and repositionings to be saved across restarts. The most important part, in this context, of my photo album application (i.e., this is a totally separate application to the VacationPhotos application above), is the code that defines my photo service: package photoalbumapp; import java.util.Collection; import org.openide.util.Lookup; import org.openide.util.Lookup.Result; import org.openide.util.Lookup.Template; public class PhotoService { private static PhotoService service; private Lookup photoLookup; private Collection photos; private Template photoTemplate; private Result photoResults; private PhotoService() { photoLookup = Lookup.getDefault(); photoTemplate = new Template(Photo.class); photoResults = photoLookup.lookup(photoTemplate); photos = photoResults.allInstances(); } public static synchronized PhotoService getInstance() { if (service == null) { service = new PhotoService(); } return service; } public Collection getDefinitions() { return photos; } } The template lookup method returns a Result instance that contains multiple providers, if they exist. You can retrieve the entire collection of providers by calling the Result instance's allInstances method, which is exactly what is done above. Here you see that we are not dealing with the Java SE 6 ServiceLoader class (nor its earlier incarnations, which have been in the JDK since JDK 1.3). Instead, we are dealing with the NetBeans Platform's org.openide.util.Lookup class. Above, I have provided the bridge between your VacationPhotos application and my own separate application that provides the photo album. The bridge is accessed by the photo album to retrieve photos and descriptions. The bridge, in its role as a "service", will, in turn, access all the classes that implement the Photo implementers, as defined in the small Java applications that exist for no other reason than to provide photos, such as the VacPhotos application shown earlier. And how is the service used? The main JFrame constructor in the photo album is as follows, really simplistic as you can see: ... ... ... private PhotoService photo; public PhotoAlbum() { photo = PhotoService.getInstance(); initComponents(); JPanel content = new JPanel(); content.setLayout(new FlowLayout()); Collection coll = photo.getDefinitions(); Iterator it = coll.iterator(); while (it.hasNext()) { Photo photo = it.next(); Icon[] icons = photo.getPhoto(); String[] strings = photo.getDescription(); for (int i = 0; i < icons.length; i++) { JLabel imageLabel = new JLabel(); imageLabel.setBorder(BorderFactory.createLineBorder(Color.red)); Icon icon = icons[i]; String desc = strings[i]; imageLabel.setIcon(icon); imageLabel.setText(desc); content.add(imageLabel); } } setContentPane(content); } ... ... ... And that's really all. Now, what are the benefits of using the NetBeans Platform's org.openide.util.Lookup class instead of the JDK's ServiceLoader class? Lookup is available in versions for older JDKs and thus you can use it as a replacement of ServiceLoader when running on JDKs older than 1.6. Lookup is ready to work inside of the NetBeans runtime container, so makes even more sense when you're working with NetBeans modules. It knows how to discover all the modules in the system, how to effectively read its defined services, and similar activities. Lookup supports listeners. Client code can attach a listener and observe changes in lookup content. This is a necessary improvement to adapt to the dynamic environment created by the NetBeans runtime container, where modules can be enabled or disabled at runtime, which in turn can affect the set of registered service providers. Lookup is extensible and replaceable. While the ServiceLoader class in JDK 1.6 is a final class with hard-coded behavior, the NetBeans Lookup class is an extensible class that allows various implementations. This can be useful while writing unit tests. Or you can write an enhanced version of lookup that not only reads META-INF/services but, for example, finds the requested service providers around the Internet. Lookup is a general purpose abstraction. While the JDK's ServiceLoader can de-facto have just one instance per classloader, there can be thousands of independent Lookup instances, each representing a single place to query services and interfaces. In fact this is exactly the way Lookup is used in NetBeans IDE—it represents the context of each dialog, window element, node in a tree, etc. And now you know all that's needed for treating Java applications as plugins. (For further information, see John O'Conner's Creating Extensible Applications With the Java Platform.) In summary, by means of registration and discovery of classes and interfaces, loosely coupled photo albums, and similar applications, are clearly very easy to achieve.
March 16, 2008
· 47,107 Views

Refcards

Refcard #080

Essential NetBeans Platform

Essential NetBeans Platform

Refcard #014

NetBeans IDE 7 Java Editor

NetBeans IDE 7 Java Editor

Comments

How To Write a NetBeans Plugin

Dec 27, 2014 · Priyanka Sharma

Many more tutorials on NetBeans plugins here:

https://netbeans.org/features/platform/all-docs.html

JavaFX Accordion Slide Out Menu for the NetBeans Platform

May 20, 2013 · Geertjan Wielenga

Great article, many thanks for writing it, indeed in the context of maps and globes, this is a great solution.

Styling a JavaFX Control with CSS

Jan 07, 2012 · Toni Epple

This is cool! Looking forward to styling my NetBeans Platform application with CSS...
Real-Time Charts on the Java Desktop

Nov 23, 2010 · Geertjan Wielenga

Like I said in the comments to the blog entry, you need org-openide-util.jar, which is in the "lib/visualvm/platform/lib" folder in the JDK.
Real-Time Charts on the Java Desktop

Nov 23, 2010 · Geertjan Wielenga

Like I said in the comments to the blog entry, you need org-openide-util.jar, which is in the "lib/visualvm/platform/lib" folder in the JDK.
Real-Time Charts on the Java Desktop

Nov 23, 2010 · Geertjan Wielenga

Like I said in the comments to the blog entry, you need org-openide-util.jar, which is in the "lib/visualvm/platform/lib" folder in the JDK.
Let's Create... Our Own SQL Editor

Sep 11, 2010 · Geertjan Wielenga

symbol : variable WindowManager
location: class org.sqleditor.branding.Installer
WindowManager.getDefault().inkoveWhenUIReady(
3 errors

From the above, you can see that you need "WindowManager" class. That's part of the Window System API. Add that module as a dependency to your module: go to the Project Properties dialog of the module and add "Window System API" as one of the APIs that the module depends on. Apologies, I should have specified that in the instructions above!

Let's Create... Our Own SQL Editor

Sep 07, 2010 · Geertjan Wielenga

Yup, good point. Leave more messages here if you find other things, would be very helpful.
Let's Create... Our Own SQL Editor

Sep 07, 2010 · Geertjan Wielenga

Yup, good point. Leave more messages here if you find other things, would be very helpful.
Let's Create... Our Own SQL Editor

Sep 07, 2010 · Geertjan Wielenga

Yup, good point. Leave more messages here if you find other things, would be very helpful.
Let's Create... Our Own SQL Editor

Sep 07, 2010 · Geertjan Wielenga

Yup, good point. Leave more messages here if you find other things, would be very helpful.
Let's Create... Our Own SQL Editor

Sep 07, 2010 · Geertjan Wielenga

Here it is: http://platform.netbeans.org/tutorials/nbm-visual_library2.html
Let's Create... Our Own SQL Editor

Sep 07, 2010 · Geertjan Wielenga

Here it is: http://platform.netbeans.org/tutorials/nbm-visual_library2.html
Let's Create... Our Own SQL Editor

Sep 07, 2010 · Geertjan Wielenga

Here it is: http://platform.netbeans.org/tutorials/nbm-visual_library2.html
Let's Create... Our Own SQL Editor

Sep 07, 2010 · Geertjan Wielenga

Here it is: http://platform.netbeans.org/tutorials/nbm-visual_library2.html
Complete List of Macro Keywords for the NetBeans Java Editor

Apr 01, 2010 · Geertjan Wielenga

http://wiki.netbeans.org/FaqEditorMacros
Top 10 Interesting NetBeans IDE Java Shortcuts I Never Knew Existed

Mar 27, 2010 · Geertjan Wielenga

Expand selection is Alt-Shift-period, the opposite way is Alt-Shift-comma. Does that help you, Willis?
Top 10 Interesting NetBeans IDE Java Shortcuts I Never Knew Existed

Feb 19, 2010 · Geertjan Wielenga

The saving is that you don't need to look for the asterisk and the slash, nor hold down the Shift key.
How to Create a Java EE 6 Application with JSF 2, EJB 3.1, JPA, and NetBeans IDE 6.8

Dec 30, 2009 · Christopher Lam

Download link works fine for me:

http://netbeans.dzone.com/sites/all/files/CustomerApp_PrimeFaces.zip

How to Create a Swing CRUD Application on NetBeans Platform 6.8

Dec 14, 2009 · Geertjan Wielenga

Hi surajchchetry, that's a great idea. If I understand it correctly. This is the kind of project structure I am creating at the moment, for a new tutorial, based on your suggestion above.

A new tutorial should appear within the next week or two, to explain how to create project structures like the above, with a bunch of additional features too, as described here in my blog!

How to Create a Swing CRUD Application on NetBeans Platform 6.8

Dec 14, 2009 · Geertjan Wielenga

I already replied. You want a CRUD tutorial, well, this IS a CRUD tutorial.
How to Create a Swing CRUD Application on NetBeans Platform 6.8

Dec 13, 2009 · Geertjan Wielenga

Hi Florian, that would be wonderful and is something I've been thinking of working on... sometime... when I have the time to do so... At least now there is a tutorial (the one to which these are the comments) describing how to do it and, yes, the next step would be to have a wizard that generates the code and you'd use the tutorial to understand what's been generated.
How to Create a Swing CRUD Application on NetBeans Platform 6.8

Dec 09, 2009 · Geertjan Wielenga

Excellent feedback, ringerc. That will be fixed. Thank you. One approach is to register actions in the layer file which then enables you to add an attribute to the layer entry. That attribute causes the action to be processed asynchronously, (which is a new feature in 6.8, i.e., the ability to mark an action as being asynchronous). These asynchronous actions can simulate SwingWorker:

class MyAction implements ActionListener, Runnable {
public MyAction(MyContext c) {
assert EventQueue.isEventThread();
// setup inside AWT thread, get what is important from c
}
public void actionPerformed(AE ev) {
assert !EventQueue.isEventThread();
// run off AWT thread
// perform the work
SwingUtilities.invokeLater(this);
}

public void run() {
assert EventQueue.isEventThread();
// finish in AWT and update the UI
}
}

Another approach would be to use SwingWorker. These approaches will be added to the article, though note that threading on the NetBeans Platform is also discussed here: http://wiki.netbeans.org/NetBeansDeveloperFAQ#Threading

Something else that's possible is to integrate with the NetBeans progress bar, which can be achieved with, literally, 3 lines of code.

How to Split an Application into Modules?

Dec 02, 2009 · Geertjan Wielenga

Great feedback. Maybe a refcard on modulerization should be created. The basic principles listed above are great starting points. It's also cool to see that various module systems have the same basic rationales underpinning them.

Also, based on the above various comments, could one perhaps say: "when in doubt about whether or not to create another module, go ahead and do so"? I.e., the fact that you're thinking about it is probably a reason to go ahead and follow that impulse, since it is probably appropriate in your context.

How to Create Modular Groovy Applications in 5 Steps!

Mar 05, 2009 · Geertjan Wielenga

Hi Matt. Right now NetBeans uses the standard JDK approach, that is, META-INF/services for the communication between modules, which are similar to OSGi bundles, except that the Manifest has NetBeans-specific keys, instead of OSGi keys, which is probably not going to change. OSGi will be supported in the sense that you'll be able to create OSGi bundles in NetBeans IDE, not in the sense that NetBeans IDE will run on OSGi. For more on the NetBeans module system, watch this screencast: http://mediacast.sun.com/users/GWiel/media/top10-netbeans-apis-part1.flv/details
Using IntelliJ IDEA for NetBeans Platform Development

Mar 05, 2009 · Geertjan Wielenga

Not necessarily. Firstly, "no", because the approach taken in step 4 could probably be done in a better way. Secondly, "no", because you could do the build step anywhere (e.g., outside NetBeans IDE, from the command line or inside IntelliJ, using the build script).
How to Create Modular Groovy Applications in 5 Steps!

Feb 14, 2009 · Geertjan Wielenga

Good question. Modularity is not everybody's cup of tea. Though it provides no extra overhead (or the advantages outweigh any overhead you might have), not all applications need/want this kind of architecture, for personal reasons of taste and style, etc. Also, for small applications, i.e., those for which there is no plan to ever make larger than 'small', Griffon is definitely preferable.
Hello EclipseLink on the NetBeans Platform

Jan 17, 2009 · Geertjan Wielenga

[quote=miguelgl]

I only find a drawback: Whenever I need to make changes to entity library (which is a regular NB IDE Java Library Project), I am then also required to manually copy the new generated .jar file into the NB platform library wrapper module project (step nr. 2 in the post). In fact, I need to copy it directly to the project directory, having to have a knowledge on its filesystem layout.

This makes it not really agile if the above happens often (which, BTW, is my case).

[/quote]

Workaround: create a new Ant target and include it in your build process. During the build, the JAR will be created afresh in the NetBeans module, automatically, without you needing to do anything special (once you've created that Ant target). (See "Updating the Sources" here.)

Hello EclipseLink on the NetBeans Platform

Jan 17, 2009 · Geertjan Wielenga

[quote=miguelgl]

I only find a drawback: Whenever I need to make changes to entity library (which is a regular NB IDE Java Library Project), I am then also required to manually copy the new generated .jar file into the NB platform library wrapper module project (step nr. 2 in the post). In fact, I need to copy it directly to the project directory, having to have a knowledge on its filesystem layout.

This makes it not really agile if the above happens often (which, BTW, is my case).

[/quote]

Workaround: create a new Ant target and include it in your build process. During the build, the JAR will be created afresh in the NetBeans module, automatically, without you needing to do anything special (once you've created that Ant target). (See "Updating the Sources" here.)

Hello EclipseLink on the NetBeans Platform

Jan 17, 2009 · Geertjan Wielenga

[quote=miguelgl]

I'm also considering filling in a bug report on this, as I do not really happen to see any justification for this fact. Having solved that, one could keep developing a Suite (or NBP-based app.) which does include a "JPA-enabled" module all within the great NB IDE and also let it keep track of all dependencies.

[/quote]

+1 on that! Here's my issue on this, please go in there and agree with me:

http://www.netbeans.org/issues/show_bug.cgi?id=155214

Thanks for liking my humor, nice to hear. :-)

Hello EclipseLink on the NetBeans Platform

Jan 17, 2009 · Geertjan Wielenga

[quote=miguelgl]

I'm also considering filling in a bug report on this, as I do not really happen to see any justification for this fact. Having solved that, one could keep developing a Suite (or NBP-based app.) which does include a "JPA-enabled" module all within the great NB IDE and also let it keep track of all dependencies.

[/quote]

+1 on that! Here's my issue on this, please go in there and agree with me:

http://www.netbeans.org/issues/show_bug.cgi?id=155214

Thanks for liking my humor, nice to hear. :-)

Calling JavaFX From Java?

Dec 10, 2008 · Geertjan Wielenga

Hi Alex, you need to put a whole bunch of JavaFX JARs on your app's classpath to make it possible. (To save time, I simply put all of them there, i.e., every JAR in the JavaFX distro.) Then put Jim's FX file in a package and the Java class you see above there too.
Calling JavaFX From Java?

Dec 10, 2008 · Geertjan Wielenga

Thanks all for the comments: good to see I'm not alone in yearning for the marriage of JavaFX with Java! I agree with Michael Bien that it feels like reflection, i.e., some kind of workaround, though. On the (very!) bright side, I received an e-mail from Josh Marinacci with these words: "I'm in belgium and have forgotten my login so i couldn't comment on your blog. Can you post an update that soon we'll have some code that shows you how to properly embed a javafx scene into a swing application."
Taking the New Swing Tree Table for a Spin

Nov 30, 2008 · Geertjan Wielenga

Create a Java Application. Then use the JFrame template (in the New File dialog) to create a JFrame. Thanks.
Quick Start: Creating Language Tools In NetBeans IDE

Jul 02, 2008 · Jordi R Cardona

Here are some other articles on this topic that might be found useful:

http://www.netbeans.org/community/magazine/html/03/schliemann/

http://www.netbeans.org/community/magazine/html/04/schliemann.html

http://platform.netbeans.org/tutorials/60/nbm-prolog.html

Visual Debugging for Swing Apps

Apr 17, 2008 · Geertjan Wielenga

@Shay: wow that stuff in JDeveloper looks cool. I think I might take JDeveloper for a spin soon especially for that reason.

@shaulgo: you're right, without the sources debugging would be problematic. However, I really like the idea of being able to look at the internals of a Swing app where I would simply have the JAR and nothing else. Just for the fun of it, but I'm guessing there'd be practical reaons too.

@Maxim, congrats with this cool tool and hope to catch up with you at JavaOne!

Visual Debugging for Swing Apps

Apr 16, 2008 · Geertjan Wielenga

Probably every IDE has such a thing. However, as pointed out in this article, this particular application is not part of an IDE. This has several advantages, such as the fact that it is lightweight and it is useful for debugging JAR files for which you might not even have the sources available.
1st Binary Release of Java Music Composer

Apr 10, 2008 · Geertjan Wielenga

Thanks all for the comments! Yes, several things need to be worked on still (as indicated in the "Known Issues" above, which already listed most of the issues in these comments). By the way, you can't open files into the composer yet, as Mike P above tried to do, you can only create new music. External MIDI keyboards can't be hooked up yet, but that's a plan for the future. Don't know about the bitmap question, someone else on the project worked on that part. Thanks for the tips for getting Java sound working on Linux, because I have the same problem too since moving to Gutsy Gibbon!
Spring: How to Create Decoupled Swing Components

Apr 08, 2008 · Geertjan Wielenga

[quote=cm38280]

This whole thing is such a bad idea on so many levels. If you have a good UI design, why do you want to move stuff around?

[/quote]

As pointed out by one or two people above, maybe you have different end users and the person doing the packaging is not a Java programmer. The Spring config file would be a way for the assembler, a non Java programmer, to assemble an application from the decoupled Swing components provided by the programmer.

[quote=cm38280]

How do people maintaining your code figure out where some panel class MyPanel exists within your application?

[/quote]

Most IDEs (at least NetBeans does, for sure) have support within Spring config files exactly for that purpose. You can click on a reference to a Java source file and then the source file in question opens. You also have code completion for the value of the "class" attribute, so that can be used for filling in the values and verifying that the referenced class actually exists.

[quote=cm38280]

Spring is fantastic at configuring "service" classes which can be accessed from within an app but it is not an appropriate XML description on so many levels for configuring instances of any old POJO (whether that be data classes or GUI components).

[/quote]

I agree that this approach is probably atypical. But at the same time there could be scenarios out there where this could be useful. And the XML would not necessarily be reams and reams of tags either -- possibly you'd have three or four panels that could be exchanged with each other and the assembler would do this via the Spring config file. Again, I'm not making this scenario up myself -- look at the comments above where at least one respondent sees this as being applicable to their real life needs.

[quote=cm38280]

I see "bean, I see "property", I see "value" and I see "list" but nowhere do I get a feel for what the panel contains nor its layout.

[/quote]

In the scenario of there being an assembler of the application, that's not relevant, they don't need to see the panel (or other decoupled Swing component) in question. However, if they do want to see the layout or other content, they can simply click to it from the Spring config file (as pointed out above).

[quote=cm38280]

Just take one step back and look at the sheer awfulness of the XML you've posted above!

  • How would you integrate this with GridBagLayout? Or BoxLayout? Via the MethodInvokingFactoryBean?
  • How would you reconcile the above with the rule of thumb that each GUI component should have a no-arg constructor?
  • How do you quickly view sub-panels of your app, without creating reams and reams of near identical Spring config files?

[/quote]

I think I've responded to these points. I'm not arguing that this is useful for each and every Swing app, I'm just pointing out that this is possible in those cases where it makes sense.

Spring: How to Create Decoupled Swing Components

Apr 08, 2008 · Geertjan Wielenga

[quote=cm38280]

This whole thing is such a bad idea on so many levels. If you have a good UI design, why do you want to move stuff around?

[/quote]

As pointed out by one or two people above, maybe you have different end users and the person doing the packaging is not a Java programmer. The Spring config file would be a way for the assembler, a non Java programmer, to assemble an application from the decoupled Swing components provided by the programmer.

[quote=cm38280]

How do people maintaining your code figure out where some panel class MyPanel exists within your application?

[/quote]

Most IDEs (at least NetBeans does, for sure) have support within Spring config files exactly for that purpose. You can click on a reference to a Java source file and then the source file in question opens. You also have code completion for the value of the "class" attribute, so that can be used for filling in the values and verifying that the referenced class actually exists.

[quote=cm38280]

Spring is fantastic at configuring "service" classes which can be accessed from within an app but it is not an appropriate XML description on so many levels for configuring instances of any old POJO (whether that be data classes or GUI components).

[/quote]

I agree that this approach is probably atypical. But at the same time there could be scenarios out there where this could be useful. And the XML would not necessarily be reams and reams of tags either -- possibly you'd have three or four panels that could be exchanged with each other and the assembler would do this via the Spring config file. Again, I'm not making this scenario up myself -- look at the comments above where at least one respondent sees this as being applicable to their real life needs.

[quote=cm38280]

I see "bean, I see "property", I see "value" and I see "list" but nowhere do I get a feel for what the panel contains nor its layout.

[/quote]

In the scenario of there being an assembler of the application, that's not relevant, they don't need to see the panel (or other decoupled Swing component) in question. However, if they do want to see the layout or other content, they can simply click to it from the Spring config file (as pointed out above).

[quote=cm38280]

Just take one step back and look at the sheer awfulness of the XML you've posted above!

  • How would you integrate this with GridBagLayout? Or BoxLayout? Via the MethodInvokingFactoryBean?
  • How would you reconcile the above with the rule of thumb that each GUI component should have a no-arg constructor?
  • How do you quickly view sub-panels of your app, without creating reams and reams of near identical Spring config files?

[/quote]

I think I've responded to these points. I'm not arguing that this is useful for each and every Swing app, I'm just pointing out that this is possible in those cases where it makes sense.

Spring: How to Create Decoupled Swing Components

Apr 08, 2008 · Geertjan Wielenga

[quote=cm38280]

This whole thing is such a bad idea on so many levels. If you have a good UI design, why do you want to move stuff around?

[/quote]

As pointed out by one or two people above, maybe you have different end users and the person doing the packaging is not a Java programmer. The Spring config file would be a way for the assembler, a non Java programmer, to assemble an application from the decoupled Swing components provided by the programmer.

[quote=cm38280]

How do people maintaining your code figure out where some panel class MyPanel exists within your application?

[/quote]

Most IDEs (at least NetBeans does, for sure) have support within Spring config files exactly for that purpose. You can click on a reference to a Java source file and then the source file in question opens. You also have code completion for the value of the "class" attribute, so that can be used for filling in the values and verifying that the referenced class actually exists.

[quote=cm38280]

Spring is fantastic at configuring "service" classes which can be accessed from within an app but it is not an appropriate XML description on so many levels for configuring instances of any old POJO (whether that be data classes or GUI components).

[/quote]

I agree that this approach is probably atypical. But at the same time there could be scenarios out there where this could be useful. And the XML would not necessarily be reams and reams of tags either -- possibly you'd have three or four panels that could be exchanged with each other and the assembler would do this via the Spring config file. Again, I'm not making this scenario up myself -- look at the comments above where at least one respondent sees this as being applicable to their real life needs.

[quote=cm38280]

I see "bean, I see "property", I see "value" and I see "list" but nowhere do I get a feel for what the panel contains nor its layout.

[/quote]

In the scenario of there being an assembler of the application, that's not relevant, they don't need to see the panel (or other decoupled Swing component) in question. However, if they do want to see the layout or other content, they can simply click to it from the Spring config file (as pointed out above).

[quote=cm38280]

Just take one step back and look at the sheer awfulness of the XML you've posted above!

  • How would you integrate this with GridBagLayout? Or BoxLayout? Via the MethodInvokingFactoryBean?
  • How would you reconcile the above with the rule of thumb that each GUI component should have a no-arg constructor?
  • How do you quickly view sub-panels of your app, without creating reams and reams of near identical Spring config files?

[/quote]

I think I've responded to these points. I'm not arguing that this is useful for each and every Swing app, I'm just pointing out that this is possible in those cases where it makes sense.

Spring: How to Create Decoupled Swing Components

Apr 07, 2008 · Geertjan Wielenga

johan and robert, I fixed the EDT problem. Is there someone here who has used the approach to Spring that is described here, i.e., in a desktop environment? I'd be interested in interviewing you for Javalobby, if so.
Spring: How to Create Decoupled Swing Components

Apr 07, 2008 · Geertjan Wielenga

[quote=dwdyer]

Making sure that your components are decoupled and easy to test is all very well, but you don't need to use Spring to achieve that. You could just as easily use all of the decoupled classes that you have written but wire them together in some Java code.

I fail to see the advantage of 100s of lines of XML, several JAR dependencies and moving errors from compile time to runtime, over a much more concise Java wiring of the components.

[/quote]

I think there might be several reasons why one would take this approach. A simple usecase might be if the developer/s is/are already familiar with Spring in the context of the web/Java EE world. In that context, it would be nice to continue using the same framework within the desktop space.

Secondly, imagine that, instead of 4 or 5 Swing components as in this example, you had dozens, or even hundreds or thousands. Having one centralized location where you manage the interactions between these components can only be a good thing, right? Because in that case your wiring code would be spread across MANY Java classes, I don't believe having a single Java class handling all the interactions of thousands of Swing components would be conceivable.

Spring: How to Create Decoupled Swing Components

Apr 07, 2008 · Geertjan Wielenga

[quote=dwdyer]

Making sure that your components are decoupled and easy to test is all very well, but you don't need to use Spring to achieve that. You could just as easily use all of the decoupled classes that you have written but wire them together in some Java code.

I fail to see the advantage of 100s of lines of XML, several JAR dependencies and moving errors from compile time to runtime, over a much more concise Java wiring of the components.

[/quote]

I think there might be several reasons why one would take this approach. A simple usecase might be if the developer/s is/are already familiar with Spring in the context of the web/Java EE world. In that context, it would be nice to continue using the same framework within the desktop space.

Secondly, imagine that, instead of 4 or 5 Swing components as in this example, you had dozens, or even hundreds or thousands. Having one centralized location where you manage the interactions between these components can only be a good thing, right? Because in that case your wiring code would be spread across MANY Java classes, I don't believe having a single Java class handling all the interactions of thousands of Swing components would be conceivable.

Spring: How to Create Decoupled Swing Components

Apr 07, 2008 · Geertjan Wielenga

[quote=dwdyer]

Making sure that your components are decoupled and easy to test is all very well, but you don't need to use Spring to achieve that. You could just as easily use all of the decoupled classes that you have written but wire them together in some Java code.

I fail to see the advantage of 100s of lines of XML, several JAR dependencies and moving errors from compile time to runtime, over a much more concise Java wiring of the components.

[/quote]

I think there might be several reasons why one would take this approach. A simple usecase might be if the developer/s is/are already familiar with Spring in the context of the web/Java EE world. In that context, it would be nice to continue using the same framework within the desktop space.

Secondly, imagine that, instead of 4 or 5 Swing components as in this example, you had dozens, or even hundreds or thousands. Having one centralized location where you manage the interactions between these components can only be a good thing, right? Because in that case your wiring code would be spread across MANY Java classes, I don't believe having a single Java class handling all the interactions of thousands of Swing components would be conceivable.

Spring: How to Create Decoupled Swing Components

Apr 07, 2008 · Geertjan Wielenga

[quote=dwdyer]

Making sure that your components are decoupled and easy to test is all very well, but you don't need to use Spring to achieve that. You could just as easily use all of the decoupled classes that you have written but wire them together in some Java code.

I fail to see the advantage of 100s of lines of XML, several JAR dependencies and moving errors from compile time to runtime, over a much more concise Java wiring of the components.

[/quote]

I think there might be several reasons why one would take this approach. A simple usecase might be if the developer/s is/are already familiar with Spring in the context of the web/Java EE world. In that context, it would be nice to continue using the same framework within the desktop space.

Secondly, imagine that, instead of 4 or 5 Swing components as in this example, you had dozens, or even hundreds or thousands. Having one centralized location where you manage the interactions between these components can only be a good thing, right? Because in that case your wiring code would be spread across MANY Java classes, I don't believe having a single Java class handling all the interactions of thousands of Swing components would be conceivable.

How to Create Visual Applications in Java?

Apr 02, 2008 · Geertjan Wielenga

Thanks. :-)

Part 2 was published sometime ago already:

http://java.dzone.com/news/how-add-resize-functionality-v

VisualVM: Free and Open Source Java Troubleshooter

Mar 04, 2008 · Geertjan Wielenga

Hi Mark. That's an extremely good question. The answer is that VisualVM is a business layer on top of the NetBeans Platform. The objects you work with in VisualVM are "DataSource", "Application", "Host", "DataSourceView", "ThreadDump", etc. That is a business layer on top of the typical NetBeans Platform concepts of "Node", "DataObject", "TopComponent", etc. In other words, life is much easier for you without the Nodes API because the business layer lets you work on a higher (and more logical) level.
Binding a JTable to Swing Controls in NetBeans IDE

Feb 22, 2008 · Geertjan Wielenga

In answer to your latter question, you can right-click the Libraries node, choose Add Library, and then scroll to Swing Application Framework. Then you have two new JARs that should provide everything you need.
Binding a JTable to Swing Controls in NetBeans IDE

Feb 21, 2008 · Geertjan Wielenga

Hi Richard, I'm not completely clear about what exactly you're wanting to bind to what. What are the POJOs exactly? And what are you trying to bind them to? What is the end result you're trying to achieve, exactly?
Binding a JTable to Swing Controls in NetBeans IDE

Feb 21, 2008 · Geertjan Wielenga

Here are some tips for Hermien:

http://www.techienuggets.com/Comments?tx=2752

Binding a JTable to Swing Controls in NetBeans IDE

Feb 21, 2008 · Geertjan Wielenga

Hi Hermien. I'm not sure if there's tooling for what you describe. I would write to [email protected] and ask this question there. I agree with you that handcoding the necessities must be possible, though whether/how there is tooling is a different question, and I doubt it.
Lorem Ipsum: Now Generated in Java

Feb 19, 2008 · Geertjan Wielenga

Ah, Xelipe, it's all Greek to me...
Plugging into Lobo's Pure Java Web Browser

Feb 06, 2008 · Geertjan Wielenga

Jacek, I agree with you that not everything must be in Java. However, on the other hand, I find these arguments from the Lobo page pretty convincing in this regard, under the heading "Why a Pure Java Browser?":

There are a number of advantages to be derived from a browser that is written in Java as opposed to a language compiled into native code, namely:
  • Security.- In principle, a Java program is less suceptible to certain types of vulnerabilities such as a buffer overflow attack. Java's security model can also allow web content to have access to a complex set of APIs, except in a controlled sandbox.
  • Extensibility.- A Java-based application can be extended via powerful cross-platform plugins. Consider the difference this has made for Java software such as jEdit and Eclipse. (Lobo already has a plugin API).
  • New paradigms.- With the help of Java we can implement new powerful cross-platform and secure mechanisms to represent web content. We would like to make it easy to integrate arbitrary UI languages into Lobo. We would also like to support JavaFX by default as a first-class citizen. But we also plan to allow, for example, representation of web content merely as Java source code.
  • Portability.- This is the obvious advantage of a pure Java application.
Plugging into Lobo's Pure Java Web Browser

Feb 06, 2008 · Geertjan Wielenga

Jacek, I agree with you that not everything must be in Java. However, on the other hand, I find these arguments from the Lobo page pretty convincing in this regard, under the heading "Why a Pure Java Browser?":

There are a number of advantages to be derived from a browser that is written in Java as opposed to a language compiled into native code, namely:
  • Security.- In principle, a Java program is less suceptible to certain types of vulnerabilities such as a buffer overflow attack. Java's security model can also allow web content to have access to a complex set of APIs, except in a controlled sandbox.
  • Extensibility.- A Java-based application can be extended via powerful cross-platform plugins. Consider the difference this has made for Java software such as jEdit and Eclipse. (Lobo already has a plugin API).
  • New paradigms.- With the help of Java we can implement new powerful cross-platform and secure mechanisms to represent web content. We would like to make it easy to integrate arbitrary UI languages into Lobo. We would also like to support JavaFX by default as a first-class citizen. But we also plan to allow, for example, representation of web content merely as Java source code.
  • Portability.- This is the obvious advantage of a pure Java application.
Plugging into Lobo's Pure Java Web Browser

Feb 06, 2008 · Geertjan Wielenga

Jacek, I agree with you that not everything must be in Java. However, on the other hand, I find these arguments from the Lobo page pretty convincing in this regard, under the heading "Why a Pure Java Browser?":

There are a number of advantages to be derived from a browser that is written in Java as opposed to a language compiled into native code, namely:
  • Security.- In principle, a Java program is less suceptible to certain types of vulnerabilities such as a buffer overflow attack. Java's security model can also allow web content to have access to a complex set of APIs, except in a controlled sandbox.
  • Extensibility.- A Java-based application can be extended via powerful cross-platform plugins. Consider the difference this has made for Java software such as jEdit and Eclipse. (Lobo already has a plugin API).
  • New paradigms.- With the help of Java we can implement new powerful cross-platform and secure mechanisms to represent web content. We would like to make it easy to integrate arbitrary UI languages into Lobo. We would also like to support JavaFX by default as a first-class citizen. But we also plan to allow, for example, representation of web content merely as Java source code.
  • Portability.- This is the obvious advantage of a pure Java application.
Plugging into Lobo's Pure Java Web Browser

Feb 06, 2008 · Geertjan Wielenga

Jacek, I agree with you that not everything must be in Java. However, on the other hand, I find these arguments from the Lobo page pretty convincing in this regard, under the heading "Why a Pure Java Browser?":

There are a number of advantages to be derived from a browser that is written in Java as opposed to a language compiled into native code, namely:
  • Security.- In principle, a Java program is less suceptible to certain types of vulnerabilities such as a buffer overflow attack. Java's security model can also allow web content to have access to a complex set of APIs, except in a controlled sandbox.
  • Extensibility.- A Java-based application can be extended via powerful cross-platform plugins. Consider the difference this has made for Java software such as jEdit and Eclipse. (Lobo already has a plugin API).
  • New paradigms.- With the help of Java we can implement new powerful cross-platform and secure mechanisms to represent web content. We would like to make it easy to integrate arbitrary UI languages into Lobo. We would also like to support JavaFX by default as a first-class citizen. But we also plan to allow, for example, representation of web content merely as Java source code.
  • Portability.- This is the obvious advantage of a pure Java application.

User has been successfully modified

Failed to modify user

  • RSS
  • X
  • Facebook

ABOUT US

  • About DZone
  • Support and feedback
  • Community research

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 215
  • Nashville, TN 37211
  • [email protected]

Let's be friends:

  • RSS
  • X
  • Facebook