【问题标题】:JPanel Problem in JavaJava中的JPanel问题
【发布时间】:2011-09-10 16:13:33
【问题描述】:

美好的一天!

我在重置 JPANEL 的内容时遇到问题。有什么方法可以删除JPANEL的所有内容吗?

我正在制作一个 HangMan 游戏。我需要初始化我的面板以让位于下一个级别。我的面板是使用 Netbeans GUI 创建的,一切都是固定的(甚至是位置和大小)。

我的 SAMPLE 代码如下:

 public MainGame(JDialog owner) {
        super(owner, true);
        initComponents();
        newGame();
    }

    void newGame() {
         jPanel3.setLayout(new GridLayout(3, 9, 3, 5));
         for (char buttonChar = 'a'; buttonChar <= 'z'; buttonChar++) {
             String buttonText = String.valueOf(buttonChar);
             letterButton = new JButton(buttonText);
             letterButton.addActionListener(this);
             jPanel3.add(letterButton);
         }
    }

    void checkHame(){
         newGame();   //I CALL AGAIN TO GO TO THE NEXT LEVEL...
    }

在我的代码中,jPanel3 是使用 netbeans 的 GUI 创建的。我的问题是,在第一次调用 newGame 方法时,JPanel3 充满了内容。我需要删除第二次调用 newGame 中的所有内容,否则所有内容都会加起来或加倍。

任何建议都将受到高度赞赏。

再次感谢您!

干杯。

【问题讨论】:

    标签: java swing jpanel


    【解决方案1】:

    在for loop 之前做一个jPanel3.removeAll() 怎么样?

    removeAll() 的定义:-

    public void removeAll()

    Removes all the components from this container.
    

    【讨论】:

      【解决方案2】:

      您可能还需要在 removeAll 之后调用 revalidate() 和 repaint()

      【讨论】:

        【解决方案3】:

        您可以使用removeAll 方法。

        不过,与其移除组件,不如考虑将按钮的状态重置回其原始状态并重新使用按钮。

        【讨论】:

          猜你喜欢
          • 2014-08-14
          • 2010-09-06
          • 1970-01-01
          • 1970-01-01
          • 2021-12-28
          • 1970-01-01
          • 2016-04-19
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多