Thursday May 11, 2006

Swing Tutorial in Matisse - Custom Table Models

The continuing adventures of the Swing Tutorial in NetBeans and Matisse. In yesterday's blog, I talked about how it's a pain that when you define the data for your JTable's model in some defined arrays of strings and objects, the data doesn't show up in the design view.

In real-world applications, however, you're most likely going to define your custom TableModel to do things like access a database. For example, sets up MyTableModel as an inner class. So how do you get this set up in the IDE?

Once again, we're using the model property editor for the JTable (select the JTable - not the JScrollPane - in the Inspector window and click the button for the model property in the Properties window). One simple way to do this is to switch to Form Connection mode, select User Code, and just enter new MyTableModel(). If you run the file, you'll see the model is properly used. But in the design view, we still see nothing.

A better way is to copy the MyTableModel class to its own separate class, called MyTableModel, of course. Then build the project (you need a binary version of MyTableModel for what we're about to do). Now select MyTableModel in the Projects window and press Ctrl-C, then paste it anywhere in the design view (or select any node in the Inspector and paste). An instance of MyTableModel gets added to the Other Components node.

Now we can go back to the model property editor for the JTable, select From Bean, and select myTableModel1. And voila, the data appears in the design view.

This and much more is coming up in an excellent tutorial being prepared by Talley Mulligan on hooking up a Matisse GUI form to a DB back-end, so stay tuned for the full story.

Wednesday May 10, 2006

Doing the Swing Tutorial in NetBeans: Tables

Trying to go through the Swing tutorial in NetBeans has always been hard, simply because the code looks so much different than the code that NetBeans uses. You can't just copy and paste their code in, because then you wouldn't be able to see the form in the design view. And of course, the samples don't use Matisse for layout rules, and really why would you use anything else?

I decided to try and power my way through some of the examples anyway. First stop: tables. I'm gonna look at some code, like, and try to reproduce it in NetBeans.

Warning: I know very little about GUI development so this is a case of the blind leading the blind. I will most likely do things that will make real developers grimace. If so, please tell me.

First create a Java Application project with no main class. Create a JFrame called SimpleTableSelectionDemo and just put a JTable into it, expanded to all four sides of the JFrame so it resizes correctly.

Now we encounter the first problem - getting the column values and names into the table and populating it with some data. The example creates two arrays and uses the arrays to set these:

   final String[] columnNames = {"First Name",
                                 "Last Name",
                                 "# of Years",

   final Object[][] data = {
       {"Mary", "Campione",
        "Snowboarding", new Integer(5), new Boolean(false)},
       {"Alison", "Huml",
        "Rowing", new Integer(3), new Boolean(true)},
       {"Kathy", "Walrath",
        "Knitting", new Integer(2), new Boolean(false)},
       {"Sharon", "Zakhour",
        "Speed reading", new Integer(20), new Boolean(true)},
       {"Philip", "Milne",
        "Pool", new Integer(10), new Boolean(false)}

        final JTable table = new JTable(data, columnNames);

But the IDE just the arrays straign into the parameters of DefaultTableModel:

jTable1.setModel(new javax.swing.table.DefaultTableModel(
   new Object [][] {
   {null, null, null, null},
   {null, null, null, null},
   {null, null, null, null},
   {null, null, null, null}
   new String [] {
   "Title 1", "Title 2", "Title 3", "Title 4"

Not a big deal, the model property editor can be used to set this. To open the editor, select the JTable in the Inspector window (not in the Design Area, because that just selects the JScrollPane that the JTable resides in) and in the Properties window click the model property. We can do one of the following:

  • With Select Mode set to TableModelEditor at the top, just enter the column names and types in the Table Settings tab and the default values in the Default Values section.
  • Copy the two arrays from the example file and paste them into the field declarations in your file. Then open the model property editor, set Select Mode to Form Connection, select User Code, and enter the following:
    new DefaultTableModel(data, columnNames)

    Notice that the IDE has code completion in this editor. Once you get back to the source view, make sure to fix your imports to import DefaultTableModel. One major limitation here is that if you define the model in this way, you don't get to view it in the Design View. Not sure why that is, but I will investigate.

I did the latter, just because I'm too lazy to enter all of that stuff into the GUI when I can just copy and paste the two arrays.

Now where to put the rest of the code, namely the code that defines the selection model? Most of the examples have a createAndShowGUI method that's called from the main method to actually initialize and create the form. NetBeans does something similar in the initComponents method. This method is in a guarded blue block, which means you can't edit it manually. It is then called by in the JFrame constructor method, which is editable.

So for this example, the simplest thing is to let the IDE do its thing when initiating the code in the initComponents section, then add the code to further tune the component behavior in the constructor (or in a separate method that's then called by the constructor).

Before you start cutting and pasting, rename the JTable variable name to match what's in the example code by clicking the jTable1 node in the Inspector window, pressing F2, and typing table. Then copy the following code in bold into the constructor.

    public SimpleTableSelectionDemo() {
        if (ALLOW_ROW_SELECTION) { // true by default
            ListSelectionModel rowSM = table.getSelectionModel();
            rowSM.addListSelectionListener(new ListSelectionListener() {
                public void valueChanged(ListSelectionEvent e) {
                    //Ignore extra messages.
                    if (e.getValueIsAdjusting()) return;

                    ListSelectionModel lsm = (ListSelectionModel)e.getSource();
                    if (lsm.isSelectionEmpty()) {
                        System.out.println("No rows are selected.");
                    } else {
                        int selectedRow = lsm.getMinSelectionIndex();
                        System.out.println("Row " + selectedRow
                                           + " is now selected.");
        } else {

        if (ALLOW_COLUMN_SELECTION) { // false by default
            if (ALLOW_ROW_SELECTION) {
                //We allow both row and column selection, which
                //implies that we \*really\* want to allow individual
                //cell selection.
            ListSelectionModel colSM =
            colSM.addListSelectionListener(new ListSelectionListener() {
                public void valueChanged(ListSelectionEvent e) {
                    //Ignore extra messages.
                    if (e.getValueIsAdjusting()) return;

                    ListSelectionModel lsm = (ListSelectionModel)e.getSource();
                    if (lsm.isSelectionEmpty()) {
                        System.out.println("No columns are selected.");
                    } else {
                        int selectedCol = lsm.getMinSelectionIndex();
                        System.out.println("Column " + selectedCol
                                           + " is now selected.");

        if (DEBUG) {
            table.addMouseListener(new MouseAdapter() {
                public void mouseClicked(MouseEvent e) {

Now add the boolean fields at the top of the file:

    private boolean DEBUG = false;
private boolean ALLOW_COLUMN_SELECTION = true;
private boolean ALLOW_ROW_SELECTION = true;

And add the printDebugData method somewhere in the file:

    private void printDebugData(JTable table) {
        int numRows = table.getRowCount();
        int numCols = table.getColumnCount();
        javax.swing.table.TableModel model = table.getModel();

        System.out.println("Value of data: ");
        for (int i=0; i < numRows; i++) {
            System.out.print("    row " + i + ":");
            for (int j=0; j < numCols; j++) {
                System.out.print("  " + model.getValueAt(i, j));

And run the file. Notice that you can select only rows and the Output Window says which row you selected. If you change the boolean values in ALLOW_COLUMN_SELECTION and ALLOW_ROW_SELECTION and run again, you can select cells, rows, or columns, and the Output Window tells you which one you've selected.

Here's the completed version of my file.

Wednesday Apr 12, 2006

Doing Your Own NetBeans Flash Demos

Been a while since I flogged but don't think I've been sitting on my keister the whole time, things around here have been hopping! Getting ready for JavaOne, looking at reorganizing the website docs and support section, working on a new and very cool Welcome Screen (more on that later)... Lots of stuff.

But one of the funner things we did was to put together some guidelines and templates for doing Flash demos. We took Vince's article about doing Wink demos and expanded it to provide full steps and a template for nice NetBeans-branded loading screen, controller (the thing at the bottom), intro and ending screen, and standard callouts and buttons. Check it out here:

  • So get out there and start flogging!

    Thursday Mar 16, 2006

    Internationalizing a Matisse Form

    One of the coolest things about Matisse is that when you translate your program into another language, it doesn't get all screwed up because all of the components are grouped relative to each other with relative spacing provided by the look and feel. But how do you take a program with hard-coded display text and internationalize it?

    Marek Grummich answers this question in this latest installment in our continuation of Matisse articles. There are basically four things you can do (each of which Marek goes through, including Flash demos, of course):

    • Insert internationalized strings right in the GUI Builder as you create the form. To do this, click the ellipsis for the text property for a component, then select Resource Bundle in the Select Mode combo box and enter the properties file, key, and value (display text) for the string. View Demo
    • Insert an internationalized string in code. If you're working in the code view, and not in the GUI editor, just press Ctrl-Shift-J, specify the properties file, key, and value, and the IDE fills in the correct lookup code for you.

      View Demo

    • Internationalize an entire project at once. Right-click the Source Packages node and choose Tools > Internationalization > Internationalization Wizard. The wizard will go through and list all of the strings in the source files and suggest to replace them with key/value pairs in a properties file.

      Page 3 of the Internationalization wizard

    • Convert strings in a single file one at a time. Right-click the file in the Source Editor and choose Tools > Internationalization > Internationalize. This is best if you've got a small project or you know there are lots of strings that you don't want to internationalize. You cycle through all of strings one at a time and provide the key/value pairs for them.

      View Demo

    Another tip: If you know you've got a lot of strings that you don't want to internationalize, put a //NOI18N comment in each row that contains one of these Strings. Then go Tools > Options > Advanced Options > Editing > Internationalization and add //NOI18N to the regular expression in the I18n Search Format property. The IDE will automatically skip all these strings when you run internationalization commands.

    Then to run your project in a different locale, put a string like the following in your VM options:


    And you get something like this:

    Hope everyone's enjoying the Matisse tutorials. Stay tuned for the next and most important one: Hooking up the Matisse form to a database. It's the hardest one so it takes the longest to write. Oh yeah, and regarding Matisse4Eclipse, using SWT to program a Swing app is like using a coal-powered generator to charge up your electric car. IMHO, it's kind of missing the point...

    Wednesday Mar 15, 2006

    Life After JBuilder

    I know, I know. You were happily using JBuilder, you've got all your personalized settings configured and your work flow down, you don't want to learn another tool. I feel your pain.

    But, the good folks at Borland have decided that JBuilder will soon be a thing of the past. So it's time to pick up the pieces and start thinking about life after JBuilder.

    Here's a first step:

    NetBeans IDE Guide for JBuilder Users

    A new article from Patrick Keegan, of NetBeans Field Guide fame, that shows you how to quickly port all of your JBuilder projects over to NetBeans. And once you get up-and-running, I bet you'll probably like NetBeans even more :-)

    Thursday Mar 02, 2006

    Getting Under the Hood of Matisse

    The whole point of Matisse is that you don't have to understand what's going on behind the scenes, you just have to know how to work with the alignment and positioning in the GUI front-end, then only switch to the Java code when it's time to hook up business logic to the code.

    Having said that, a deeper understanding of how GroupLayout, the layout manager for Matisse, works helps in understanding the approach you should take to designing your forms. And 9 out of 10 developers, when presented with a shiny new toy, want to take it apart to see how it works.

    So if you're interested in such things, head over to Tomas Pavek's blog. He's got some good entries describing the philosophy behind GroupLayout and examining the code a little. Tomas wrote most of Matisse, so he should know!

    Java Web Start and Matisse

    We're in the process of getting a series of Matisse docs together that build on the UI that was laid out in the GUI Builder Tutorial. We're hoping to cover the following:

    • Hooking up the UI to a database back end
    • Internationalizing a GUI form
    • Deploying a GUI form via Java Web Start
    • Hooking up a GUI form to a web service
    • Others? If there's something you want to see let us know!

    So here's the first installment - Deploying a GUI Form via Java Web Start, brought to us by Amy Lu and including, of course, a Flash demo.

    Click image to start the Flash demo

    The Java Web Start team has done a great job on the Java Web Start module. You can download it from the Beta Update Center. Then you just right-click any project and choose Java Web Start | Enable Java Web Start, and the IDE adds the Java Web Start JAR files to the classpath and creates the .jnlp file for you.

    For Matisse applications, you also have to add a JAR reference to the swing-layout-1.0.jar file, so that it gets packaged and deployed too. But I wonder, isn't this JAR file publicly available somewhere so that you can just link to it rather than having to deploy it again to your server?

    Then you're set, you can deploy the file to the bundled Tomcat server by choosing the Run with Java Web Start command. Bob's yer uncle.

    Wednesday Mar 01, 2006

    Phone Phlogging

    I remember when I first moved to the Czech Republic, I was teaching English in Brno and making something like $250 a month. Back then, everything was about the cheap! I never ate at a place where the side order wasn't included in the price of the meal, drank at a place where the beer was more than 16kc, or danced at a place that charged a cover, even a measely 50kc.

    So for a frugal English teacher at the time, the height of decadence was having a mobile phone. Me and my friends would marvel at the Czuppies (translation - Czech yuppies) who would blather on in a pub on their phones, calculating how many beers we could drink with the money that person was wasting on a phone call.

    Nope, we did it the old fashioned way. You set a time to meet - usually the top of Ceska street at 7PM - and if you didn't make it within a half hour of the given time (15 minutes in the cold winter) then you just had to guess which pub we went to or just hope to run into us. Ceska at 7PM on a Friday was always quite a scene, because that's where everybody met, and it was a good place to bump into people and stare at girls.

    Now of course everyone has phones, you just can't get by without one, although our good friend and hi-tech luddite Geertjan bucks the trend and refuses to get his phone unblocked. People walk into the pub and call each other to see which table they're at rather than walk around and look. If I'm more than 3 minutes late somewhere my wife will usually call me to figure out where I'm at. Gone is the fifteen minute grace period.

    I think that's why, despite my love for all things electronic, I refuse to spend money on a phone. I'll spare no expense in my quest for the perfect home entertainment center or tricking out my PC, but a phone... that's not a toy, it's just a necessity.

    So why am I waxing nostalgic about phones? It's all just a long intro to the fact that, in recognition of the fact that the NetBeans Mobility Pack is hands-down the best tool in the world for developing Java mobile apps, we're proudly annoucing the first ever Mobility Pack Day in Harrah's Las Vegas (Vegas, baby!!!) during the CTIA conference. That's right, hit the blackjack tables, catch a Lisa Minelli show, and check out the hottest cell phone technology. Man, I wish I was working for that group.

    So in celebration of the Mobility Pack Day, here's a great flash demo done by Petr Suchomel. Also check out the full tutorial. It covers setting up platforms for various phones and using device fragmentation to create a single application that can be compiled for both Siemens TC45 and TC65 devices.

    Tuesday Feb 28, 2006

    Quick and Helpful NetBeans Editor Demos

    Gregg Sporar put together some quick-hit demos of useful NetBeans editor functionality. They're short, sweet, and helpful, even if you already know your way around the editor but especially if you're just moving to NetBeans.

    Edit Hints - This demo explains the new editor hints feature that was added in version 5.0 of the NetBeans IDE.

    Code Completion - The IDE's editor can help you type code faster by completing expressions as you type; this demo shows you how it works.

    Navigation - This brief demo shows some of the shortcuts available for navigating between files in the source editor.

    Source Tools - The Source menu was added in version 5.0 of the NetBeans IDE. This brief demo shows you the commands that it contains.

    Monday Feb 27, 2006

    Reading Excel Data in a Matisse Form

    Dafe Simonek contributed this great tutorial about how to work with Excel files in Java applications. It creates a simple GUI using matisse and then populates it with data from an Excel file. Here's the highlights of what the tutorial covers:

    First, download JExcelApi — the Java Excel library. Then create a Java application project, add the JExcelApi JAR to the classpath (Dafe creates a full library with sources and Javadocs) and create the ReadExcelUI form to display the data. See Dafe's turorial for how to create the form. It's basically just got a menu with two items and a JTable. The form should look like the following:

    preview of the form

    Then you hook up the logic to the form GUI components. See Dafe's tutorial for the business logic. It's pretty easy and a good introduction to hooking up events and working with custom data models in Matisse. Thanks for the contribution, Dafe!!!

    Roman's cool JavaLobby flash demo

    If you haven't checked it out yet, you should. It's all slick and professional and stuff, not like the scrappy little wink-lets I've been doing :-)

    Click to watch and listen to my Roman's presentation

    Thursday Feb 23, 2006

    EJB 3.0 Demo

    As Roman said, EJB 3.0 is a whole lot easier than in EJB 2.1. Forget about CMP mapping, deployment descriptors, or even having to create full-blown entity beans for your DB access. Just create a persistence unit then regular annotated POJO entity classes for each of your tables, and off you go. You can even use them in a regular J2SE project.

    Lots of other things are much easier as well. My favorite is calling an EJB. First look at the gobbly-gook that is EJB lookup in EJB 2.1:

        private org.test.ProcessOrderLocal lookupProcessOrderBean() {
            try {
                javax.naming.Context c = new javax.naming.InitialContext();
                org.test.ProcessOrderLocalHome rv = (org.test.ProcessOrderLocalHome) c.lookup("java:comp/env/ejb/ProcessOrderBean");
                return rv.create();
            catch(javax.naming.NamingException ne) {
                java.util.logging.Logger.getLogger(getClass().getName()).log(java.util.logging.Level.SEVERE,"exception caught" ,ne);
                throw new RuntimeException(ne);
            catch(javax.ejb.CreateException ce) {
                java.util.logging.Logger.getLogger(getClass().getName()).log(java.util.logging.Level.SEVERE,"exception caught" ,ce);
                throw new RuntimeException(ce);

    Now the same thing in EJB 3.0:

        ProcessOrderLocal orderProcess;

    Ahhhhhh.... I just feel sorry for the NetBeans engineers who did so much work to implement automatic generation of all that code.

    Anyway, if you've got some time grab a cup of coffee and check out this flash tutorial, which shows you how to set up EJB 3.0 persistence in an EJB module, then access it using JSF in a web module. Again, it's a bit long (sorry) but it's worth it. I promise some shorter flash demos are coming!

    Wednesday Feb 22, 2006

    BEPL Orchestration Demo

    As everyone I'm sure has heard, we've released a special preview of NetBeans 5.5 with Java EE 5 support to go out with the Sun Java System Application Server 9 Beta. What you may not know is that this contains something very new and very cool - the Enterprise Pack. This is basically the BEPL, UML, and SOA modules from Java Studio Enterprise integrated into NetBeans IDE. Pretty impressive, huh?

    But what, you ask, is BEPL?

    As usual, I have no idea. I just ferret out other people's work and present it on my blog. Here's a quick description from their web page:

    Web Services Orchestration - Author, build, deploy, and test BPEL4WS 1.1 processes. Includes BPEL runtime engine integrated with Sun Java System Application Server Platform Edition 9 Beta, installed and fully configured to work with the IDE; advanced visual and source editor with support for round-trip engineering; support for process debugging and test runs integrated in the IDE. Watch the video introducing the Orchestration Designer.

    And of course, it wouldn't be a flog without a video demo. It's a bit long so I suggest you get a cup of coffee first.

    Watch the video introducing the Orchestration Designer.

    Tuesday Feb 21, 2006

    Alternate Definition of Flogging

    FlexRex, the Fictional Blogger, has a definition of flogging that may just beat mine. Maybe we can combine the two. We take lots of screenshots, fax them to someone, then have them flip through them to simulate animation. That's how they did flash demos in the old days!

    In school I always used to draw the little stick men walking doing weird stuff on the bottom of my binder. Anything to get me through to that cigarette under the bleachers at lunchtime. BTW - I've actually stuck to my New Year's Resolution of death. One month, 21 days with no smokes. Feels good, just hope I can walk the line on that next >3 tequila night.

    And to continue my tangent-fest, I watched Walk the Line last night, and promptly decided to never see a biographical film ever again in my life. It's not that the acting was bad (they both did all right) or that it looked like lip-singing (both Phoenix and Reeces Pieces actually sang all the songs, especially impressive for Reeces doing Sue Carter), it's just that no matter how good it is, it really is just someone doing a celebrity impersonation for an hour and half. Just starts dragging.

    More Matisse Flash Demos

    Talley's full-fledged Matisse demo has gotten lots of hits and comments, but he also put together two other quick Matisse demos that show how to rebuild the sample forms that come packaged with the IDE. To open these forms, go to the New Project wizard and look under Samples | General | GUI Form Examples.

    Click the images below to open the demos.

    Find Form Demo

    Antenna Demo




    « April 2014