bpatrick24
bpatrick24

Reputation: 5

I want to be able to use check boxes to allow users to select which parameters they want to add into their password in Java

//Removed imports as I felt they were uneccessary to include
//So my program currently can produce a string of 16 characters with random chars from the strings 
//(cont.) LOWER, UPPER, NUMBERS, SYMBOLS
//I want to be able to check specific boxes that will allow me to "filter" what chars i select
public class Main implements ActionListener{
    
    public final static String LOWER = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
    public final static String UPPER = "abcdefghijklmnopqrstuvwxyz";
    public final static String NUMBERS = "0123456789";
    public final static String SYMBOLS = "~`!@#$%^&*()_-+={[}]|\\:;\"'<,>.?/";
    static JButton genButton;
    static JTextField textGenPassword;
    static generatePassword password;
    static JCheckBox upperCheckBox;
    static JCheckBox lowerCheckBox;
    static JCheckBox numCheckBox;
    static JCheckBox symbolCheckBox;


    public static void main(String[] args) {
        
        
        password = new generatePassword();
        
        JFrame frame = new JFrame();
        JPanel titlePanel = new JPanel();   
        JPanel configPanel = new JPanel(); 
        JPanel mainPanel = new JPanel();
        JLabel title = new JLabel();
        JLabel configTitle = new JLabel();
        JCheckBox upperCheckBox = new JCheckBox();
        JCheckBox lowerCheckBox = new JCheckBox();
        JCheckBox numCheckBox = new JCheckBox();
        JCheckBox symbolCheckBox = new JCheckBox();
        JLabel configUpperLabel = new JLabel();
        JLabel configLowerLabel = new JLabel();
        JLabel configNumLabel = new JLabel();
        JLabel configSymbolLabel = new JLabel();
        textGenPassword = new JTextField();
        genButton = new JButton("Generate Password");
        
        //Title panel
        titlePanel.setBackground(new Color(25, 25, 25));
        titlePanel.setPreferredSize(new Dimension(100,100));
        titlePanel.add(title);
        titlePanel.setLayout(new GridBagLayout());
        
        title.setText("Strong Password Generator");
        title.setForeground(Color.WHITE);
        title.setFont(new Font("Roboto", Font.BOLD, 20));
        
        //Config Panel
        configPanel.add(configTitle);
        configPanel.setLayout(new GridLayout(9,1,20,10));
        configTitle.setText("Configuration Settings");
        configTitle.setHorizontalAlignment(SwingConstants.CENTER);
        configTitle.setAlignmentX(JLabel.CENTER);
        configTitle.setForeground(Color.BLACK);
        Border configBorder = new EmptyBorder(20, 0, 0, 0);
        configTitle.setBorder(configBorder);
        
        
        //upercase group
        configPanel.add(configUpperLabel);
        configUpperLabel.setText("Uppercase Letters");
        configUpperLabel.setHorizontalAlignment(SwingConstants.CENTER);
        configPanel.add(upperCheckBox);
        upperCheckBox.addActionListener(password);
        upperCheckBox.setHorizontalAlignment(SwingConstants.CENTER);
        upperCheckBox.setBackground(new Color(107, 208, 255));
        

        //lowercase group
        configPanel.add(configLowerLabel);
        configLowerLabel.setText("Lowercase Letters");
        configLowerLabel.setHorizontalAlignment(SwingConstants.CENTER);
        configPanel.add(lowerCheckBox);
        lowerCheckBox.setHorizontalAlignment(SwingConstants.CENTER);
        lowerCheckBox.setBackground(new Color(107, 208, 255));
        
        //num group
        configPanel.add(configNumLabel);
        configNumLabel.setText("Numbers: ( e.g. 123)");
        configNumLabel.setHorizontalAlignment(SwingConstants.CENTER);
        configPanel.add(numCheckBox);
        numCheckBox.setHorizontalAlignment(SwingConstants.CENTER);
        numCheckBox.setBackground(new Color(107, 208, 255));
        
        //symbol group
        configPanel.add(configSymbolLabel);
        configSymbolLabel.setText("Symbols: ( e.g. ! @ $)");
        configSymbolLabel.setHorizontalAlignment(SwingConstants.CENTER);
        configPanel.add(symbolCheckBox);
        symbolCheckBox.setHorizontalAlignment(SwingConstants.CENTER);
        symbolCheckBox.setBackground(new Color(107, 208, 255));

        
        configPanel.setBackground(new Color(107, 208, 255));
        configPanel.setPreferredSize(new Dimension(200,150));
    

        //Main panel
        mainPanel.setLayout(new GridBagLayout());
        mainPanel.setBackground(new Color(255, 255, 255));
        mainPanel.setPreferredSize(new Dimension(200, 150));

        textGenPassword.setPreferredSize(new Dimension(250, 25));
        textGenPassword.setLocation(100, 100);
        textGenPassword.setHorizontalAlignment(SwingConstants.CENTER);
        
        genButton.addActionListener(password);

        //gridbag constraints
        GridBagConstraints textFieldConstraints = new GridBagConstraints();
        textFieldConstraints.gridx = 0; 
        textFieldConstraints.gridy = 0; 
        textFieldConstraints.fill = GridBagConstraints.HORIZONTAL;
        textFieldConstraints.insets = new Insets(5, 5, 5, 5); 

        
        mainPanel.add(textGenPassword, textFieldConstraints);

        
        GridBagConstraints buttonConstraints = new GridBagConstraints();
        buttonConstraints.gridx = 0; 
        buttonConstraints.gridy = 1; 
        buttonConstraints.insets = new Insets(5, 5, 5, 5); 

        
        mainPanel.add(genButton, buttonConstraints);
        
        frame.setSize(900,600);
        frame.setVisible(true);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setLayout(new BorderLayout());
        frame.setResizable(false);
        
        frame.add(titlePanel,BorderLayout.NORTH);
        frame.add(configPanel,BorderLayout.WEST);
        frame.add(mainPanel,BorderLayout.CENTER);
        
        
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        if (e.getSource() == genButton) {
            textGenPassword.setText(password.genPassword());
        }
        
    }



}

//start of separate class in separate file

public class generatePassword extends Main implements ActionListener{
    

    public String genPassword() {
        
        SecureRandom random = new SecureRandom();
        String combinedChars = LOWER + UPPER + NUMBERS + SYMBOLS;
        StringBuilder password = new StringBuilder(16);
        
        for (int i = 0; i < 16; i++) {
            int num = random.nextInt(combinedChars.length());
            password.append(combinedChars.charAt(num));
        }
        
        return password.toString();
        
    }
    
    
}

I have tried to set up actioneventlisteners and itemeventlisteners on the check boes, but im not sure what im doing wrong?

I'll write something like this

@Override

        if(upperCheckBox.isSelected()) {
            combinedChars += UPPER;
        }
    public void actionPerformed(ActionEvent e) {
        if (e.getSource() == genButton) {
            textGenPassword.setText(password.genPassword());
        }
        
    }

I will set the combinedChars variable to null before doing this, as well as trying to add the event listener to the checkbox, but nothing i seem to do works? I am really lost.

Upvotes: 0

Views: 52

Answers (2)

Gilbert Le Blanc
Gilbert Le Blanc

Reputation: 51445

I rearranged your code to create the following GUI:

SPG

Oracle has a helpful tutorial, Creating a GUI With Swing. Skip the Learning Swing with the NetBeans IDE section. Pay particular attention to the Laying Out Components Within a Container section.

The first thing I did was to separate the creation of the JFrame and the JPanels into separate methods. This makes the code much easier for other people to read, separates your concerns, and allows you to focus on one part of the Swing GUI at a time.

Next, I reordered the code so it's executed in the correct order. The JFrame methods must be called in a specific order. The order I coded is the order I use for most of my Swing applications. JPanels should be created in column, row order.

All Swing applications must start with a call to the SwingUtilities invokeLater method. This method ensures that the Swing components are created and executed on the Event Dispatch Thread.

The only fields that need to be class instance fields are the fields that you use in more than one method. Defining all your fields as class fields is a bad habit that confuses readers of your code.

None of your fields need to be static.

The ActionListener is attached to your JButton. I build the combinedChars String based on your checkboxes, check to make sure at least one check box is checked, and create the password. You might want to consider adding a JSlider to your GUI somewhere to specify the length of the password.

Here's the complete runnable code.

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.GridLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.security.SecureRandom;

import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.SwingConstants;
import javax.swing.SwingUtilities;
import javax.swing.border.EmptyBorder;

public class PasswordGenerator implements ActionListener, Runnable {

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new PasswordGenerator());
    }

    private JCheckBox upperCheckBox, lowerCheckBox, numCheckBox, symbolCheckBox;

    private JTextField textGenPassword;

    @Override
    public void run() {
        JFrame frame = new JFrame("Strong Password Generator");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        frame.add(createTitlePanel(), BorderLayout.NORTH);
        frame.add(createConfigurationPanel(), BorderLayout.WEST);
        frame.add(createMainPanel(), BorderLayout.CENTER);

        frame.pack();
        frame.setLocationByPlatform(true);
        frame.setVisible(true);
    }

    private JPanel createTitlePanel() {
        JPanel titlePanel = new JPanel(new GridBagLayout());
        titlePanel.setBackground(new Color(25, 25, 25));
        titlePanel.setPreferredSize(new Dimension(100, 60));

        JLabel title = new JLabel("Strong Password Generator");
        title.setForeground(Color.WHITE);
        title.setFont(new Font("Roboto", Font.BOLD, 20));
        titlePanel.add(title);

        return titlePanel;
    }

    private JPanel createConfigurationPanel() {
        JPanel configPanel = new JPanel(new GridLayout(0, 1, 20, 10));

        JLabel configTitle = new JLabel("  Configuration Settings  ");
        configTitle.setHorizontalAlignment(SwingConstants.CENTER);
        configTitle.setAlignmentX(JLabel.CENTER);
        configTitle.setForeground(Color.BLACK);
        configTitle.setBorder(new EmptyBorder(20, 0, 0, 0));
        configPanel.add(configTitle);

        Color backgroundColor = new Color(107, 208, 255);

        // uppercase group
        JLabel configUpperLabel = new JLabel();
        configUpperLabel.setText("Uppercase Letters");
        configUpperLabel.setHorizontalAlignment(SwingConstants.CENTER);
        configPanel.add(configUpperLabel);

        upperCheckBox = new JCheckBox();
        upperCheckBox.setHorizontalAlignment(SwingConstants.CENTER);
        upperCheckBox.setBackground(backgroundColor);
        configPanel.add(upperCheckBox);

        // lowercase group
        JLabel configLowerLabel = new JLabel("Lowercase Letters");
        configLowerLabel.setHorizontalAlignment(SwingConstants.CENTER);
        configPanel.add(configLowerLabel);

        lowerCheckBox = new JCheckBox();
        lowerCheckBox.setHorizontalAlignment(SwingConstants.CENTER);
        lowerCheckBox.setBackground(backgroundColor);
        configPanel.add(lowerCheckBox);

        // num group
        JLabel configNumLabel = new JLabel("Numbers: ( e.g. 123)");
        configNumLabel.setHorizontalAlignment(SwingConstants.CENTER);
        configPanel.add(configNumLabel);

        numCheckBox = new JCheckBox();
        numCheckBox.setHorizontalAlignment(SwingConstants.CENTER);
        numCheckBox.setBackground(backgroundColor);
        configPanel.add(numCheckBox);

        // symbol group
        JLabel configSymbolLabel = new JLabel("Symbols: ( e.g. ! @ $)");
        configSymbolLabel.setHorizontalAlignment(SwingConstants.CENTER);
        configPanel.add(configSymbolLabel);

        symbolCheckBox = new JCheckBox();
        symbolCheckBox.setHorizontalAlignment(SwingConstants.CENTER);
        symbolCheckBox.setBackground(backgroundColor);
        configPanel.add(symbolCheckBox);

        return configPanel;
    }

    private JPanel createMainPanel() {
        JPanel mainPanel = new JPanel(new GridBagLayout());
        mainPanel.setBackground(new Color(255, 255, 255));

        GridBagConstraints textFieldConstraints = new GridBagConstraints();
        textFieldConstraints.gridx = 0;
        textFieldConstraints.gridy = 0;
        textFieldConstraints.insets = new Insets(5, 5, 5, 5);

        textGenPassword = new JTextField(20);
        mainPanel.add(textGenPassword, textFieldConstraints);

        GridBagConstraints buttonConstraints = new GridBagConstraints();
        buttonConstraints.gridx = 0;
        buttonConstraints.gridy = 1;
        buttonConstraints.insets = new Insets(5, 5, 5, 5);

        JButton genButton = new JButton("Generate Password");
        genButton.addActionListener(this);
        mainPanel.add(genButton, buttonConstraints);

        return mainPanel;
    }

    @Override
    public void actionPerformed(ActionEvent event) {
        String upper = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
        String lower = "abcdefghijklmnopqrstuvwxyz";
        String numbers = "0123456789";
        String symbols = "~`!@#$%^&*()_-+={[}]|\\:;\"'<,>.?/";
        String combinedChars = "";

        if (upperCheckBox.isSelected()) {
            combinedChars += upper;
        }

        if (lowerCheckBox.isSelected()) {
            combinedChars += lower;
        }

        if (numCheckBox.isSelected()) {
            combinedChars += numbers;
        }

        if (symbolCheckBox.isSelected()) {
            combinedChars += symbols;
        }

        if (combinedChars.isEmpty()) {
            return;
        }

        SecureRandom random = new SecureRandom();
        StringBuilder password = new StringBuilder(16);

        for (int i = 0; i < 16; i++) {
            int num = random.nextInt(combinedChars.length());
            password.append(combinedChars.charAt(num));
        }

        textGenPassword.setText(password.toString());
    }

}

Upvotes: 0

Farha Mansuri
Farha Mansuri

Reputation: 151

You need to register your genButton's action listener.

genButton.addActionListener(new java.awt.event.ActionListener() {
     public void actionPerformed(java.awt.event.ActionEvent evt) {
            genButtonActionPerformed(evt);
     }
}); 

And then make your button listener active

private void genButtonActionPerformed(java.awt.event.ActionEvent evt) {
      ....
}

Upvotes: 0

Related Questions