I'm attempting to make a code that will use JFileChooser and JPassword for getting input of encrypted code or code to be encrypted.
Here is the code to be encrypted "Be sure to drink your Ovaltine!" to be saved in a .rtf or a .txt file. The key is "annie". The output should be
"Fv '$zi (# pzm"| (wy& `%ip(zzm%".
I have two different class files under the project "Password". One class is called "File Opener". It calls the class "Password1".
Here is Password1.java.
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.Arrays;
/* PasswordDemo.java requires no other files. */
public class Password1 extends JPanel
implements ActionListener {
private String key;
private static String OK = "ok";
private JFrame controllingFrame; //needed for dialogs
private JPasswordField passwordField;
public Password1(JFrame f) {
//Use the default FlowLayout.
controllingFrame = f;
//Create everything.
passwordField = new JPasswordField(10);
passwordField.setActionCommand(OK);
passwordField.addActionListener(this);
JLabel label = new JLabel("Enter the key: ");
label.setLabelFor(passwordField);
JComponent buttonPane = createButtonPanel();
//Lay out everything.
JPanel textPane = new JPanel(new FlowLayout(FlowLayout.TRAILING));
textPane.add(label);
textPane.add(passwordField);
add(textPane);
add(buttonPane);
}
protected JComponent createButtonPanel() {
JPanel p = new JPanel(new GridLayout(0,1));
JButton okButton = new JButton("OK");
okButton.setActionCommand(OK);
okButton.addActionListener(this);
p.add(okButton);
return p;
}
public void actionPerformed(ActionEvent e) {
String cmd = e.getActionCommand();
controllingFrame.dispose();
if (OK.equals(cmd)) { //Process the password.
char[] input = passwordField.getPassword();
key = new String(input);
//Zero out the possible password, for security.
Arrays.fill(input,'0');
passwordField.selectAll();
resetFocus();
} else {
System.out.println("Please enter a key.");
}
}
public String getKey(){
return key;
}
//Must be called from the event dispatch thread.
protected void resetFocus() {
passwordField.requestFocusInWindow();
}
public static void createAndShowGUI() {
//Create and set up the window.
JFrame frame = new JFrame("Key");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//Create and set up the content pane.
final Password1 newContentPane = new Password1(frame);
newContentPane.setOpaque(true); //content panes must be opaque
frame.setContentPane(newContentPane);
//Make sure the focus goes to the right component
//whenever the frame is initially given the focus.
frame.addWindowListener(new WindowAdapter() {
public void windowActivated(WindowEvent e) {
newContentPane.resetFocus();
}
});
//Display the window.
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
//Schedule a job for the event dispatch thread:
//creating and showing this application's GUI.
SwingUtilities.invokeLater(new Runnable() {
public void run() {
//Turn off metal's use of bold fonts
UIManager.put("swing.boldMetal", Boolean.FALSE);
createAndShowGUI();
}
});
}
}
And here is the FileOpener.java.
import javax.swing.*;
import java.io.*;
import javax.swing.filechooser.*;
import java.awt.event.*;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.util.Scanner;
public class FileOpener extends JPanel implements ActionListener {
static private final String newline = "\n";
private Password1 p1;
JButton decodeButton, encodeButton;
JFileChooser fc;
JTextArea log;
Scanner in = new Scanner(System.in);
JFrame frame;
File file;
int count;
public FileOpener(){
// create and set up the window.
frame = new JFrame("Open Your File");
// make the program close when the window closes
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// create the box layout
frame.getContentPane( ).setLayout(new BoxLayout(frame.getContentPane( ), BoxLayout.Y_AXIS));
//label prompting user for input
JLabel label1 = new JLabel ("Would you like to encode or decode your file?", JLabel.CENTER);
frame.getContentPane().add(label1);
//create a filer chooser
fc = new JFileChooser();
// add a button object
decodeButton = new JButton("Decode");
decodeButton.addActionListener(this);
frame.getContentPane( ).add(decodeButton);
encodeButton = new JButton("Encode");
encodeButton.addActionListener(this);
frame.getContentPane( ).add(encodeButton);
// display the window.
frame.pack( );
frame.setVisible(true);
}
public void actionPerformed(ActionEvent e) {
//Handle open button action.
if (e.getSource() == encodeButton) {
frame.dispose();
int returnVal = fc.showOpenDialog(FileOpener.this);
if (returnVal == JFileChooser.APPROVE_OPTION ) {
try {
file = fc.getSelectedFile();
p1 = new Password1(frame);
p1.createAndShowGUI();
//get length of key
String key = p1.getKey();
int length3 = key.length();
count = 0;
int keyAsciiValues[] = new int[length3];
String name1 ="";
//get ascii value of each letter in key
for (int k=0; k<length3; k++){
char a = key.charAt(k);
int ascii1 = (int)a;
//put ascii value of letter in key to array
keyAsciiValues[k]= ascii1;
}
FileInputStream file2= new FileInputStream(file);
//create a scanner for it
in = new Scanner(file2);
//read in message
String name;
name = in.nextLine();
for (int k=0; k<length3; k++){
char a = key.charAt(k);
int ascii1 = (int)a;
//put ascii value of letter in key to array
keyAsciiValues[k]= ascii1;
}
//measure length of code message array
int length1 = name.length();
//measures length of strings in code message array
for(int j=0;j<length1;j++){
char c = name.charAt(j);
int ascii = (int)c;
ascii += keyAsciiValues[count];
if(c != ' '){
count++;
}
if(count>length3-1){
count = 0;
}
while(ascii>126){
ascii-= 93;
}
char b=(char)ascii;
if(c == ' '){
b = ' ';
}
name1 += b;
}
System.out.println(name1);
} catch (FileNotFoundException k){
//the file was not found!
System.out.println("File could not be opened!");
}
}
//Handle save button action.
} else if (e.getSource() == decodeButton) {
frame.dispose();
int returnVal = fc.showOpenDialog(FileOpener.this);
if (returnVal == JFileChooser.APPROVE_OPTION) {
try {
file = fc.getSelectedFile();
p1 = new Password1(frame);
p1.createAndShowGUI();
//open the file
//get length of key
String key = p1.getKey();
int length3 = key.length();
count = 0;
int keyAsciiValues[] = new int[length3];
String name1 ="";
//get ascii value of each letter in key
for (int k=0; k<length3; k++){
char a = key.charAt(k);
int ascii1 = (int)a;
//put ascii value of letter in key to array
keyAsciiValues[k]= ascii1;
}
//create a scanner for it
in = new Scanner(file);
//read in message
String name;
name = in.nextLine();
for (int k=0; k<length3; k++){
char a = key.charAt(k);
int ascii1 = (int)a;
//put ascii value of letter in key to array
keyAsciiValues[k]= ascii1;
}
//measure length of code message array
int length1 = name.length();
//measures length of strings in code message array
for(int j=0;j<length1;j++){
char c = name.charAt(j);
int ascii = (int)c;
ascii -= keyAsciiValues[count];
if(c != ' '){
count++;
}
if(count>length3-1){
count = 0;
}
while(ascii<33){
ascii+= 93;
}
char b=(char)ascii;
if(c == ' '){
b = ' ';
}
name1 += b;
}
System.out.print(name1);
} catch (FileNotFoundException k){
//the file was not found!
System.out.println("File could not be opened!");
}
}
in.close();
log.append("Opening: " + file.getName() + "." + newline);
}
}
public static void main(String args[]) {
//Schedule a job for the event dispatch thread:
//creating and showing this application's GUI.
FileOpener f = new FileOpener();
}
}
It was working fine before I added the JFileChooser and the Password stuff aka there shouldn't be anything wrong with the actual ciphering part of the code.
It's giving me a java.lang.NullPointerException at line at line 70 in FileOpener.
int length3 = key.length();
Thanks!
In the createAndShowGUI() method, you show your Password1 instance in a JFrame, not a modal JDialog. Therefore, this display instruction is non-blocking, i.e. it does not stop code execution, nor does it wait until you click a button that closes the window.
As a result, you retrieve the Password1 instance key before its actionPerformed() method can execute and initialize the key attribute, hence the key is still null and you get a NullPointerException when you invoke any method on it.
My suggestion is using a modal JDialog in createAndShowGUI() to manage your Password1 interface (initialization using a JPanel is much like what you are already doing with a JFrame). This way, when you invoke createAndShowGUI(), the FileOpener.actionPerformed() method execution will block until you are done with the Password1 dialog, hence you will make sure key is properly initialized before you retrieve and use it in FileOpener.actionPerformed().
One last thing: be careful with frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);! Using it on your main window is OK but using it on any secondary window will make the whole program shut down completely as soon as you close it. But anyway, the JDialog version of setDefaultCloseOperation() doesn't accept EXIT_ON_CLOSE as a valid argument, so you will remain using it only on your main FileOpener window, which is fine.
Related
I am currently working on an address book program, and got it to work before...
but for some reason, I cannot get the GUI window to open up on DrJava
I have tried compiling it with no errors.. I did comment out the exceptions because it was giving me problems, so I will fix that error, but that is for the FileIO anyway
It is so weird how I cannot get the GUI to popup, I am really not sure why it isn't working...
//imports
import javax.swing.*;
import java.io.PrintWriter;
import java.io.File;
import java.io.*;
import java.util.Scanner;
import java.awt.*;
import java.awt.event.*; //Adding the event since we will now be using an action listener
import java.io.FileNotFoundException;
public class AddressbookFinal extends JFrame implements ActionListener//actionlistener enables us to set actions to buttons
{
// Create some Panels
JPanel pan1 = new JPanel ();//panel 1
JPanel pan2 = new JPanel ();//panel 2
File writeFile = new java.io.File ("Address book.txt"); //create the file to write to
File readFile = new java.io.File ("Address book.txt");//read the file
//global variables
static final int MAX = 100;//lenght of the arrays
String lastname[] = new String [MAX];//holds last names
String names[] = new String [MAX];//holds first names
String e_mail[] = new String [MAX];// holds emails
String address[] = new String [MAX];//holds addresses
String phone[] = new String [MAX];// holds phone numbers
int total;//the counter that keeps track of our position
// Create some GUI components
JLabel lastnameLabel = new JLabel ("Last name", JLabel.LEFT);
JTextField lastnameField = new JTextField (40);
JLabel nameLabel = new JLabel ("First Name ", JLabel.LEFT);
JTextField nameField = new JTextField (40);
JLabel AddressLabel = new JLabel ("Address", JLabel.LEFT);
JTextField AddressField = new JTextField (40);
JLabel PhoneLabel = new JLabel ("Phone", JLabel.LEFT);
JTextField PhoneField = new JTextField (40);
JLabel EmailLabel = new JLabel ("Email", JLabel.LEFT);
JTextField EmailField = new JTextField (40);
JButton deleteButton = new JButton ("Delete");
JButton saveButton = new JButton ("Save");
JButton modifyButton = new JButton ("Update");
JButton previousButton = new JButton ("<<");
JButton searchButton = new JButton ("Search");
JButton nextButton = new JButton (">>");
JButton readButton = new JButton ("Read");
JButton writeButton = new JButton ("Write");
JButton clearButton = new JButton ("Clear");
JLabel instructionsLabel = new JLabel ("Enter your name", JLabel.LEFT);
JButton exitButton = new JButton ("Exit");
// CONSTRUCTOR - Setup your GUI here
public void HamzaTest () throws IOException
{
total = 0;
//all fields to empty
for (int i = total ; i < names.length ; i++)
{
lastname [i] = "";
names [i] = "";
e_mail [i] = "";
address [i] = "";
phone [i] = "";
}
setTitle ("Hello World!"); // Create a window with a title
setSize (640, 480); // set the window size
// Create some Layouts
GridLayout layout1 = new GridLayout (4, 1);
GridLayout layout2 = new GridLayout (5, 1);
// Set the frame and both panel layouts
setLayout (layout1); // Setting layout for the whole frame
pan1.setLayout (layout2); // Layout for Pan1
pan2.setLayout (layout1); // Layout for Pan2
saveButton.addActionListener (this); // Add an action listener to the buttons
deleteButton.addActionListener (this);
modifyButton.addActionListener (this);
previousButton.addActionListener (this);
searchButton.addActionListener (this);
nextButton.addActionListener (this);
clearButton.addActionListener (this);
exitButton.addActionListener (this);
readButton.addActionListener (this);
writeButton.addActionListener (this);
// this allows the program to know if
// the button was pressed
// Add all the components to the panels
pan1.add (lastnameLabel);
pan1.add (lastnameField);
pan1.add (nameLabel);
pan1.add (nameField);
pan1.add (AddressLabel);
pan1.add (AddressField);
pan1.add (PhoneLabel);
pan1.add (PhoneField);
pan1.add (EmailLabel);
pan1.add (EmailField);
//panel 2 is for buttons
pan2.add (saveButton);
pan2.add (deleteButton);
pan2.add (modifyButton);
pan2.add (previousButton);
pan2.add (searchButton);
pan2.add (nextButton);
pan2.add (clearButton);
pan2.add (readButton);
pan2.add (writeButton);
pan2.add (exitButton);
pan2.add (instructionsLabel);
// add the panels to the frame and display the window
add (pan1);
add (pan2);
setVisible (true);//set the GUI window to visible
}
// ACTION LISTENER - This method runs when an event occurs
// Code in here only runs when a user interacts with a component
// that has an action listener attached to it
public void actionPerformed (ActionEvent event) /* throws IOException */
{
String command = event.getActionCommand (); // find out the name of the
// component
// that was used
if (command.equals ("Save"))
{ // if the save button was pressed
while (lastname [total] != "")//find the current position and save in the nearest
total++;
System.out.println ("save button pressed"); // display message inconsole(for testing)
System.out.println ("name:" + nameField.getText ()); // get the info located in the field component
instructionsLabel.setText ("Thank you " + nameField.getText ()); // change the label message to 'thank you'
//get the String values from the fields and set them to our arrays
lastname [total] = lastnameField.getText ();
names [total] = nameField.getText ();
e_mail [total] = EmailField.getText ();
address [total] = AddressField.getText ();
phone [total] = PhoneField.getText ();
//move to the next position
total++;
//sort the lists
Sort (lastname, names, e_mail, address, phone, total);
}
else if (command.equals ("Delete"))//if delete is pressed
{
System.out.println ("delete button pressed");
System.out.println (nameField.getText () + "was deleted");
//set the current position to empty
lastname [total] = ("");
names [total] = ("");
e_mail [total] = ("");
address [total] = ("");
phone [total] = ("");
instructionsLabel.setText ("Deleted");
}
else if (command.equals ("Update"))//modify button was pressed
{
//change a field without changing the current position meaning that it will overwrite what you already have
System.out.println (lastnameField.getText () + "was modified");
lastname [total] = lastnameField.getText ();
names [total] = nameField.getText ();
e_mail [total] = EmailField.getText ();
address [total] = AddressField.getText ();
phone [total] = PhoneField.getText ();
instructionsLabel.setText (lastnameField.getText () + " was modified");
}
else if (command.equals ("<<"))//previous button is pressed
{
if (total > 0)//go back if it's not zero
total--;
System.out.println ("name: " + names [total]);
//set the text field on the GUI to the current data
lastnameField.setText (lastname [total]);
nameField.setText (names [total]);
EmailField.setText (e_mail [total]);
AddressField.setText (address [total]);
PhoneField.setText (phone [total]);
instructionsLabel.setText (names [total]);
}
else if (command.equals ("Search"))//search for a specific name(last name)
{
int location = search (lastname, lastnameField.getText (), 0, 99);
if (location >= 0)//if the name is found the mehtod will return a number larger than zero which is the location
{
lastnameField.setText (lastname [location]);
nameField.setText (names [location]);
EmailField.setText (e_mail [location]);
PhoneField.setText (phone [location]);
AddressField.setText (address [location]);
instructionsLabel.setText ("found");
System.out.println (lastname [location]);
total = location;
}
else//the name wasn't found
instructionsLabel.setText ("not found");
}
else if (command.equals (">>"))//next button
{
if (total < 100)//move up if the position is smaller than a 100
total++;
System.out.println ("name" + names [total]);
//set the text fields to the current data
lastnameField.setText (lastname [total]);
nameField.setText (names [total]);
EmailField.setText (e_mail [total]);
AddressField.setText (address [total]);
PhoneField.setText (phone [total]);
instructionsLabel.setText (names [total]);
}
else if (command.equals ("Clear"))//clear the fields button
{
instructionsLabel.setText ("cleared");
lastnameField.setText ("");
nameField.setText ("");
EmailField.setText ("");
AddressField.setText ("");
PhoneField.setText ("");
}
else if (command.equals ("Read"))//read file that already exists
{
System.out.println ("At read");//reading
Scanner input = null;
try
{
input = new Scanner (readFile);//the file name was declared previously
while (input.hasNext ())//if there are more lines to go
{
lastname [total] = input.nextLine ();
names [total] = input.nextLine ();
e_mail [total] = input.nextLine ();
address [total] = input.nextLine ();
phone [total] = input.nextLine ();
total++;
System.out.println (total);
}
input.close ();//close the file stream
}
catch (FileNotFoundException e)//exception
{
System.out.println ("File not found");
}
//catch (IOException e)//exception
{
System.out.println ("Error writing to file");
}
//finally//makes sure the input stream is being closed
{
if (input != null)
input.close ();
}
}
else if (command.equals ("Write"))//writes to text files to save the data
{
System.out.println ("At write");
PrintWriter output = null;
try
{
output = new PrintWriter (writeFile);//the file name was declared previously
for (int i = 0 ; i < total ; ++i)//writes data to the file based on the current position
{
output.println (lastname [i]);
output.println (names [i]);
output.println (e_mail [i]);
output.println (address [i]);
output.println (phone [i]);
output.println (""); //make a space in between people
}
}
catch (IOException e)//exception
{
instructionsLabel.setText ("File cannot be read");
}
finally//makes sure the files is being closed so it would save
{
if (output != null)
output.close ();
}
instructionsLabel.setText ("Info has been saved to a file");
}
else if (command.equals ("Exit"))//exit the GUI
{
setVisible (false);//hide the GUI
}
}
public static int Search (String lastnames[], String searchString, int min, int max)//search method
{
if (max < min)
return -1;
else
{
int mid = (max + min) / 2;
if (searchString.compareToIgnoreCase (lastnames [mid]) < 0) //is below the midpoint
return Search (lastnames, searchString, min, mid - 1);
else if (searchString.compareToIgnoreCase (lastnames [mid]) > 0) //is above the midpoint
return Search (lastnames, searchString, mid + 1, max);
else
return mid; //of the searched item has been found
}
}
public static int search (String[] names, String name, int min, int max)//temporary search method
{
for (int i = 0 ; i < MAX ; i++)
{
if (names [i].compareTo (name) == 0)
return i;
}
return -1;
}
public static void Sort (String lastname[], String names[], String e_mail[], String address[], String phone[], int total)//insertion sort
{
String tempLS; //temporary variable for last names
String tempN; //temporary variable for first names
String tempA; //temporary variable for addresses
String tempP; //temporary variable for phones
String tempE; //temporary variable for emails
int j;
for (int i = 1 ; i < total ; i++) // going through list --> start i at 1
// to make one less comparison
{
tempLS = lastname [i]; // setting temp at start of loop
tempN = names [i];
tempA = address [i];
tempP = phone [i];
tempE = e_mail [i];
j = i - 1; // to check names before
while (j >= 0 && tempLS.compareToIgnoreCase (lastname [j]) < 0) // checks to see if
// previous names
// are greater ->
// then makes swap
{
lastname [j + 1] = lastname [j]; // if previous name is greater, moves
// greater value up the array by 1
names [j + 1] = names [j];
e_mail [j + 1] = e_mail [j];
address [j + 1] = address [j];
phone [j + 1] = phone [j];
j--; // compares to previous numbers
}
lastname [j + 1] = tempLS; // swap //+1 to make up for j=-1
names [j + 1] = tempN;
e_mail [j + 1] = tempE;
address [j + 1] = tempA;
phone [j + 1] = tempP;
}
}
// Main method
public static void main (String[] args) throws IOException
{
AddressbookFinal frame1 = new AddressbookFinal (); // Start the GUI
}
}
You have two choices, you either change
// CONSTRUCTOR - Setup your GUI here
public void HamzaTest() throws IOException {
to be a proper constructor for the class,
public AddressbookFinal() throws IOException {
OR you call the HamzaTest method from your main method
// Main method
public static void main(String[] args) throws IOException {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
}
AddressbookFinal frame1 = new AddressbookFinal(); // Start the GUI
frame1.HamzaTest();
} catch (IOException ex) {
ex.printStackTrace();
}
}
});
}
You should have a look at Providing Constructors for Your Classes for more details.
For the reasons for EventQueue.invokeLater, you should have a look at Concurrency in Swing
I am trying to create a java applet that uses text fields to add strings to a linked list. I can not get the search button to work. I am trying to get the string specified by the user in the text field and then search the list and print how many times the word has been found if any.
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.LinkedList;
import java.util.ListIterator;
/**
* Created by joshuaogunnote on 31/10/2015.
*/
public class Applet2 extends JApplet {
private String text;
private int text1;
JTextField value1, value2;
LinkedList<String> list = new LinkedList<String>();
public JLabel jLabel;
public int count = 0;
I have created this search_count variable to count up how many times the word has been found.
public int search_count = 0;
public void init() {
JLabel prompt = new JLabel("Please enter a word");
JLabel prompt1 = new JLabel("Please enter a certain letter");
value1 = new JTextField(10);
value2 = new JTextField(10);
JPanel textPanel = new JPanel();
textPanel.add(prompt);
textPanel.add(value1);
add(textPanel, BorderLayout.NORTH);
textPanel.add(prompt1);
textPanel.add(value2);
JPanel centrePanel = new JPanel();
text = "";
jLabel = new JLabel(text);
centrePanel.add(jLabel);
add(centrePanel, BorderLayout.CENTER);
JButton but = new JButton("Add word");
JButton but1 = new JButton("Clear");
JButton but2 = new JButton("Remove first occurrence");
JButton but3 = new JButton("Remove all occurrences");
JButton but4 = new JButton("Display all words begging with certain letter");
JButton but5 = new JButton("Search");
JPanel butPanel = new JPanel();
butPanel.add(but);
butPanel.add(but1);
butPanel.add(but5);
butPanel.add(but2);
butPanel.add(but3);
butPanel.add(but4);
add(butPanel, BorderLayout.SOUTH);
but.addActionListener(new ButtonHandler(this));
but1.addActionListener(new ButtonHandler1(this));
but5.addActionListener(new ButtonHandler2(this));
}
class ButtonHandler implements ActionListener {
private Applet2 theApplet;
public ButtonHandler(Applet2 app) {
theApplet = app;
}
public void actionPerformed(ActionEvent e) {
text = theApplet.value1.getText();
try {
text1 = Integer.parseInt(text);
jLabel.setText("ERROR - The string " + "'" + text1 + "'" + " is not a valid word");
} catch (NumberFormatException e1) {
if (text.length() != 0) {
jLabel.setText("Word " + "'" + text + "'" + " has been added to the list");
count = count + 1;
} else {
jLabel.setText("ERROR - Please enter a word");
}
}
}
}
class ButtonHandler1 implements ActionListener {
private Applet2 theApplet;
public ButtonHandler1(Applet2 app) {
theApplet = app;
}
public void actionPerformed(ActionEvent e) {
list.clear();
jLabel.setText("List has been cleared");
count = 0;
}
}
class ButtonHandler2 implements ActionListener {
private Applet2 theApplet;
public ButtonHandler2(Applet2 app) {
theApplet = app;
}
public void actionPerformed(ActionEvent e) {
String text = theApplet.value1.getText();
Here I am trying to use a for loop to iterate through all the strings in the list and increment search_count if a match has been found. It does not however produce the correct answer. I am also trying to produce an ERROR message when the user tries to search for a word that is not in the list. How do I get the search_count variable and how do I get the ERROR message to show at the correct time?
for (int i = 0; i < list.size(); i++) {
if(text.equals(list.get(i))){
search_count = search_count + 1;
} else {
jLabel.setText("ERROR - word is not in the list")
}
jLabel.setText("Word " + "'" + text + "'" + " was found " + search_count + " time(s) in the list");
if (text.length() == 0) {
jLabel.setText("Please enter a word - The total number of words in the list are: " + count);
}
}
}
}
It seems you did not declare count as a variable before you used it in the loop. If the output is not what you want / expect, the condition of the loop gives you something else then what you think it does.
int count = 0;
i've been stuck on getting one of my JTextArea's to display an array of Strings that represent letters in a word in a hangman game. Once the user guesses a letter, (assuming it's right), it should reflect into the array. Instead, it seems to be only adding the letter that was guessed, and not the blanks or the rest of the array. I want to set the guessed letter equal to the correct index in the array and then have it shown on the screen. Here is my code:
import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Random;
#SuppressWarnings("serial")
public class GuiClass extends JFrame {
char guess = ' ';
int numGuesses = 0;
char[] letterGuessedAgainst = null;
String wordInPlay = " ";
String[] hangmanScores = null;
ArrayList<Character> wrongGuesses = null;
boolean isGuessSuccessfull = false;
private Container contents;
JRadioButton rbEasy;
JRadioButton rbHard;
ButtonGroup difficultyGroup;
JTextField txtfldWord;
JTextArea txtareaWord;
JLabel difficultyPrompt;
JLabel userDifficulty;
JButton btnStartGame;
JButton btnGuessSubmit;
JButton btnWordGuessSubmit;
JPanel topPanel;
JPanel midPanel;
JLabel topLabel;
JPanel guessPanel;
JPanel letterPanel;
JLabel word;
JTextArea txtareaNumGuesses;
JTextField txtfldGuess;
JTextField txtfldWordGuess;
JTextArea txtareaguessedLetters;
JTextArea txtareaLettersLeft;
public GuiClass(){
super("Hangman GUI");
contents = getContentPane();
//create a new panel & set layout
midPanel = new JPanel();
midPanel.setLayout(new GridLayout(3,3));
//layout manager
topLabel = new JLabel("Welcome to Hangman!");
contents.setLayout(new FlowLayout());
//create new ButtonHandlers
ButtonHandler buttonHandler = new ButtonHandler();
ButtonHandler2 btnHndlrNewGame = new ButtonHandler2();
//create difficulty buttons/labels & add ActionListeners
difficultyPrompt = new JLabel("First, Choose A Difficulty:");
rbEasy = new JRadioButton("Easy");
rbHard = new JRadioButton("Hard");
userDifficulty = new JLabel("Game Difficulty: ");
difficultyGroup = new ButtonGroup();
difficultyGroup.add(rbEasy);
difficultyGroup.add(rbHard);
rbEasy.addItemListener(buttonHandler);
rbHard.addItemListener(buttonHandler);
midPanel.add(topLabel);
midPanel.add(difficultyPrompt);
midPanel.add(rbEasy);
midPanel.add(rbHard);
midPanel.add(userDifficulty);
topPanel = new JPanel();
JLabel btnStartNewGame = new JLabel("Next, Start a new game!");
btnStartGame = new JButton("Start A New Game");
btnStartGame.addActionListener(btnHndlrNewGame);
topPanel.add(btnStartNewGame);
topPanel.add(btnStartGame);
guessPanel = new JPanel();
JLabel lblGuess = new JLabel("Guess: ");
JLabel lblWordGuess = new JLabel("Word Guess: ");
btnGuessSubmit = new JButton("Submit");
btnGuessSubmit.addActionListener(btnHndlrNewGame);
btnWordGuessSubmit = new JButton("Submit");
btnGuessSubmit.addActionListener(btnHndlrNewGame);
txtfldGuess = new JTextField(10);
txtfldWordGuess = new JTextField(10);
guessPanel.add(lblGuess);
guessPanel.add(txtfldGuess);
guessPanel.add(btnGuessSubmit);
guessPanel.add(lblWordGuess);
guessPanel.add(txtfldWordGuess);
guessPanel.add(btnWordGuessSubmit);
letterPanel = new JPanel();
JLabel lblGuessedLetters = new JLabel("Guessed Letters:");
JLabel lblLettersInWord = new JLabel("Letters Left:");
JLabel lblNumGuesses = new JLabel("Guess Number: ");
txtareaNumGuesses = new JTextArea(5,5);
txtareaNumGuesses.setEditable(false);
txtareaguessedLetters = new JTextArea(5,15);
txtareaguessedLetters.setEditable(false);
txtareaLettersLeft = new JTextArea(5,15);
txtareaLettersLeft.setEditable(false);
letterPanel.add(lblGuessedLetters);
letterPanel.add(txtareaguessedLetters);
letterPanel.add(lblLettersInWord);
letterPanel.add(txtareaLettersLeft);
letterPanel.add(lblNumGuesses);
letterPanel.add(txtareaNumGuesses);
JPanel wordPanel = new JPanel();
word = new JLabel("Word is: ");
//txtfldWord = new JTextField(10);
txtareaWord = new JTextArea(20,20);
//txtfldWord.setEditable(false);
txtareaWord.setEditable(false);
wordPanel.add(word);
//wordPanel.add(txtfldWord);
wordPanel.add(txtareaWord);
//add contents of panels to the container
contents.add(midPanel);
contents.add(topPanel);
contents.add(guessPanel);
contents.add(letterPanel);
contents.add(wordPanel);
setSize(800,600);
setVisible(true);
}//end constructor
private class ButtonHandler implements ItemListener{
public void itemStateChanged(ItemEvent ie){
if (ie.getSource()==rbEasy){
userDifficulty.setText("Game Difficulty: Easy");
}//end if
if (ie.getSource()==rbHard){
userDifficulty.setText("Game Difficulty: Hard");
}//end if
}//end method
}//end ButtonHandler inner class
private class ButtonHandler2 implements ActionListener{
public void actionPerformed(ActionEvent ae){
if (ae.getSource()==btnStartGame){
if (rbEasy.isSelected()){
ArrayList<String> easyHmWords = new ArrayList<String>();
String filename = "easyhangmanwords.txt";
BufferedReader infile = null;
try {
infile = new BufferedReader(new FileReader(filename));
}//end try
catch (FileNotFoundException e) {
e.getMessage();
}//end catch
String re = "";
try {
while ((re=infile.readLine())!=null){ // reading one line
easyHmWords.add(re);
}//end while
System.out.println("words in file: "+easyHmWords);
}//end try
catch (IOException e) {
e.getMessage();
}//end while
try {
infile.close();
}//end try
catch (IOException e) {
e.getMessage();
}//end catch
wordInPlay = "";
int randomNumber = 0;
Random rand = new Random();
int maxRandomNumber = 0;
word.setText("Word is: Set");
//System.out.println("Okay, the word is set!");
maxRandomNumber = easyHmWords.size();
System.out.println("Size of arraylist: "+easyHmWords.size());
randomNumber = rand.nextInt(maxRandomNumber);
System.out.println("random num: "+randomNumber);
wordInPlay = easyHmWords.get(randomNumber);
System.out.println("word in play: "+wordInPlay);
//figures out how many letters the word has
int lettersInWord = wordInPlay.length();
System.out.println("Letters in word: "+lettersInWord);
//creates an array of hangman scores which is the size of the letters in the word
hangmanScores = new String[lettersInWord];
//for loop to iterate through the array and assign "_" to the spaces
for (int i = 0; i < hangmanScores.length; i++) {
hangmanScores[i] = " _ ";
}//end for
for (int i = 0; i < hangmanScores.length; i++){
//txtareaWord.setText(hangmanScores[i]);
//txtfldWord.append(hangmanScores[i]);
txtareaWord.append((hangmanScores[i]));
}//end for
}//end if
}//end if
if(btnGuessSubmit == ae.getSource()){ //getting problems in this if statement
guess = txtfldGuess.getText().charAt(0);
letterGuessedAgainst = wordInPlay.toCharArray();
for (int i = 0; i < letterGuessedAgainst.length; i++) {//goes through the letters of the word in play
***if(letterGuessedAgainst[i]==guess){//if a letter matches up,
hangmanScores[i] = Character.toString(guess);
isGuessSuccessfull = true;
}//end if
}//end for
for (int k =0; k < hangmanScores.length; k++){//displays the ______ in the text area
txtareaWord.setText((hangmanScores[k]));***
System.out.print(hangmanScores[k]);//testing purposes
}//end for
numGuesses++;
txtareaNumGuesses.setText(" "+numGuesses);
}//end for
if(isGuessSuccessfull = false){
wrongGuesses.add(guess);
txtareaguessedLetters.append(wrongGuesses+"");
}//end if
}//end method
}//end private inner class
public static void main (String[] args){
GuiClass estGUI = new GuiClass();
estGUI.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}//end main method
}//end class
this is the part of the code that doesn't display the correct parts of the array:
***if(letterGuessedAgainst[i]==guess){//if a letter matches up,
hangmanScores[i] = Character.toString(guess);
isGuessSuccessfull = true;
}//end if
}//end for
for (int k =0; k < hangmanScores.length; k++){
txtareaWord.setText((hangmanScores[k]));***
Basically, you are calling setText every time you want to add a new character to the JTextArea in question, this is, first, clearing any existing text and then adding the new String, which, in this case, is the last thing you entered.
There are a few ways you could fix this, but because you want to remove the existing text first and then replace it, it's probably better to build a buffer of what you want and apply it all in a single step...
StringBuilder sb = new StringBuilder(hangmanScores.length);
for (int k = 0; k < hangmanScores.length; k++) {//displays the ______ in the text area
sb.append(hangmanScores[k]);
System.out.print(hangmanScores[k]);//testing purposes
}//end for
txtareaWord.setText(sb.toString());
You also seem to have attached multiple ActionListeners to your button, as each time I clicked it, it counted for two guesses...
I need help tweaking my code. I need to write a program that outputs the count of individual ascii characters in a txt file that the user uploads, but I'm having a lot of problems trying to get the array that I count into the GUI portion of the program that "draws" the data on the screen.
I have the output looking how I want, but I can't figure out how to get the character count up there
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.io.FileReader; // both needed
import java.io.BufferedReader;
import java.io.IOException;
public class textreader extends Frame implements ActionListener
{
String dataFilePath = null;
String dataFileName = null;
int[] counter = new int[256];
String command = "";
public static void main(String[] args)
{
Frame frame = new textreader();
frame.setResizable(true);
frame.setSize(1000,850);
frame.setVisible(true);
}
public textreader()
{
setTitle("Text File Processing");
// Menu Creation
MenuBar mn = new MenuBar();
setMenuBar(mn);
// Create "File" and add it
Menu fileMenu = new Menu("File");
mn.add(fileMenu);
// Create Menu Items, Add action Listener, Add to "File" Menu Group
// Open file
MenuItem miOpen = new MenuItem("Open");
miOpen.addActionListener(this);
fileMenu.add(miOpen);
// Process file
MenuItem miProcess = new MenuItem("Process");
miProcess.addActionListener(this);
fileMenu.add(miProcess);
// Exit program
MenuItem miExit = new MenuItem("Exit");
miExit.addActionListener(this);
fileMenu.add(miExit);
// To Terminate
WindowListener d = new WindowAdapter()
{
public void windowClosing(WindowEvent ev)
{
System.exit(0);
}
public void windowActivated(WindowEvent ev)
{
repaint();
}
public void windowStateChanged(WindowEvent ev)
{
repaint();
}
};
ComponentListener k = new ComponentAdapter()
{
public void componentResized(ComponentEvent e)
{
repaint();
}
};
// listener registry
this.addWindowListener(d);
this.addComponentListener(k);
}
public void actionPerformed (ActionEvent ev)
{
// which command was issued?
command = ev.getActionCommand();
// act
if("Open".equals(command))
{
dataFilePath = null;
dataFileName = null;
JFileChooser chooser = new JFileChooser();
chooser.setDialogType(JFileChooser.OPEN_DIALOG );
chooser.setDialogTitle("Open Data File");
int returnVal = chooser.showOpenDialog(null);
if( returnVal == JFileChooser.APPROVE_OPTION)
{
dataFilePath = chooser.getSelectedFile().getPath();
dataFileName = chooser.getSelectedFile().getName();
}
repaint();
}
else
if("Process".equals(command))
{
try
{
// Initialize
int[] aCount = new int[256];
// "Instantiate" streams
BufferedReader inputStream = new BufferedReader(new FileReader(dataFilePath));
// read the file line by line and count the characters read
String line = null;
char c = 0;
int lineLength = 0;
int charValue = 0;
while ((line = inputStream.readLine()) != null)
{
// ********* process line
for (int i = 0; i < line.length(); i++)
{
char ch = line.charAt(i);
if (ch >= 0 && ch <= 255)
{
counter[(int)ch]++;
}
else
{ // silently ignore non-ASCII characters
}
// count newline at the end
counter['\n']++;
}
}
}
catch(IOException ioe)
{
System.out.print("You want to run that by me again?");
}
repaint();
}
else
if("Exit".equals(command))
{
System.exit(0);
}
}
//********************************************************
//called by repaint() to redraw the screen
//********************************************************
public void paint(Graphics g)
{
if("Open".equals(command))
{
// Acknowledge that file was opened
if (dataFileName != null)
{
g.drawString("File -- "+dataFileName+" -- was successfully opened", 400, 400);
}
else
{
g.drawString("NO File is Open", 400, 400);
}
return;
}
else
if("Process".equals(command))
{
for(int i = 0; i < 256; i++)
{
int x = 100;
int y = 100;
g.drawString("Int", x, y);
g.drawString("Char", x+50, y);
g.drawString("Count", x+100, y);
g.drawLine(100, y+15, x+120, y+15);
y = y + 30;
int line = 0;
for(int j = 0; j < 256; j++)
{
line++;
g.drawString(Integer.toString(j), x, y);
g.drawString(Character.toString((char)j), x + 50, y); // Converts the # to a char, then to a String
// This part of the code adds a new column when the flag reaches 43
if(line == 45)
{
x = x + 150;
y = 100;
g.drawString("Int", x, y);
g.drawString("Char", x+50, y);
g.drawString("Count", x+100, y);
g.drawLine(100, y+15, x+120, y+15);
y = y + 15;
line = 0;
}
y = y+15;
}
}
return;
}
}
}
Your charValue variable appears to break your logic. You should remove it. This is sufficient:
for (int i=0; i<alphabetArray.length; i++)
alphabetArray[i] = 0; // set initial values
while ((line = inputStream.readLine()) != null) {
for(int i=0; i<line.length(); i++)
alphabetArray[(int)line.charAt(i)]++; // use the ASCII value of the character as an index
}
Your alphabet counter also seems to go out of scope. Either (1) make alphabetArray an instance variable of the class, or (2) display its contents before it goes out of scope. I think #1 is preferable.
I'd also be concerned about this line:
System.out.println(c + " : "+ char.alphabetArray[i]);
char is a datatype, and alphabetArray does not exist inside of it (and technically doesn't exist anywhere at this point since it's gone out of scope). c is also undefined. Take advantage of ASCII values! However, be careful printing non-printable characters and such. Your output will look really funky.
System.out.println((char)i + " : "+ alphabetArray[i]);
Of course, you'd still need to make alphabetArray accessible somehow.
I'm busy writing an hangman application and I'm currently checking if some of the code works... now i haven't gotten to hiding the word part yet so in the place of that code i used an if statement as supplementary code:
if(original.indexOf(button.getText())!=-1){
JOptionPane.showMessageDialog(null, "Your word does contain" + text );
}
else{
JOptionPane.showMessageDialog(null, "There is no" + text );
error++;
}
}
Anyway when I press the buttons that's not in the word it suppose to add to my errors according to
error++;
and it only finds the first letter in the word. One of my words are Dinosaur when i press D it says "Yes, there is a D" but when I press A it says "No, there is no I" where the clearly is
Can someone please help
here's my full code
import java.awt.*;
import java.awt.event.*;
import java.util.Arrays;
import javax.swing.*;
import java.io.*;
import java.util.ArrayList;
import java.util.Random;
import java.util.List;
public final class Hangman extends JFrame implements ActionListener{
String original = readWord();
int error = 0;
String imageName;
JButton btnAddWord = new JButton("Add New Word");
JButton btnRestart = new JButton("Restart");
JButton btnHelp = new JButton("Help");
JButton btnExit = new JButton("Exit");
JLabel word = new JLabel(original);
static JPanel panel1 = new JPanel();
static JPanel panel2 = new JPanel();
static JPanel panel3 = new JPanel();
static JPanel panel4 = new JPanel();
public Hangman(){
Container content =getContentPane();
content.setLayout(new GridLayout(0,1));
if(error >= 0) imageName = "hangman1.jpg";
if(error >= 1) imageName = "hangman2.jpg";
if(error >= 2) imageName = "hangman3.jpg";
if(error == 3) imageName = "hangman4.jpg";
if(error == 4) imageName = "hangman5.jpg";
if(error == 5) imageName = "hangman6.jpg";
if(error == 7) imageName = "hangman7.jpg";
ImageIcon icon = null;
if(imageName != null){
icon = new ImageIcon(imageName);
}
JLabel image = new JLabel();
image.setIcon(icon);
btnAddWord.addActionListener(this);
btnRestart.addActionListener(this);
btnHelp.addActionListener(this);
btnExit.addActionListener(this);
panel2.add(image);
panel3.add(word);
panel4.add(btnAddWord);
panel4.add(btnRestart);
panel4.add(btnHelp);
panel4.add(btnExit);
for(char i = 'A'; i <= 'Z'; i++){
String buttonText = new Character(i).toString();
JButton button = getButton(buttonText);
panel1.add(button);
}
}
public JButton getButton(final String text){
final JButton button = new JButton(text);
button.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
if(original.indexOf(button.getText())!=-1){
JOptionPane.showMessageDialog(null, "Your word does contain " + text );
}
else{
JOptionPane.showMessageDialog(null, "There is no " + text );
error++;
}
}
});
return button;
}
public String readWord(){
try{
BufferedReader reader = new BufferedReader(new FileReader("Words.txt"));
String line = reader.readLine();
List<String> words = new ArrayList<String>();
while(line != null){
String[] wordsLine = line.split(" ");
boolean addAll = words.addAll(Arrays.asList(wordsLine));
line = reader.readLine();
}
Random rand = new Random(System.currentTimeMillis());
String randomWord = words.get(rand.nextInt(words.size()));
return randomWord;
}catch (Exception e){
return null;
}
}
public void actionPerformed(ActionEvent e){
if(e.getSource() == btnAddWord){
try{
FileWriter fw = new FileWriter("Words.txt", true);
PrintWriter pw = new PrintWriter(fw, true);
String word = JOptionPane.showInputDialog("Please enter a word: ");
pw.println(word);
pw.close();
}
catch(IOException ie){
System.out.println("Error Thrown" + ie.getMessage());
}
}
if(e.getSource() == btnRestart){
}
if(e.getSource() == btnHelp){
String message = "The word to guess is represented by a row of dashes, giving the number of letters and category of the word."
+ "\nIf the guessing player suggests a letter which occurs in the word, the other player writes it in all its correct positions."
+ "\nIf the suggested letter does not occur in the word, the other player draws one element of the hangman diagram as a tally mark."
+ "\n"
+ "\nThe game is over when:"
+ "\nThe guessing player completes the word, or guesses the whole word correctly"
+ "\nThe other player completes the diagram";
JOptionPane.showMessageDialog(null,message, "Help",JOptionPane.INFORMATION_MESSAGE);
}
if(e.getSource() == btnExit){
System.exit(0);
}
}
public static void main (String [] args){
Hangman frame = new Hangman();
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(400, 600);
frame.add(panel1, BorderLayout.NORTH);
frame.add(panel2, BorderLayout.CENTER);
frame.add(panel3, BorderLayout.SOUTH);
frame.add(panel4, BorderLayout.SOUTH);
}
}
My first guess is that your text comparison is case sensitive.
"Dinosaur".indexOf("A") is not the same as "Dinosaur".indexOf("a")
I'd suggest converting the text to common case when you compare it.
original.toLowerCase().indexOf(button.getText().toLowerCase())!=-1
This is because you're not correctly checking whether the word that you're reading from the file is in the same case as the text in your JButton. There're a couple of ways to fix this:
As #MadProgrammer suggested. Have a couple of checks to cover both lowercase and uppercase characters.
Standardizing your List<String> words i.e. keep everything in one case when you're reading from the file. That way you don't have to worry much in terms of checking whether its in lowercase or uppercase. So in this case you might want to change: String[] wordsLine = line.split(" "); to String[] wordsLine = line.toLowerCase().split(" "); or String[] wordsLine = line.toUpperCase().split(" "); (depending on which one you're comfortable with). Then your check with a single indexOf() operation looks fine.