In depth application analysis of Java event registration

  • 2020-04-01 02:03:32
  • OfStack

Personal understanding of the three questions last time:
1) the program first started with the main function, assuming that the main function is not static, have to instantiate this class first, then call the main method, this seems to be unrealistic. Secondly with the static main method is stored in the storage area of static, that is to say after create a class, there was the main function, remove the static after modification, compiler can pass, but cannot perform.
2) after checking the API, the readLine() side of the BufferedRead object is found to read the data, where there is a new line is a line, when directly using readLine judgment has read a line, when the output data will be interlaced output.

FileReader file=new FileReader("C:\123.txt");
            BufferedReader br1=new BufferedReader(file);
                       //A line has been read while judging
            while((br1.readLine())!=null)
            {   //The output is the second line
                System.out.println(br1.readLine());
            }

So use a temporary string variable to store the data you read, and change the program so it works:

FileReader file=new FileReader("C:\123.txt");
            BufferedReader br1=new BufferedReader(file);

            String cd;
            while((cd=br1.readLine())!=null)
            {
                System.out.println(cd);
            }

3) if the initialization of the client, input stream and output stream are all put into the event of Send button, the program will achieve the effect I want. After clicking the connection, the client will connect to it. However, I always think that there will be other security risks, and it will leak out one day.
Today to record here is a teacher with the classroom layout of a small program, the realization of a calculator prototype, which only add and subtract operations, to which the button registration has a little new understanding, or the code posted first.

import javax.swing.*;
  import java.awt.*;
  import java.awt.event.*; 
public class ComboBoxTest extends JFrame{     
      private JButton done =new JButton(" Done ");
      private JButton clear=new JButton(" Clear ");      
      private JLabel  label = new JLabel("Please choose serverID:0(+)and1(-)");      

 public  ComboBoxTest(){     
     //Add a combo box and set two options
      final JComboBox c = new JComboBox();
      int [] array = {0,1};
      c.addItem(array[0]);
      c.addItem(array[1]);
      final JTextField operand1=new JTextField(10);      //Add the first operand to the input text field, which takes up 8 columns
      final JLabel t=new JLabel("+");                     //Initializes the middle operator as a "+" sign
      final JTextField operand2=new JTextField(10);      //Second operator
      final JTextField result=new JTextField(4);         //The resulting text field is initialized with four columns

      //Register an event for combo box c that fires when combo box options change
      c.addActionListener(new ActionListener() {      
          public void actionPerformed(ActionEvent e) {
              if(c.getSelectedIndex()==0)   //Make the middle operator show a + sign when the option is 0
                t.setText(" + ");           
               else  t.setText(" - ");        
         }
        });
      //Register an event for the button Done, when the middle operator does different things at the same time
       done.addActionListener(new ActionListener(){   
            public void actionPerformed(ActionEvent e) {
                if(c.getSelectedIndex()==0)   
                {
                    //When the middle operator is "+", add the two operands, and the get() method of the text field returns a string to cast
                     int a=Integer.parseInt(operand1.getText())+Integer.parseInt(operand2.getText());                     
                     result.setText("="+" "+a+" ");  //Set the result to display the corresponding result
                   }          
              else {
                  //Subtract two operands when the middle operator is a - sign
                int a=Integer.parseInt(operand1.getText())-Integer.parseInt(operand2.getText());                     
                result.setText("="+" "+a+" ");
              }    
            }              
          });
    //Register an event for the button clear, clearing the contents of both operands and results
     clear.addActionListener(new ActionListener(){
            public void actionPerformed(ActionEvent e) {            
            operand1.setText("");    //Clear operand 1
            operand2.setText("");    //Clear operand 2
            result.setText("");      //Empty the result box
            }               
          });    
      setLayout(new FlowLayout());
      add(label);                   
      add(c);
      add(operand1);
      add(t);
      add(operand2);
      add(result);
      add(done);
      add(clear); 
      setSize(350,140);  
      setVisible(true);   
     }

   public static void main(String[] args) {
       new ComboBoxTest(); 
         }
}

The above code USES anonymous classes to register events for option boxes, "done", and "clear" buttons. This class is created to add events to the corresponding component.
Implement the only interface function in the ActionListener abstract class, and define an object for the ButtonListener listener listener

class ButtonListener implements ActionListener{
       public void actionPerformed(ActionEvent e){
            operand1.setText("");    //Clear operand 1
            operand2.setText("");    //Clear operand 2
            result.setText("");      //Empty the results box & NBSP;                      
       }
   }

The object property of a ButtonListener needs to be defined in the class property:

private ButtonListener clearaction = new ButtonListener();

The last step is to register the event object of the button listener to the button:

clear.addActionListener(clearaction);

Personal summary:
So one way to register events is basically to say ButtonListener = > ActionListener => The downside of registering buttons, compared to anonymous classes, is that there's a little bit more code, but let's say you have N of them that you want to have
When the button of function and the method of event implementation are relatively complex, an object of ActionListener can be implemented and N ButtonListener listener objects can be defined at the same time, and the same event implementation can be registered to the button. In contrast, anonymous classes in this case will have a lot of work and the amount of code will surge.
You can also use the event equetsource () method to put all the event handling into one function, which seems to be more maintainable, and emphasize the implementation of abstract functions in the interface in the class declaration.

public class ComboBoxTest extends JFrame implements ActionListener

The specific realization process is as follows:

public void actionPerformed(ActionEvent e){
       if(e.getSource()==c){
              if(c.getSelectedIndex()==0)   //Make the middle operator show a + sign when the option is 0
                    t.setText(" + ");           
                    else  t.setText(" - ");     
       }

       if(e.getSource()==done){
            if(c.getSelectedIndex()==0)   
            {
                //When the middle operator is "+", add the two operands, and the get() method of the text field returns a string to cast
                 int a=Integer.parseInt(operand1.getText())+Integer.parseInt(operand2.getText());                     
                 result.setText("="+" "+a+" ");  //Set the result to display the corresponding result
               }          
          else {
              //Subtract two operands when the middle operator is a - sign
            int a=Integer.parseInt(operand1.getText())-Integer.parseInt(operand2.getText());                     
         result.setText("="+" "+a+" ");
          }      
       }       
       if(e.getSource()==clear){
           operand1.setText("");    //Clear operand 1
            operand2.setText("");    //Clear operand 2
            result.setText("");      //Empty the results box & NBSP;    
       }


Related articles: