如何收听其组件的JButton?

时间:2014-03-19 14:26:44

标签: java swing listener actionlistener

您好,我希望课程能够收听其组件的JButton之一。 这里我有一个Window类,它有一个MyPanel组件,它本身有JButtons。当MyPanel的JButton被按下时,我希望Window得到通知。我怎么能这样做?

这是一段代码,仅用于说明我的需要,尚未经过测试。

感谢您的帮助!

 class Window extends JFrame {
            private MyPanel myPane;

            public static void main(String [] args) {
                Window mainWindow = new Window();
    }

    public Window() {

        this.myPane = new MyPanel();
            getContentPane().add(myPane);

        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        this.setSize(300, 600);
        this.setVisible(true);
    }

        public computations() {
    // Here I would like to get myPane.s, or do other things regarding myPane's attributes (with getters), only once myPane.b2 is pressed.
        }
}

class MyPanel extends JPanel {
    String s;
    JButton b1;
    JButton b2;

    public MyPanel() {
        s = new String("");
        b1 = new JButton("say hello");
        b2 = new JButton("Close");
        this.add(b1);
        this.add(b2);
        ButtonHandler phandler = new ButtonHandler();
        b1.addActionListener(phandler);
        b2.addActionListener( actionPerformed(ActionEvent e) {
            this.s = "Hello world";
        });

    }


    class ButtonHandler implements ActionListener {
        public void actionPerformed(ActionEvent e) {
            // Tells Window class something happened.
        }
    }

}

1 个答案:

答案 0 :(得分:0)

我有一个促销活动,你可以试试它是否有效。由于我只是设置了我的电脑并且还没有安装java环境或IDE,抱歉无法测试我的解决方案。

重点是你可以将一个Window实例传递给MyPanel,如下面的代码:

 class Window extends JFrame {

        public String myStr = "";
        private MyPanel myPane;

        public static void main(String [] args) {
            Window mainWindow = new Window();
}

public Window() {
    this.myPane = new MyPanel();
        getContentPane().add(myPane);

    this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    this.setSize(300, 600);
    this.setVisible(true);
}

    public computations() {
// Here I would like to get myPane.s, or do other things regarding myPane's attributes (with getters), only once myPane.b2 is pressed.
     System.out.println(this.myStr);
    }
}

class MyPanel extends JPanel {
Window win = null;
String s;
JButton b1;
JButton b2;

public MyPanel(Window window) {
    this.win = window;
    s = new String("");
    b1 = new JButton("say hello");
    b2 = new JButton("Close");
    this.add(b1);
    this.add(b2);
    ButtonHandler phandler = new ButtonHandler();
    b1.addActionListener(phandler);
    b2.addActionListener( actionPerformed(ActionEvent e) {
        this.s = "Hello world";
    });

}


class ButtonHandler implements ActionListener {
    public void actionPerformed(ActionEvent e) {
        // Tells Window class something happened.
        this.win.myStr = s;
    }
}

}