如题,有两个类AddO和AddO1,分别为两个窗体,在AddO1中有个按钮,
我想实现这样的功能:每次按下AddO1中的按钮,AddO中就添加一个按钮控件,应该如何实现?
这是我写的,贴上来,不能实现请教各位大大。。
public class AddO extends JFrame
{
AddO()
{
this.setBounds(100,100,200,400);
this.setLayout(new FlowLayout());
AddO1 a1 = new AddO1(this);
a1.setVisible(true);
}
public static void main(String[] s)
{
AddO a = new AddO();
a.setVisible(true);
}}class AddO1 extends JFrame implements ActionListener
{
AddO a;
JButton b;
AddO1(AddO a)
{
this.a = a;
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setBounds(400,100,200,400);
this.setLayout(new FlowLayout()); b = new JButton("添加");
b.addActionListener(this);
this.add(b);
} public void actionPerformed(ActionEvent e) 
{
//我想在这添加,可这样的代码无法实现功能。。
                  a.add(new JButton("new"));
a.repaint();
}}

解决方案 »

  1.   

    import java.awt.FlowLayout;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;import javax.swing.JButton;
    import javax.swing.JFrame;public class AddO extends JFrame
    {
    AddO()
    {
    this.setBounds(100,100,200,400);
    this.setLayout(new FlowLayout());
    this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    AddO1 a1 = new AddO1(this);
    a1.setVisible(true);
    }
    public static void main(String[] s)
    {
    AddO a = new AddO();
    a.setVisible(true);
    }}class AddO1 extends JFrame implements ActionListener
    {
    AddO a;
    JButton b;
    AddO1(AddO a)
    {
    this.a = a;
    this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    this.setBounds(400,100,200,400);
    this.setLayout(new FlowLayout()); b = new JButton("添加");
    b.addActionListener(this);
    this.add(b);
    } public void actionPerformed(ActionEvent e) 
    {
    //我想在这添加,可这样的代码无法实现功能。。
            a.add(new JButton("new"));
    //a.repaint();
            a.setVisible(true); // 这里
    }}