Now a lot of Java books, in introducing the swing event model, in order for Java beginners to be easy to understand and get started, it is usually done in the main class (their own jframe or JPanel): either by the main class as the listener, by judging the event source in the interface's method, and by deciding what to do specifically Or use an implicit class in the main class to implement the listener (because implicit classes can easily access the member variables in the main class). And many Java beginners Use this pattern in later programming (at least I used to). In fact, this approach, though simple, lacks readability, scalability, and maintainability. Before I saw a article on this issue (from the "Javapro"), now sorted out to share with you.
I'll use a simple example below to illustrate how to use patterns to solve this problem.
Now let's say we're going to write a program that uses several radio buttons to select different groupings from a long list, as seen in the following image. When you click the Female radio button, only the girl's name is displayed, and when you click the male button, the program displays the boy's name.
The simplest version of this program is to do everything in the main class, the main class contains arrays and vectors that hold the name of the child, and one of the easiest ways to create an object for each child, one for each object is an image Isfemal () Such a way to help us determine whether to show the male or female. In the program we refer to each child's class as swimmer:
public class Swimmer{
private String name;
private int age;
private String club;
private boolean female;
public Swimmer(String name,int age,String club,boolean female){
this.name=name;
this.age=age;
this.club=club;
this.female=female;
}
public boolean isFemale(){
return female;
}
public String getName(){
return name;
}
public int getAge(){
return age;
}
public String getClub(){
return club;
}
}