CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 3 of 3
  1. #1
    Join Date
    Jan 2011
    Posts
    1

    displaying alternate jpanels in a jframe

    hi, i want to display the attack jpanel in the same frame when the button is clicked but instead it opens in a new frame

    public void actionPerformed(ActionEvent e)
    {
    JFrame aFrame = new JFrame();
    aFrame.setBounds(0,0,400,600);
    Container contentPane = aFrame.getContentPane();
    JButton s = (JButton)e.getSource();
    if(s == attack)
    {
    contentPane.add(new Attack());
    }
    else if(s == defense)
    {
    contentPane.add(new Defense());
    }
    aFrame.setVisible(true);

    }

  2. #2
    Join Date
    Feb 2008
    Posts
    966

    Re: displaying alternate jpanels in a jframe

    Two things: first, when you are creating a new JFrame, this is the behavior you are getting: a new window. Secondly, you are setting the visibility to true instead of adding it to the current Frame. Try doing something like:

    this.add(aFrame)
    this.pack();

    I'm not sure how your main Frame is set up, so I can't guarantee that it will work.

  3. #3
    Join Date
    Jan 2011
    Location
    Tacoma, Washington
    Posts
    31

    Re: displaying alternate jpanels in a jframe

    I don't think you can add a JFrame into another JFrame as a JFrame is a top level container. You should be able to add as many JPanels to a JFrame as you like though. Can I assume that Attack() and Defend have something to do with JPanels? If each are a special instance of JPanel then perhaps you could create one instance of each JPanel and add them both to the JFrame then toggle the visibility of each to simulate a different frame when you have an "Attack" action and a "Defend" action. Than way you don't have to recreate a new JPanel each time.

    By the way any program with Attack() and Defend() methods is, by default, rad. Just so you know. =D

Tags for this Thread

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured