I made this to help me practice User Interface. For some reason the password doesn't display on the screen when Generate! is pressed. There are no program errors either. As you can see I have a JLabel for the password.
Code:
package components;
import java.io.*;
import java.util.Scanner;
import java.util.Random;
import javax.swing.*;
import javax.*;
import java.awt.*;
import java.awt.event.*;
public class PassGenButton extends JPanel implements ActionListener{
protected JButton generate;
protected JLabel passLabel;
public String password = null;
public PassGenButton()
{
JButton generate = new JButton("Generate!");
JLabel passLabel = new JLabel(password, JLabel.CENTER);
passLabel.setFont(new Font("Serif", Font.PLAIN, 36));
passLabel.setBorder(BorderFactory.createTitledBorder("Password"));
setLayout(new BorderLayout());
generate.addActionListener(this);
add(generate, BorderLayout.SOUTH);
add(passLabel, BorderLayout.CENTER);
}
public void actionPerformed(ActionEvent e)
{
GetPassword();
}
private static void createAndShowGUI()
{
JFrame frame = new JFrame("Password Generator");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
PassGenButton contentPane = new PassGenButton();
frame.setContentPane(contentPane);
frame.setSize(400, 200);
frame.setLocation(600, 300);
frame.setVisible(true);
}
public static void main(String[] args)
{
javax.swing.SwingUtilities.invokeLater(new Runnable(){
public void run(){
createAndShowGUI();
}
});
}
public void GetPassword()
{
password = null;
String[] nouns = new String[2432];
File file = new File("C:\\Temp\\nounlist.txt");
String chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
char[] characters = chars.toCharArray();
try
{
nouns = ReadTextFile(file);
}
catch (FileNotFoundException f)
{
f.getMessage();
System.exit(1);
}
ShowPassword(nouns, characters);
}
public final String[] ReadTextFile(File aFile) throws FileNotFoundException
{
String[] strings = new String[2432];
int counter = 0;
Scanner scanner = new Scanner(new FileReader(aFile));
try
{
while (scanner.hasNextLine())
{
strings[counter] = scanner.nextLine();
counter++;
}
}
finally
{
scanner.close();
}
return strings;
}
public void ShowPassword(String[] nouns, char[] characters)
{
String password;
Random generator = new Random();
int chosenNoun = 0;
int chosenChar = 0;
int int1 = 0;
int int2 = 0;
chosenNoun = generator.nextInt(2432);
chosenChar = generator.nextInt(26);
int1 = generator.nextInt(10);
int2 = generator.nextInt(10);
password = nouns[chosenNoun] + characters[chosenChar] + Integer.toString(int1) + Integer.toString(int2);
}
}