If 语句不会随着 Java 文本字段中的不同输出而改变

问题描述 投票:0回答:1

所以我对整个 Java UI 事情还很陌生,我刚刚遇到了一个问题,其中一个 if 语句的输出(带有建议添加数字、特殊字符等的语句,密码强度只是工作)很好)无论我尝试更改文本字段中的输入多少次都不会改变。 .

if(e.getSource()==click){
    pass = Input.getText();


    Pattern upperCase = Pattern.compile("[A-Z]");
    Pattern numbers = Pattern.compile("[0-9]");
    Pattern special = Pattern.compile("[^A-Za-z0-9]");

    Matcher upper = upperCase.matcher(pass);
    Matcher number = numbers.matcher(pass);
    Matcher spec = special.matcher(pass);

    boolean a = upper.find();
    boolean b = number.find();
    boolean c = spec.find();


    if(pass.length() > 15 || pass.length() < 5){
        Text1.setText("The password must be between 5 and 15 characters");
    }
    else{


        if (a && b && c) {
            Text1.setText("The password looks strong");
        } else {
            if ((a && b) || (b && c) || (c && a)) {
                Text1.setText("The password strength is average");
                if(!a){
                    Text2a.setText("*Try adding some uppercase letters");
                }
                if(!b){
                    Text2b.setText("*Try adding some numbers");
                }
                if(!c){
                    Text2c.setText("*Try adding some special characters");
                }
            }
            else {
                Text1.setText("The password seems pretty weak");
                if(!a){
                    Text2a.setText("*Try adding some uppercase letters");
                }
                if(!b){
                    Text2b.setText("*Try adding some numbers");
                }
                if(!c){
                    Text2c.setText("*Try adding some special characters");
                }
            }
        }
    }
}

我尝试在不同(和外部)循环中重新排列 if 语句,对所有代码使用单独的方法并在 else 语句中调用它,但似乎没有任何效果。 我希望“尝试添加等等” if 语句根据用户输入的字符串进行更改,但无法弄清楚。 谢谢!!

java if-statement jbutton
1个回答
0
投票

您的代码似乎工作正常,但是,我认为您应该在每次触发按钮的 ActionPerformed 事件来运行代码时清除 JTextFields,例如:

if (evt.getSource() == click) {
    Text1.setText("");
    Text2a.setText("");
    Text2b.setText("");
    Text2c.setText("");

    pass = Input.getText();
    // ... The rest of your `if` block code ...
}

是的...您应该遵循正确的 Java 命名规则。 :-/

我注意到代码中没有考虑小写字母。我认为密码中的驼峰式大小写(大写和小写)应该增加强度因素。

下面是用于检查密码强度的小型演示 GUI 应用程序的可运行代码。代码中的大量注释可以告诉您发生了什么。请务必阅读它们。稍后删除您认为不需要的评论:

enter image description here

package passwordstrengthtestguidemo;

// Required Imports:
import java.awt.Color;
import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.Window;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JFormattedTextField;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JSpinner;
import javax.swing.JSpinner.DefaultEditor;
import javax.swing.JTextField;
import javax.swing.SpinnerNumberModel;
import javax.swing.WindowConstants;
import javax.swing.border.EmptyBorder;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;

public class PasswordStrengthTestGuiDemo {

    // Class member variables (scope of these are class global):
    private JFrame frame;
    private JTextField passwordField;
    private JLabel passwordStatus;
    private JSpinner spinner;
    private JButton testButton;
    int maxPasswordLength = 15;
    private int strengthScale = 0;
    private boolean hasLower, hasUpper, hasDigits, hasSpec;

    
    // Constructor:
    public PasswordStrengthTestGuiDemo() {
        // Create the GUI Window:
        initializeGUI();
        
        /* Create event listeners for the Password entry field,
           the Test button, and the Max Password Length numerical
           Spinner.                                */
        createListeners();
    }

    // The application's entry point for execution:
    public static void main(String[] args) {
        /* App started this way to avoid the need for statics
           unless we really want them:       */
        new PasswordStrengthTestGuiDemo().startApp(args);
    }

    /* Called from the `main()` method (above) to start 
       the ball rolling (so to speak).             */
    private void startApp(String[] args) {
        java.awt.EventQueue.invokeLater(() -> {
            frame.setVisible(true);             // Make GUI window visible.
            frame.setLocationRelativeTo(null);  // Set the GUI in center screen.
        });
    }

    private void initializeGUI() {
        // Create JFrame Window:
        frame = new JFrame();
        frame.setResizable(false);
        frame.setType(Window.Type.UTILITY);
        frame.setTitle("Password Strength \"Demo\"");
        frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        frame.setPreferredSize(new Dimension(480, 240));
        frame.setAlwaysOnTop(true);

        // Create JFrame's contentPane panel (keeping default Layout):
        JPanel mainPanel = new JPanel();

        // Create the JLabel for Password Entry Field (JTextBox):
        JLabel passEntryLabel = new JLabel("Enter Password:");
        mainPanel.add(passEntryLabel); 

        /* Initialize the Password Entry Field (JTextBox).
           This Component was declared in the members area
           to make it accessable globally. The KeyPressed
           event for this JTextBox is created within the 
           createListeners() method. It detects when the 
           ENTER keyboard key is hit in order to optionally
           fire the Test Button directly from the JTextBox. */
        passwordField = new JTextField(27);
        // Make sure it is Editable:
        passwordField.setEditable(true);    
        // Provide a Tool Tip:
        passwordField.setToolTipText("<html> Pressing ENTER after your entry <br>"
                                   + " is the same as selecting button. ");
        mainPanel.add(passwordField);   // Add JTextField to JPanel

        /* Create an additional JPanel to support the Password Status 
           JLabel (below):                       */
        JPanel statusPanel = new JPanel();
        // Set a 1 pixel gray Line border around the Status Panel:
        statusPanel.setBorder(BorderFactory.createLineBorder(Color.gray, 1));
        /* Set a preferred size for this panel so that it resides 
           nicely center in the GUI Window using the main panel's
           default layout.                                   */
        statusPanel.setPreferredSize(new Dimension(400, 100));
        /* Give this particular JPanel a Layout manager of 
           GridLayout so that when the password status JLabel
           is added, it will fill the entire panel:       */
        statusPanel.setLayout(new GridLayout(1, 1));

        /* Initialize the Password Status Label (JLabel).
           This Component was declared in the members area
           to make it accessable globally:             */
        passwordStatus = new JLabel("");  // Initialize with no text.
        passwordStatus.setOpaque(true);   // Set the component as Opaque (not transparent)
        passwordStatus.setBackground(Color.white);  // Set background color to white.
        passwordStatus.setHorizontalAlignment(JLabel.LEFT); // Set text horizontal alignment to the lEFT.
        passwordStatus.setVerticalAlignment(JLabel.TOP); // Set the text vertical alignment to the TOP.
        /* Use EmptyBorder border around JLabel to set margins: 
           Left Margin = 5 pixels | Top Margin = 10 pixels.  */
        passwordStatus.setBorder(new EmptyBorder(5, 10, 0, 0)); 

        // Add the Password Status Label to the Status Panel:
        statusPanel.add(passwordStatus);
        
        // Add the Password Status Panel to the Main Panel:
        mainPanel.add(statusPanel);

        // Create a JLabel for the Max Password Length Numerical Spinner component:
        JLabel spinLabel = new JLabel("Change Max Password Length:  ");
        // Add the Label to the Main Panel:
        mainPanel.add(spinLabel);
        
        // JSpinner for changing maximum allowable password length:
        /* Initialize the Numerical Spinner (JSpinner). This Component 
           was declared in the members area to make it accessable globally.
           The default numberical value for the spinner is 15 which is what
           the `maxPasswordLength` member variable was initialized to. The
           minimum allowable spinner value is 5 and the maximum value is 50.
           Step increments of the spinner is by 1. The StateChanged event 
           for this JSpinner is created within the createListeners() method:  */
        spinner = new JSpinner(new SpinnerNumberModel(maxPasswordLength, 5, 50, 1));
        // Set the numerical display to be on the left side of the spinner.
        JFormattedTextField spinnerTextField = ((DefaultEditor) spinner.getEditor()).getTextField();
        spinnerTextField.setHorizontalAlignment(JTextField.LEFT);
        /* Set a preferred size for this JSpinner so that it resides 
           nicely center in the GUI Window using the Main Panel's
           default layout.                                   */
        spinner.setPreferredSize(new Dimension(80,25));
        // Add the Numerical Spinner to the Main Panel:
        mainPanel.add(spinner);
        
        /* Initialize the Test Button (JButton). This Component 
           was declared in the members area to make it accessable
           globally. The ActionPerformed event for this button is 
           created within the createListeners() method:        */
        testButton = new JButton("Test Password For Strength");
        
        // Add the Test Button to the Main Panel:
        mainPanel.add(testButton);
        
        // Set the Main Panel as the JFrame's Content Pane:
        frame.setContentPane(mainPanel);
        
        // Pack the JFrame components:
        frame.pack();
    }

    @SuppressWarnings("Convert2Lambda") 
    private void createListeners() {
        /* Various event Listeners - You can convert these to 
           Lambda if you like. I left them like this so to easier 
           see what is going on. If you do convert them to lambda,
           then you can delete the `@SuppressWarnings(...)` annotation
           above this method declaration:                      */
        
        // ActionListerner for the "Test Password For Strength" button.
        testButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                processPassword();
            }
        });

        /* KeyListener for Password entry JTextField to detect 
           ENTER key hit. Hitting the ENTER key is the same as
           selecting the "Test Password For Strength" button. */
        passwordField.addKeyListener(new KeyAdapter() {
            @Override
            public void keyPressed(KeyEvent e) {
                if (e.getKeyCode() == KeyEvent.VK_ENTER) {
                    e.consume();
                    testButton.doClick();
                }
            }
        });

        /* ChangeListener for the Max Password Length Numerical Spinner:
           This allows for dynamically changing the max password length. */
        spinner.addChangeListener(new ChangeListener() {
            @Override
            public void stateChanged(ChangeEvent e) {
                maxPasswordLength = (Integer)spinner.getValue();
            }
        });
    }
    
    /* The beating heart of this application. This method is
       fired whenever the User either selects the window Test
       button or, hits the ENTER key within the Password Entry
       Field. It starts to process the password (if any) that
       was supplied within the Password Entry Field to check
       its strength and provide suggestions to make the password
       stronger.    
    */
    private void processPassword() {
        // Set `maxPasswordLength` member variable to what is in numerical Spinner:
        maxPasswordLength = (int)spinner.getValue(); // Default spinner value is 15.
        String pass = passwordField.getText();       // Get the supplied password (if any).
        strengthScale = 0;                           // Reset strengthScale to 0. 

        Pattern lowerCase = Pattern.compile("[\\p{Ll}]");  // Lowercase - Any Language
        Pattern upperCase = Pattern.compile("[\\p{Lu}]");  // Uppercase - Any Language
        Pattern numbers = Pattern.compile("[\\d]");        // Any Digit
        Pattern special = Pattern.compile("[\\p{P}]");     // Any Special Character;

        Matcher lower = lowerCase.matcher(pass);           // Find any lowercase letters
        Matcher upper = upperCase.matcher(pass);           // Find any uppercase letters
        Matcher number = numbers.matcher(pass);            // Find any numerical digits
        Matcher spec = special.matcher(pass);              // Find any special characters

        // Set boolean flags to what type of characters were detected in password:
        // Are there any lowercase letters?
        hasLower = lower.find();
        // If Yes...
        if (hasLower) {
            // Add 1 to strengthScale sum.
            strengthScale++;    
        }

        // Are there any uppercase letters?
        hasUpper = upper.find();
        // If Yes...
        if (hasUpper) {
            // Add 1 to strengthScale sum.
            strengthScale++;
        }

        // Are there any numerical digits?
        hasDigits = number.find();
        // If Yes...
        if (hasDigits) {
            // Add 1 to strengthScale sum.
            strengthScale++;
        }

        // Are there any special characters?
        hasSpec = spec.find();
        // If Yes...
        if (hasSpec) {
            // Add 1 to strengthScale sum.
            strengthScale++;
        }

        /* Process the sum of strength Scale and indicate the status.
           This will also ultimately provide password strengthening 
           suggestions:                          */
        passwordStatus.setText(processStrengthScaleValue(pass));
    }

    private String processStrengthScaleValue(String pass) {
        /* Create a StringBuilder object. Far better to use this 
           than concatenating strings. Start the builder with the 
           string "<html>". The Password Status display JLabel uses 
           basic HTML to display results. It can produce a flexible
           output as you can see when you run this application:   */
        StringBuilder sb = new StringBuilder("<html>");
        
        /* Add the supplied password to the builder. The actual 
           password text will have a hex forecolor which is an
           orange variant.                            */
        sb.append("The supplied Password is: <font color=#FFA500><b>")
                  .append(pass).append("</b></font><br>");
        
        /* If by chance the password length is less than 5 or greater
           than that specified within the Numerical Spinner (which is 
           held within the class member variable `maxPasswordLength`), 
           then indicate as such within the Password Status Label.  */
        if (pass.length() < 5 || pass.length() > maxPasswordLength) {
            sb.append("<font color=red>The password must be inclusively between 5 and ")
                    .append(maxPasswordLength)
                            .append(" characters!</font>");
        }
        /* Otherwise... Indicate the determined strength of the supplied
           password within the Password Status Label. Password strength
           suggestions are also determined here.                 */
        else {
            // Make assumptions based on the determined strength Scale value.
            switch (strengthScale) {
                /* A strength scale value of 1 (only one of the four character 
                   types is within the password):       */
                case 1 -> {
                    sb.append("The password seems pretty <font color=red>weak</font>!<br>");
                    // Determine and provide suggestions for a stronger password:
                    sb.append(strengthSuggestions());   
                }
                
                /* A strength scale value of 2 (only two of the four character 
                   types is within the password):       */
                case 2 -> {
                    sb.append("The password strength is <font color=blue>average</font>!<br>");
                    // Determine and provide suggestions for a stronger password:
                    sb.append(strengthSuggestions());
                }
                
                /* A strength scale value of 3 (only three of the four character 
                   types is within the password):       */
                case 3 -> {
                    sb.append("The password looks <font color=green>Strong</font> (low level)!<br>");
                    // Determine and provide suggestions for a stronger password:
                    sb.append(strengthSuggestions());
                }
                
                /* A strength scale value of 4 (all four character types are
                   within the password):       */
                case 4 -> sb.append("The password looks <font color=green>Strong</font> (high level)!<br>");
                // No suggestions for a stronger password is required or available.
            }
        }

        // Apply the closing html tag to the string build:
        sb.append("</html>");
        return sb.toString();   // Return the built string.
    }

    private String strengthSuggestions() {
        /* Create a StringBuilder object. Far better to use this 
           than concatenating strings. Start the builder with a 
           null string (""). The Password Status display JLabel uses 
           basic HTML to display results. It can produce a flexible
           output as you can see when you run this application:   */
        StringBuilder sb = new StringBuilder("");
        
        /* If there are no lowercase alphabetic characters within the 
           password then suggest to apply some for a stronger password. */
        if (!hasLower) {
            /* If password is already at Strong (low level), make the 
               suggestion to acquire a Strong (High Level):        */
            if (strengthScale == 3) {
                sb.append("<font color=red>*</font> For high level strength, "
                        + "try adding some lowercase letters.<br>");
            }
            /* Otherwise...make the suggestion to add lowercase characters
               to increase the password strength level:         */
            else {
                sb.append("<font color=red>*</font> For a higher strength level, "
                        + "try adding some lowercase letters.<br>");
            }
        }
        
        /* If there are no uppercase alphabetic characters within the 
           password then suggest to apply some for a stronger password. */
        if (!hasUpper) {
            /* If password is already at Strong (low level), make the 
               suggestion to acquire a Strong (High Level):        */
            if (strengthScale == 3) {
                sb.append("<font color=red>*</font> For high level strength, try "
                        + "adding some uppercase letters.<br>");
            }
            /* Otherwise...make the suggestion to add uppercase characters
               to increase the password strength level:         */
            else {
                sb.append("<font color=red>*</font> For a higher strength level, "
                        + "try adding some uppercase letters.<br>");
            }
        }
        
        /* If there are no numerical digits within the password, then
           suggest to apply some for a stronger password. */
        if (!hasDigits) {
            /* If password is already at Strong (low level), make the 
               suggestion to acquire a Strong (High Level):        */
            if (strengthScale == 3) {
                sb.append("<font color=red>*</font> For high level strength, "
                        + "try adding some numerical digits.<br>");
            }
            /* Otherwise...make the suggestion to add numerical digits
               to increase the password strength level:         */
            else {
                sb.append("<font color=red>*</font> For a higher strength level, "
                        + "try adding some numerical digits.<br>");
            }
        }
        
        /* If there are no special characters within the password, then
           suggest to apply some for a stronger password. */
        if (!hasSpec) {
            /* If password is already at Strong (low level), make the 
               suggestion to acquire a Strong (High Level):        */
            if (strengthScale == 3) {
                sb.append("<font color=red>*</font> For high level strength, "
                        + "try adding some special characters.<br>");
            }
            /* Otherwise...make the suggestion to add special character
               to increase the password strength level:         */
            else {
                sb.append("<font color=red>*</font> For a higher strength level, "
                        + "try adding some special characters.<br>");
            }
        }
        return sb.toString();  // Return the built string.
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.