KDecker
KDecker

Reputation: 7128

Displaying a JFrame as the result of a JButton click?

I am trying to create a JPanel to display when a user clicks a button within my main JFrame. In Netbeans I first used the wizard to add a new JPanel to my project, I then used the GUI creator to fill in all the content. I am not trying to display the JPanel with the following code

private void m_jbShowSelAccResultsActionPerformed(java.awt.event.ActionEvent evt)
{                                                      
    Account selAcc = getSelectedAccount();
    if(selAcc != null)
    {
        AccountView accPanel = new AccountView(Account.getDeepCopy(selAcc));
        accPanel.setVisible(true);
    }
    else
        ShowMessage("Please select an account to view");
}    

But nothing happens, no error is thrown and the JPanel is not shown. So I then changed the JPanel to a JFrame (Netbeans didn't complain). When I try again with the same code I receive the error GroupLayout can only be used with one Container at a time.

How can I display my JPanel/JFrame?

Upvotes: 1

Views: 104

Answers (1)

Hovercraft Full Of Eels
Hovercraft Full Of Eels

Reputation: 285403

  1. To change views within a Swing GUI, use a CardLayout as this is a much more robust and reliable way to do this.
  2. Don't try to blindly "change a JPanel to a JFrame". It looks like you're just guessing here.
  3. GroupLayout can't be reused as the error message is telling you. Likely this error comes from the point above. If you avoid trying to make a JFrame out of a JPanel, the error message will likely go away. As an aside, GroupLayout is not easily used manually, especially if you're trying to add components to an already rendered GUI.

So for instance, if your program had a JPanel say called cardHolderPanel, that used a CardLayout, this held by a variable say called cardLayout, and you've already added a "card" JPanel to this holder for accounts, say called accPanel, and if the accPanel had a method to set its currently displayed account, say setAccount(Accoint a), you could easily swap views by calling the CardLayout show(...) method, something like:

private void m_jbShowSelAccResultsActionPerformed(java.awt.event.ActionEvent evt) {                                                      
    Account selAcc = getSelectedAccount();

    if(selAcc != null) {
        accPanel.setAccount(Account.getDeepCopy(selAcc));
        cardLayout.show(cardHolderPanel, "Account View");
    }
    else {
        showErrorMessage("Please select an account to view");
    }
}

Upvotes: 2

Related Questions