Change a JPanel dynamically based on JRadioButton

别等时光非礼了梦想. 提交于 2019-12-12 00:54:34

问题


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!!!


回答1:


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




回答2:


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.



来源:https://stackoverflow.com/questions/9233394/change-a-jpanel-dynamically-based-on-jradiobutton

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!