With the gradual development, I found that I did not understand anything, And suddenly lost my sense of superiority. Originally, what programmers want to do with this kind of superiority will only let you go downhill, continue to learn and understand and try again to survive. Let's go back to the basics. Otherwise, we will encounter a lot of problems in the future.
There are two methods for my understanding about the response of actionlistener. First, you put it in a new class, implement the actionlistener interface, and write the public void actionreceivmed (actionevent e) method. This method is useful when inherited from jframe, but if it is a jframe created in public static void main (string [] ARGs), and then (such as a button) to implement the listener, it is not appropriate to implement the actionlistener interface (ah, many of them know what is appropriate after you do). However, Java provides another solution:
Import java. AWT .*;
Import javax. Swing .*;
Import java. AWT. event .*;
Public class actionlistenertest ...{
Public static void main (string [] ARGs )...{
Jframe frame = new jframe ("button test ");
Frame. setdefaclocloseoperation (jframe. exit_on_close );
Final jbutton jbclose = new jbutton ("Close the frame ");
Jbclose. addactionlistener (New actionlistener ()...{
Public void actionreceivmed (actionevent e )...{
If (E. getsource (). Equals (jbclose ))...{
System. Exit (0 );
}
}
}
);
Frame. Add (jbclose );
Frame. Pack ();
Frame. setvisible (true );
}
}
That is, define an actionlistenner in the addactionlistener parameter and override its actionreceivmed. However, it should be noted that the actionsynchronized med must be public, otherwise the permission is insufficient. In addition, the components used inside must be declared as final externally, which may cause some restrictions on use.
The other one is actually very commonly used. It has been used before, but it is very troublesome to write it again here.
Import java. AWT .*;
Import javax. Swing .*;
Import java. AWT. event. *; public class buttonframe extends jframe implements actionlistener ...{
Jbutton jbclose = NULL;
Public buttonframe ()...{
Super ("buttonframe test ");
Jbclose = new jbutton ("Close the frame in buttonframe ");
Jbclose. addactionlistener (this );
This. setdefaclocloseoperation (jframe. exit_on_close );
This. Add (jbclose );
This. Pack ();
This. setvisible (true );
}
Public void actionreceivmed (actionevent e )...{
If (E. getsource (). Equals (jbclose ))...{
System. Exit (0 );
}
}
Public static void main (string [] ARGs )...{
Buttonframe BF = new buttonframe ();
}
}
The two programs have the same effect. They all end the program after clicking the button.