views:

133

answers:

2

I am creating a program for database manipulation with proper GUI and all. I am using swing for the same. Anyway, when I run the app, the following window opens:

public class MusicShopManagementView extends FrameView {

public MusicShopManagementView(SingleFrameApplication app) {
    super(app);

    initComponents();

    // status bar initialization - message timeout, idle icon and busy animation, etc
    ResourceMap resourceMap = getResourceMap();
    int messageTimeout = resourceMap.getInteger("StatusBar.messageTimeout");
    messageTimer = new Timer(messageTimeout, new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            statusMessageLabel.setText("");
        }
    });
    messageTimer.setRepeats(false);
    int busyAnimationRate = resourceMap.getInteger("StatusBar.busyAnimationRate");
    for (int i = 0; i < busyIcons.length; i++) {
        busyIcons[i] = resourceMap.getIcon("StatusBar.busyIcons[" + i + "]");
    }
    busyIconTimer = new Timer(busyAnimationRate, new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            busyIconIndex = (busyIconIndex + 1) % busyIcons.length;
            statusAnimationLabel.setIcon(busyIcons[busyIconIndex]);
        }
    }); 
    idleIcon = resourceMap.getIcon("StatusBar.idleIcon");
    statusAnimationLabel.setIcon(idleIcon);
    progressBar.setVisible(false);

    // connecting action tasks to status bar via TaskMonitor
    TaskMonitor taskMonitor = new TaskMonitor(getApplication().getContext());
    taskMonitor.addPropertyChangeListener(new java.beans.PropertyChangeListener() {
        public void propertyChange(java.beans.PropertyChangeEvent evt) {
            String propertyName = evt.getPropertyName();
            if ("started".equals(propertyName)) {
                if (!busyIconTimer.isRunning()) {
                    statusAnimationLabel.setIcon(busyIcons[0]);
                    busyIconIndex = 0;
                    busyIconTimer.start();
                }
                progressBar.setVisible(true);
                progressBar.setIndeterminate(true);
            } else if ("done".equals(propertyName)) {
                busyIconTimer.stop();
                statusAnimationLabel.setIcon(idleIcon);
                progressBar.setVisible(false);
                progressBar.setValue(0);
            } else if ("message".equals(propertyName)) {
                String text = (String)(evt.getNewValue());
                statusMessageLabel.setText((text == null) ? "" : text);
                messageTimer.restart();
            } else if ("progress".equals(propertyName)) {
                int value = (Integer)(evt.getNewValue());
                progressBar.setVisible(true);
                progressBar.setIndeterminate(false);
                progressBar.setValue(value);
            }
        }
    });

    // tracking table selection
    masterTable.getSelectionModel().addListSelectionListener(
        new ListSelectionListener() {
            public void valueChanged(ListSelectionEvent e) {
                firePropertyChange("recordSelected", !isRecordSelected(),
                    isRecordSelected());
            }
        });

    // tracking changes to save
    bindingGroup.addBindingListener(new AbstractBindingListener() {
        @Override
        public void targetChanged(Binding binding, PropertyStateEvent event) {
            // save action observes saveNeeded property
            setSaveNeeded(true);
        }
    });

    // have a transaction started
    entityManager.getTransaction().begin();
}


public boolean isSaveNeeded() {
    return saveNeeded;
}

private void setSaveNeeded(boolean saveNeeded) {
    if (saveNeeded != this.saveNeeded) {
        this.saveNeeded = saveNeeded;
        firePropertyChange("saveNeeded", !saveNeeded, saveNeeded);
    }
}

public boolean isRecordSelected() {
    return masterTable.getSelectedRow() != -1;
}


@Action
public void newRecord() {
    musicshopmanagement.Intrument i = new musicshopmanagement.Intrument();
    entityManager.persist(i);
    list.add(i);
    int row = list.size()-1;
    masterTable.setRowSelectionInterval(row, row);
    masterTable.scrollRectToVisible(masterTable.getCellRect(row, 0, true));
    setSaveNeeded(true);
}

@Action(enabledProperty = "recordSelected")
public void deleteRecord() {
    int[] selected = masterTable.getSelectedRows();
    List<musicshopmanagement.Intrument> toRemove = new
        ArrayList<musicshopmanagement.Intrument>(selected.length);
    for (int idx=0; idx<selected.length; idx++) {
        musicshopmanagement.Intrument i = 
            list.get(masterTable.convertRowIndexToModel(selected[idx]));
        toRemove.add(i);
        entityManager.remove(i);
    }
    list.removeAll(toRemove);
    setSaveNeeded(true);
}


@Action(enabledProperty = "saveNeeded")
public Task save() {
    return new SaveTask(getApplication());
}

private class SaveTask extends Task {
    SaveTask(org.jdesktop.application.Application app) {
        super(app);
    }
    @Override protected Void doInBackground() {
        try {
            entityManager.getTransaction().commit();
            entityManager.getTransaction().begin();
        } catch (RollbackException rex) {
            rex.printStackTrace();
            entityManager.getTransaction().begin();
            List<musicshopmanagement.Intrument> merged = new 
                ArrayList<musicshopmanagement.Intrument>(list.size());
            for (musicshopmanagement.Intrument i : list) {
                merged.add(entityManager.merge(i));
            }
            list.clear();
            list.addAll(merged);
        }
        return null;
    }
    @Override protected void finished() {
        setSaveNeeded(false);
    }
}

/**
 * An example action method showing how to create asynchronous tasks
 * (running on background) and how to show their progress. Note the
 * artificial 'Thread.sleep' calls making the task long enough to see the
 * progress visualization - remove the sleeps for real application.
 */
@Action
public Task refresh() {
   return new RefreshTask(getApplication());
}

private class RefreshTask extends Task {
    RefreshTask(org.jdesktop.application.Application app) {
        super(app);
    }
    @SuppressWarnings("unchecked")
    @Override protected Void doInBackground() {
        try {
            setProgress(0, 0, 4);
            setMessage("Rolling back the current changes...");
            setProgress(1, 0, 4);
            entityManager.getTransaction().rollback();

            setProgress(2, 0, 4);

            setMessage("Starting a new transaction...");
            entityManager.getTransaction().begin();

            setProgress(3, 0, 4);

            setMessage("Fetching new data...");
            java.util.Collection data = query.getResultList();
            for (Object entity : data) {
                entityManager.refresh(entity);
            }

            setProgress(4, 0, 4);


            list.clear();
            list.addAll(data);
        } catch(Exception ignore) { }
        return null;
    }
    @Override protected void finished() {
        setMessage("Done.");
        setSaveNeeded(false);
    }
}

@Action
public void showAboutBox() {
    if (aboutBox == null) {
        JFrame mainFrame = MusicShopManagementApp.getApplication().getMainFrame();
        aboutBox = new MusicShopManagementAboutBox(mainFrame);
        aboutBox.setLocationRelativeTo(mainFrame);
    }
    MusicShopManagementApp.getApplication().show(aboutBox);
}
@Action
public void showInventory() {
    JFrame frame1 = new JFrame(); 
            frame1.setContentPane(new InventoryForm());
            frame1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame1.setVisible(true);

}

Now I want to open another JPanel called InventoryForm. The last method showInventory() in the above code is supposed to open InventoryForm, but I get an error:

Exception in thread "AWT-EventQueue-0" java.lang.Error: java.lang.reflect.InvocationTargetException
    at org.jdesktop.application.ApplicationAction.actionFailed(ApplicationAction.java:859)
    at org.jdesktop.application.ApplicationAction.noProxyActionPerformed(ApplicationAction.java:665)
    at org.jdesktop.application.ApplicationAction.actionPerformed(ApplicationAction.java:698)
.................

Either my whole approach is incorrect or I am (obviously) screwing up somewhere. Please help!

+1  A: 

It looks like you're using Swing Application Framework (JSR 296), with which I am unfamiliar, but the usual approach is to add() the panel to the frame, as suggested below.

http://platform.netbeans.org/ frame1 = new JFrame(); 
frame1.add(new InventoryForm());
frame1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame1.setVisible(true);

Here is a common alternative:

frame1.getContentPane().add(new InventoryForm());

Addendum: From the NetBeans New Project dialog, "Note that JSR-296 (Swing Application Framework) is no longer developed and will not become part of the official Java Development Kit as was originally planned. You can still use the Swing Application Framework library as it is, but no further development is expected."

"If you are looking for a Swing-based application framework, consider using the NetBeans Platform platform.netbeans.org, which is a full-featured platform suitable for creating complex and scalable desktop applications. The Platform contains APIs that simplify the handling of windows, actions, files, and many other typical application elements."

trashgod
nope. the problem still persists..
vr3690
NB: The `Swing Application Framework` "project is currently frozen."
trashgod
thanks for your help,but i am still getting the same error.
vr3690
+2  A: 

"project is currently frozen.""project is currently frozen."

It is not entirely true. You can review an absolutely compatible fork of this framework at http://kenai.com/projects/bsaf

It's about to release 1.9 version with huge amount of bugs fixed, and several important improvements.

If you want help with you problem you can use forum of this project. There are many experienced developers there. Provide full stack-trace and code snippet where you bin action to a button or menu item.

Illya Yalovyy
+1 This is probably the most fruitful route if staying with JSR-296.
trashgod