【问题标题】:Change a JPanel dynamically based on JRadioButton基于 JRadioButton 动态更改 JPanel
【发布时间】:2012-03-03 06:05:17
【问题描述】:

我正在尝试根据 JRadioButton 选择动态更改内容...我的简化代码如下所示。

//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();
    }
  //
  }

这让我可以更改面板,但我无法更改回我之前选择的面板...我不明白为什么。请帮忙!!!

【问题讨论】:

  • 你的内部类的方法不应该是 actionPerformed() ???

标签: java swing dynamic jpanel jradiobutton


【解决方案1】:

您应该改用 CardLayout,因为这正是它的用途。查看tutorial here

【讨论】:

    【解决方案2】:

    使用适当的布局管理器。在这种情况下,我建议使用CardLayout。这使开发人员能够将面板交换的“复杂性”委托给布局管理器,这是应该的。

    【讨论】:

    • @creXALBO,没问题。很高兴为您提供帮助。
    猜你喜欢
    • 1970-01-01
    • 2010-11-28
    • 2010-09-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-03-13
    • 2021-08-30
    相关资源
    最近更新 更多