2

I'm trying to set a variable to be a new JPanel and then add it once a button is pressed, but it is not working and I don't know why.

code:

private void nextButtonActionPerformed(java.awt.event.ActionEvent evt) {                                           
    remove(scriptPanel);
    scriptPanel = new GemPanel();
    add(scriptPanel);
    validate();
    repaint();
    pack();
}    

GemPanel is just a JPanel class I made. When I press the next button, it re-sizes the frame to be as small as possible and nothing actually happens. If I re-size it to normal, the original scriptPanel is still there.

What gives?

Paul Samsotha
  • 205,037
  • 37
  • 486
  • 720

1 Answers1

3

Instead of trying to remove and add entire panels, a better, less problem prone approach would be to use a CardLayout that will allow to swap views. You can see more at How to use Cardlayout

Also, by the looks of your method signature, it seems you're using the Netbeans builder too. You may also want to take a look at How to Use CardLayout with Netbeans Gui Builder

Community
  • 1
  • 1
Paul Samsotha
  • 205,037
  • 37
  • 486
  • 720
  • @user3527825 Um not really, IMO it's a lot much cleaner. Suit yourself though. – Paul Samsotha Apr 12 '14 at 22:27
  • 1
    _"and it's hard to navigate through also."_ . Um `layout.show(panel, "card")` doesn't seem that hard to _me_ – Paul Samsotha Apr 12 '14 at 22:29
  • _"There has to be a way to get what I want to work"_. You need to provide [a Minimal, Complete, and Verifiable example](http://stackoverflow.com/help/mcve). – Paul Samsotha Apr 12 '14 at 22:31
  • @user3527825 CardLayout is the recommended method for typically achieving what you are trying to do... – MadProgrammer Apr 12 '14 at 23:34
  • +1, `it doesn't suit what I'm trying to do.` - it shows a different panel. Which is what you are trying to do. How does this not meet your requirement? `it's hard to navigate through` - it has built in next/previous methods as oppose to you writing your own. How is this hard to use? It also has a "show" method as oppose to writing your own. How is this hard to use? `There has to be a way to get what I want to work` - well you haven't actually stated a requirement that the CardLayout doesn't meet. You only posted a few lines of non-working code. – camickr Apr 13 '14 at 00:23