creXALBO
creXALBO

Reputation: 317

Change a JPanel dynamically based on JRadioButton

I'm trying to change content dynamically based on a JRadioButton selection... My simplified code looks something like this.

//import
public class Thing {
  //
  JPanel pnlMain, pnl1, pnl2, pnlRt, pnlLt;
  JRadioBtn btn1, btn2;
  //
  Thing () {
    //
    //initialize panels, add to them, etc.
    pnlMain.add(pnlLt);
    pnlMain.add(pnl1);
    pnlMain.add(pnlRt);
    //
    //Get it showing and stuff.
    //
    }
  //
  //One instance of this class connected to all radio buttons.
  class Evt implements ActionListener {
    public void actionImplemented (ActionEvent evt) {
      //
      pnlMain.remove(1);
      //
      if (evt.getActionCommand().equals("Radio 1"))
        pnlMain.add(pnl1);
      else pnlMain.add(pnl2);
      //
      pnlMain.validate();
      //
      }
    }
  //
  public static void main (String[] args) {
    new Thing();
    }
  //
  }

This lets me change panels, but i cannot change back to a panel i had previously selected... I don't understand why. Please help!!!

Upvotes: 0

Views: 2239

Answers (2)

Spencer Kormos
Spencer Kormos

Reputation: 8441

You should be using CardLayout instead, as this is exactly what that is for. Check out the tutorial here.

Upvotes: 3

mre
mre

Reputation: 44240

Use a proper layout manager. In this scenario, I recommend using CardLayout. This enables the developer to delegate the "complexity" of panel exchanging to the layout manager, which is how it should be.

Upvotes: 2

Related Questions