【问题标题】:Java - replace compoment in JFrameJava - 替换 JFrame 中的组件
【发布时间】:2012-11-19 14:54:24
【问题描述】:

我正在努力使用 java GUI - 提前感谢您的帮助!我有一个 JFrame,其中有几个组件:button (Jbutton) 触发动作侦听器,comp 这是我试图替换 JScrollPane 的组件strong> 里面有一个组件(不管是什么类型的组件,可以是文本字段、表格或任何东西)。

我想触发一个动作 - 删除组件,将一个新组件放在与已删除组件相同的位置,然后重新绘制窗口(我使用它来显示不同类型的文本字段和 JTable)。这就是我所拥有的:

JScrollPane sp = new JScrollPane(comp);
this.add(sp, BorderLayout.CENTER);
//this works so far - first time I display this is ok!

private void replace() {
 comp = new Component(...); //name and type of the components is not important
 sp = new JSCrollPane(comp);
 this.remove(sp); //remove old component
 add(sp, BorderLayout.CENTER);
 repaint();
 revalidate();
}

为什么函数不能代替工作?它没有做任何事情(它改变了逻辑组件,所以如果我访问 comp 的内容,它会被刷新但它仍然显示旧的)。

我写的有点象征意义,因为我的代码很长...感谢您的帮助! 编辑:在我的代码中忘记了一行..

【问题讨论】:

    标签: java swing


    【解决方案1】:

    您不必像以前那样尝试删除滚动窗格。

    要更改滚动窗格显示的组件,只需进行以下调用:

    sp.setViewportView(new Component(...));
    

    调用后,旧组件将从视图中移除并由新组件替换。

    所以你的代码应该看起来像这样:

    JScrollPane sp = new JScrollPane(comp);
    this.add(sp, BorderLayout.CENTER);
    
    private void replace() {
        comp = new Component(...); //name and type of the components is not important
        sp.setViewportView(comp);
    }
    

    【讨论】:

      【解决方案2】:

      从您的代码的外观来看,您添加的第一个滚动窗格 (this.add) 与您删除的滚动窗格 (this.remove) 不同。测试从 remove 返回的布尔值,看看它是否真的被删除了。我想你会发现它不是。

      【讨论】:

      • 这是错误,我应该先删除 sp 然后创建它并重新添加它...
      【解决方案3】:

      this board中有解决方案:

      jpanel.remove(component); //remove component from your jpanel in this case i used jpanel 
      jpanel.revalidate(); 
      jframe.repaint();//repaint a JFrame jframe in this case 
      
      to add: 
      jpanel.add(component); //add component to jpanel in this case i used jpanel 
      jpanel.revalidate(); 
      jframe.repaint();//repaint a JFrame jframe in this case 
      

      看看这是否适合你。自己没试过……

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-02-03
        • 2011-09-22
        • 1970-01-01
        • 2011-11-12
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多