我正在尝试从另一个框架打开 JPanel。无法这样做

发布于 2024-09-25 03:10:40 字数 8352 浏览 5 评论 0原文

我正在创建一个程序,用于使用适当的 GUI 等进行数据库操作。我正在使用 swing 来实现同样的目的。无论如何,当我运行该应用程序时,将打开以下窗口:

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);

}

现在我想打开另一个名为 InventoryFormJPanel。上面代码中的最后一个方法 showInventory() 应该打开 InventoryForm,但我收到错误:

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)
.................

要么我的整个方法不正确,要么我(显然)搞砸了某处。请帮忙!

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!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

硪扪都還晓 2024-10-02 03:10:40

“项目当前已冻结。”“项目当前已冻结。”

这并不完全正确。您可以在http://kenai.com/projects/bsaf查看该框架的绝对兼容分支

。即将发布 1.9 版本,修复了大量错误,并进行了一些重要改进。

如果您需要帮助解决您的问题,您可以使用该项目的论坛。那里有很多经验丰富的开发人员。提供完整堆栈跟踪和代码片段,将操作绑定到按钮或菜单项。

"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.

酷遇一生 2024-10-02 03:10:40

看起来您正在使用我不熟悉的 Swing 应用程序框架 (JSR 296),但通常的方法是 add() 将面板添加到框架中,如下所示。

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

以下是一个常见的替代方案:

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

附录:在 NetBeans New Project 对话框中,“请注意,JSR-296(Swing 应用程序框架)不再开发,也不会像以前那样成为官方 Java 开发工具包的一部分”您仍然可以按原样使用 Swing 应用程序框架库,但预计不会有进一步的开发。”

“如果您正在寻找基于 Swing 的应用程序框架,请考虑使用 NetBeans 平台 platform.netbeans.org,这是一个功能齐全的平台,适合创建复杂且可扩展的桌面应用程序,该平台包含可简化窗口、操作、文件和许多其他典型应用程序元素的处理的 API。”

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."

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文