简体   繁体   中英

Is there something wrong with my algorithms?

I'm creating an "addStudent" method and it looks like this:

package gui;

import java.awt.*;
import java.awt.event.*;

import javax.swing.*;
import javax.swing.border.*;

import dataManager.DataManager;



public class test extends JFrame {
    private static boolean addHowManyStudentsSet=false;
    private static int addHowManyStudents=0;
    private static JFrame addStudentFrame = new JFrame("Add Student");
    private static JTextField newStudentName = new JTextField();
    private static JTextField newStudentID = new JTextField();
    private static JLabel label1 = new JLabel("");
    private static final JButton addButton = new JButton("ADD");
    private static JButton addStudent = new JButton("SET");
    private static JPanel addStudentPanel = new JPanel();
    /**
     * Constructor of the GUI, creating labels, buttons, and other stuff.  Then they are added onto the interface.
     */
    public test() {
        super("test");
        setSize(200, 200);
        setLocation(10, 10);
        final JPanel panel = new JPanel();

        addStudent.setBounds(10,60,80,25);
        panel.add(addStudent);
        add(panel);
        addStudent.addActionListener(new ActionListener(){
            public void actionPerformed(ActionEvent ae){
                if(!addHowManyStudentsSet){
                    try{
                        addHowManyStudents=Integer.parseInt(JOptionPane.showInputDialog(panel, "Add how many students..."));
                        JOptionPane.showMessageDialog(panel,"Set, please click this button again");
                        addStudent.setText("ADD");
                        addHowManyStudentsSet=true;
                    }
                    catch(NumberFormatException ex){
                        JOptionPane.showMessageDialog(panel, "Please enter a number");
                    }
                }

                else{

                    addStudentPanel.setLayout(null);
                    label1.setText("    "+(addHowManyStudents-1)+" more students to add...");
                    label1.setFont(new Font("Segoe UI Light",Font.PLAIN,30));
                    label1.setBounds(5,20,400,25);
                    newStudentName.setBounds(270,100,140,30);
                    newStudentID.setBounds(270,150,140,30);
                    final JLabel label2 = new JLabel("New Student Name:");
                    final JLabel label3 = new JLabel("New Student Number:");
                    label2.setBounds(30,100,200,30);
                    label2.setFont(new Font("Segoe UI Light",Font.PLAIN,21));
                    label3.setBounds(30,150,200,30);
                    label3.setFont(new Font("Segoe UI Light",Font.PLAIN,21));
                    //      final JButton addButton = new JButton("ADD");
                    addButton.setBounds(330,220,80,25);
                    addStudentPanel.add(addButton);
                    addButton.addActionListener(new ActionListener(){
                        public void actionPerformed(ActionEvent ae){            
                            addStudent();
                            //      addStudentFrame.dispose();
                        }
                    });                 
                    addStudentPanel.add(label1);
                    addStudentPanel.add(label2);
                    addStudentPanel.add(label3);
                    addStudentPanel.add(newStudentName);
                    addStudentPanel.add(newStudentID);
                    addStudentFrame.add(addStudentPanel);
                    addStudentFrame.setVisible(true);
                    addStudentFrame.setLocation(40,40);
                    addStudentFrame.setSize(470,335);
                }

            }

        });
    }

    public static void main(String[] args) {
        JFrame f = new test(  );

        f.addWindowListener(new WindowAdapter(  ) {
            public void windowClosing(WindowEvent we) { 
                System.exit(0); }
        });
        f.setVisible(true);
    }

    private static void addStudent(){
        if(addHowManyStudents>0){
            addHowManyStudents--;           
            //          addButton.addActionListener(new ActionListener(){
            //              public void actionPerformed(ActionEvent ae){        
            System.out.println("add");
            //          //  JLabel label1 = new JLabel((StudentList.getHowManyStudentToAdd()-1)+"more students to add");
            try{
                String studentName = newStudentName.getText();
                long studentNum = Long.parseLong(newStudentID.getText());
                //          //  DataManager.addStudent(studentNum, studentName);
                System.out.println("Done: "+studentNum+", "+studentName);
            }
            catch(NumberFormatException ex){
                JOptionPane.showMessageDialog(addStudentFrame, "Student ID can only be numbers");
            }
            if(addHowManyStudents!=0){
                label1.setText("    "+(addHowManyStudents-1)+" more students to add...");

            }
            newStudentName.setText("");
            newStudentID.setText("");
            addStudent();
            //              }               
            //          });

        }
        else if(addHowManyStudents==0){
            JOptionPane.showMessageDialog(addStudentFrame,"Done!");
            addStudentFrame.dispose();
            addHowManyStudentsSet=false;
            addStudent.setText("SET");
        }
    }
}

It's actually pretty interesting because the first time the user clicks the "add" button it only adds the student once (for instance, if you wanted to add 14 students it works properly the first time and tells you there are 13 more students to add.)

However, when the user clicks the "add" button for the second time it adds the student twice (there are 11 more students to add); it adds 8 times on the third click(3 more students to add), and so on.

I don't know what was happening but it just doesn't work properly.

Every time you call addStudent() you add the ActionListener to the JButton, and this will cause the JButton to have the listener added many times eventually. This means that when the button is pressed, the listener will be called several times, which is something you really don't want to happen. The solution is not to do that. Instead add the listener to the JButton only once in the constructor or init method and leave it be at that.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM