import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
class frm extends JFrame
{

JPanel p = new JPanel(); 
JButton b1 = new JButton("Add");
frm()
{
Container con =getContentPane();
con.add(p);
p.add(b1);
b1.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
p.add(new JButton("ff"));
}
} );
}

}class Demo 
{
public static void main(String[] args) 
{
frm f = new frm();
f.setSize(300,300);
f.setVisible(true);
}
}希望通过实现 点击 add按钮 在面板上生成一个新的按钮或别的组件 这个功能可以实现么?

解决方案 »

  1.   

    可以的
    package je.test;
    //动态加载新的按钮
    import java.awt.*;
    import javax.swing.*;
    import java.awt.event.*;public class addButtonTest implements ActionListener
    {
    JFrame frame;
    Container panel;
    JButton button;
    JPanel btsPanel;

    public addButtonTest()
    {
    frame = new JFrame("AddTest");
    frame.setSize(400,300);
    panel = frame.getContentPane();
    button = new JButton("Add");
    button.addActionListener(this);
    frame.setLayout(new FlowLayout());
    panel.add(button);
    btsPanel = new JPanel();
    frame.add(btsPanel,FlowLayout.CENTER);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setVisible(true);
    }

    public void actionPerformed(ActionEvent e)
    {
    if (e.getSource().equals(button))
    {
    JButton btn = new JButton("NewButton");
    btsPanel.add(btn);
    frame.validate();
    }
    }

    public static void main(String[] args)
    {
    new addButtonTest();
    }
    }
      

  2.   

    当然可以,楼上的仁兄给出的代码应该是对的,对于动态的问题,只要存在响应,就可以在响应后做出反应,在接受响应后重新new 函数即可,当然你这时的函数就要添加你所要的效果,就像你这个jframe,按添加后,就在新的对象中添加button,楼上给出的是比较好的方法,如果不好理解的话,你也可以重构构造函数,写两种构造函数,new不同的构造函数实现不同的面板效果