我写了一个类,它继承了JPanel是用来创建一个面板用的,在它上面有一个关闭按钮。例如:
import javax.swing.*;
class Panel1 extends JPanel{
     public Panel1(){
        JButton button=new JButton("关闭");
        this.add(button);
     }
}
然后又写了一个驱动类,在这个类中建了一个窗口(JFrame)然后在窗口中添加一个刚刚声明的类的对象。例如:
import javax.swing.*;
public class Test{
   public Test(){}
   public static void main(String [] args){
      JFrame frame=new JFrame("关闭按钮");
      frame.add(new Panel1());
      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      frame.pack();
      frame.setVisebel(true);
   }
}
在这两个类中我想为这个关闭按钮加一个监听器,用来关闭这个窗口怎么加????请各位高手多多指教呀!!!

解决方案 »

  1.   

    沙发,做人要厚道,有帮助的话要给分啊!button.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent e) {
            // TODO
        }
    });
      

  2.   

    你先把JFrame做为一个主类,然后将JPanel做为一个内部类试一试,否则没有办法完成这种操作的
      

  3.   

    你要把那个窗口作为参数传递到Panel里面去,然后给Panel里面的按钮加一个ActionListener,来处理关闭事件比如:class Panel1 extends JPanel implements ActionListener{
         JFrame parentFrame;
         public Panel1(JFrame parentFrame){
            this.parentFrame = parentFrame;
            JButton button=new JButton("关闭");
            button.setActionCommand("closeFrame");
            button.addActionListener(this);
            this.add(button);
         }     public void actionPerformed(ActionEvent e) {
             if (e.getActionCommand().equals("closeFrame") {
                 //关闭parentFrame操作
             }
         }
    }
      

  4.   

    setDefaultCloseOperation(EXIT_ON_CLOSE);