2012-12-10 20 views
4

我试图在下面的代码的帮助下在一个swing窗口JFrame容器上添加和删除面板。 JPanel被添加,如果它添加在构造函数中,但它不会被添加运行时。在jframe运行时添加删除面板

import java.awt.Container; 
import java.awt.event.ActionEvent; 
import java.awt.event.ActionListener; 

import javax.swing.JButton; 
import javax.swing.JFrame; 
import javax.swing.JPanel; 

class test extends JFrame implements ActionListener { 
    test() { 
     Container cp = this.getContentPane(); 
     JButton b1 = new JButton("add"); 
     JButton b2 = new JButton("remove"); 
     cp.add(b1); 
     cp.add(b2); 
     b1.addActionListener(this); 
     b2.addActionListener(this); 
    } 

    public void actionPerformed(ActionEvent ae) { 
     if (ae.getActionCommand().equals("add")) { 
      panel1 frm = new panel1(); 
      cp.add(frm); 
     } 
     if (ae.getActionCommand().equals("remove")) { 
      remove(frm); 
     } 
    } 

    public static void main(String args[]) { 
     test t1 = new test(); 
     t1.show(true); 
    } 
} 

class panel1 extends JPanel { 
    panel1() { 
     JButton b1 = new JButton("ok"); 
     add(b1); 
    } 
} 
+0

你需要重新绘制和或验证哟用'repaint()'方法整个框架,这应该在添加或删除面板后完成 – SomeJavaGuy

+0

你的意思是“它没有被添加运行时”是什么意思? –

回答

5
  1. 为你的概念(后删除或添加JPanelJFrame),要叫validate() & repaint()JFrame

  2. 更好的可能是使用CardLayout

+0

我必须调用validate()和repaint()方法。 –

+0

有一次,作为最后的代码行,完成对GUI的所有更改后, – mKorbel

+0

@mKorbel调用'revalidate()'总是一个更好的选择vs'validate()'/'invalidate()'see [here](http ://stackoverflow.com/questions/13549976/how-to-change-the-dimension-of-a-component-in-a-jframe/13551229#13551229)更多,但其余+1。 –

1

我处理类似的问题,我想改变面板续ained在运行时
面板经过一番测试,再测试和大量的失败我的伪算法是这样的:

parentPanel:包含我们要删除
childPanel面板:面板我们要切换
parentPanelLayout :parentPanel
editParentLayout()的布局:构建parentPanel不同childPanel和新parentPanelLayout每次

parentPanel.remove(childPanel); 
editParentLayout(); 
parentPanel.revalidate(); 
parentPanel.repaint();