簡體   English   中英

基於JRadioButton動態更改JPanel

[英]Change a JPanel dynamically based on JRadioButton

我正在嘗試根據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();
    }
  //
  }

這使我可以更改面板,但是我無法更改回以前選擇的面板...我不明白為什么。 請幫忙!!!

您應該改用CardLayout,因為這正是它的用途。 此處查看教程

使用適當的布局管理器。 在這種情況下,我建議使用CardLayout 這使開發人員可以將面板交換的“復雜性”委托給布局管理器,這應該是這樣。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM