0

I want to check the event of panel class which is being added on the JFrame class. In this sample program there is a button on a panel.

I want to monitor the click event of the button from the source frame.

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");
        cp.add(b1);
        b1.addActionListener(this);
    }

    public void actionPerformed(ActionEvent ae) {
        if (ae.getActionCommand().equals("add")) {
            panel1 frm = new panel1();
            cp.add(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);
    }
}
4

2 回答 2

1

您需要以JButton某种方式使“外部”世界可用。

就个人而言,我不愿意让按钮本身可用,相反,我会允许外部世界附加一个ActionListener...

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

    public void actionPerformed(ActionEvent ae) {
        if (ae.getActionCommand().equals("add")) {
            TestPane frm = new TestPane();
            frm.addActionListener(...); // Add your new action listener here
            cp.add(frm);
        }
    }

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


public class TestPane extends JPanel {
    private JButton b1;
    public TestPane() {
        b1 = new JButton("ok");
        add(b1);
    }

    public void addActionListener(ActionListener listener) {
        b1.addActionListener(listener);
    }

    public void removeActionListener(ActionListener listener) {
        b1.removeActionListener(listener);
    }
}
于 2012-12-11T06:37:28.520 回答
0

无论您放入框架中,它都只是放入框架的中心。因此,请使用 BorderLayout 使其可见,如下所示

公共无效actionPerformed(ActionEvent ae){
        if (ae.getActionCommand().equals("add")) {
            System.out.println("in actionPerformed");
            面板 1 frm = 新面板 1();
          // this.removeAll();
            add(frm,BorderLayout.NORTH);
            this.validate();
        }
    }
于 2012-12-11T06:55:24.553 回答