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
Related
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.
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 seem to be having issues with the search array function in my swing app , I'm not sure as to what is causing this function not to work, it has a try catch in it to say no matching results but that isn't even working. I also have a section where the user could add their own movie to the arrays, this also seems to not be working at all. I think these issues might be related as they both use the array. Can anyone see the problem ? Thanks in advanced!
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.text.*;
public class DVD1 extends JFrame implements ActionListener
{
//construct components
JLabel sortPromt= new JLabel("Sort by:");
JComboBox fieldCombo= new JComboBox();
JTextPane textPane = new JTextPane();
//initalize data in arrays
String title[]={"Casablanca", "Citizen Kane", "Singin in the rain", "The wizzard of Oz"};
String studio[]={"Wanner Brothers", "RKO Pictures", "MGM", "MGM"};
String year[]={"1942", "1941", "1952", "1939"};
//construct an instance of DVD
public DVD1()
{
super("Classic on DVD");
}
//create the menu system
public JMenuBar createMenuBar()
{
///create instance of menu bar
JMenuBar mnuBar =new JMenuBar();
setJMenuBar(mnuBar);
//Construct and Populate the File menu
JMenu mnuFile = new JMenu("File",true);
mnuFile.setMnemonic(KeyEvent.VK_F);
mnuFile.setDisplayedMnemonicIndex(0);
mnuBar.add(mnuFile);
JMenuItem mnuFileExit =new JMenuItem("Exit");
mnuFileExit.setMnemonic(KeyEvent.VK_E);
mnuFileExit.setDisplayedMnemonicIndex(1);
//mnuBar.add(mnuFileExit);
mnuFile.add(mnuFileExit);
mnuFileExit.setActionCommand("Exit");
mnuFileExit.addActionListener(this);
//construct and pop the edit menu
JMenu mnuEdit = new JMenu("Edit",true);
mnuEdit.setMnemonic(KeyEvent.VK_E);
mnuEdit.setDisplayedMnemonicIndex(0);
mnuBar.add(mnuEdit);
JMenuItem mnuEditInsert = new JMenuItem("Insert New DVD");
mnuEditInsert.setMnemonic(KeyEvent.VK_I);
mnuEditInsert.setDisplayedMnemonicIndex(1);
mnuEdit.add(mnuEditInsert);
mnuEditInsert.setActionCommand("Insert");
mnuEditInsert.addActionListener(this);
JMenu mnuEditSearch = new JMenu("Search",true);
mnuEditSearch.setMnemonic(KeyEvent.VK_R);
mnuEditSearch.setDisplayedMnemonicIndex(3);
mnuEdit.add(mnuEditSearch);
JMenuItem mnuEditSearchByTitle =new JMenuItem("By Title");
mnuEditSearchByTitle.setMnemonic(KeyEvent.VK_T);
mnuEditSearchByTitle.setDisplayedMnemonicIndex(3);
mnuEditSearch.add(mnuEditSearchByTitle);
mnuEditSearchByTitle.setActionCommand("title");
mnuEditSearchByTitle.addActionListener(this);
JMenuItem mnuEditSearchByStudio =new JMenuItem("By Studio");
mnuEditSearchByStudio.setMnemonic(KeyEvent.VK_S);
mnuEditSearchByStudio.setDisplayedMnemonicIndex(3);
mnuEditSearch.add(mnuEditSearchByStudio);
mnuEditSearchByStudio.setActionCommand("title");
mnuEditSearchByStudio.addActionListener(this);
JMenuItem mnuEditSearchByYear =new JMenuItem("By Year");
mnuEditSearchByYear.setMnemonic(KeyEvent.VK_Y);
mnuEditSearchByYear.setDisplayedMnemonicIndex(3);
mnuEditSearch.add(mnuEditSearchByYear);
mnuEditSearchByYear.setActionCommand("title");
mnuEditSearchByYear.addActionListener(this);
return mnuBar;
}//End menu contructor
//Create the conetnt pane
public Container createContentPane()
{
//populate the jcomboBox
fieldCombo.addItem("Title");
fieldCombo.addItem("Studio");
fieldCombo.addItem("Year");
fieldCombo.addActionListener(this);
fieldCombo.setToolTipText("Click the drop-down arow to display sort fields");
//construct and populate the north panel
JPanel northPanel = new JPanel();
northPanel.setLayout(new FlowLayout());
northPanel.add(sortPromt);
northPanel.add(fieldCombo);
//Create the JTextPane and center Panel
JPanel centerPanel = new JPanel();
setTabsAndStyles(textPane);
textPane = addTextToTextPane();
JScrollPane scrollPane = new JScrollPane(textPane);
scrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
scrollPane.setPreferredSize(new Dimension(500, 200));
centerPanel.add(scrollPane);
//create container and set attributes
Container c = getContentPane();
c.setLayout(new BorderLayout(10,10));
c.add(northPanel,BorderLayout.NORTH);
c.add(centerPanel,BorderLayout.CENTER);
return c;
}//end create container method
//method to create thtab stops and set fontstyles
protected void setTabsAndStyles(JTextPane textPane)
{
//create Tab Stops
TabStop[] tabs = new TabStop[2];
tabs[0] = new TabStop(200, TabStop.ALIGN_LEFT,TabStop.LEAD_NONE);
tabs[1] = new TabStop(350, TabStop.ALIGN_LEFT,TabStop.LEAD_NONE);
TabSet tabset = new TabSet(tabs);
//set tab style
StyleContext tabStyle = StyleContext.getDefaultStyleContext();
AttributeSet aset=
tabStyle.addAttribute(SimpleAttributeSet.EMPTY, StyleConstants.TabSet,tabset);
textPane.setParagraphAttributes(aset, false);
//set Font Style
Style fontStyle =
StyleContext.getDefaultStyleContext().getStyle(StyleContext.DEFAULT_STYLE);
Style regular = textPane.addStyle("regular", fontStyle);
StyleConstants.setFontFamily(fontStyle, "sansSerif");
Style s = textPane .addStyle("italic",regular);
StyleConstants.setItalic(s,true);
s = textPane .addStyle("blod",regular);
StyleConstants.setBold(s,true);
s = textPane .addStyle("lard",regular);
StyleConstants.setFontSize(s,16);
}
//method to ad text to textpane
public JTextPane addTextToTextPane()
{
Document doc = textPane.getDocument();
try
{
//clear previous text
doc.remove(0, doc.getLength());
//Insert title
doc.insertString(0,"Title\tStudio\tYear\n",textPane.getStyle("large"));
//insert detail
for(int j=0;j<title.length;j++)
{
doc.insertString(doc.getLength(),title[j] + "\t",textPane.getStyle("bold"));
doc.insertString(doc.getLength(),studio[j] + "\t",textPane.getStyle("italic"));
doc.insertString(doc.getLength(),year[j] + "\n",textPane.getStyle("regular"));
}//end loop
} //end try
catch (BadLocationException ble)
{
System.err.println("Couldnlt Insert Text");
}//end catch
return textPane;
}///end addtexttotextpane method
public void actionPerformed(ActionEvent e)
{
String arg = e.getActionCommand();
//user clicks the sort by combo box
if(e.getSource() == fieldCombo)
{
switch(fieldCombo.getSelectedIndex())
{
case 0:
sort(title);
break;
case 1:
sort(studio);
break;
case 2:
sort(year);
break;
}//end swictch
} //end if
//user clicks exit on file menu
if (arg=="Exit")
System.exit(0);
//user clicks insert new dvd on edit menu
if (arg=="insert")
{
String newTitle = JOptionPane.showInputDialog(null, "Please enter the moive's title");
String newStudio = JOptionPane.showInputDialog(null, "Please enter the studio for" + newTitle);
String newYear = JOptionPane.showInputDialog(null, "Please enter the year for " + newTitle);
//Enlarge arrays
title = enlargeArray(title);
studio = enlargeArray(studio);
year = enlargeArray(year);
//add to arrys
title[title.length-1] = newTitle;
studio[studio.length-1] = newStudio;
year[year.length-1] = newYear;
//call to sort method
sort(title);
fieldCombo.setSelectedIndex(0);
}//end if
//user clicks title on search submeu
if(arg=="title")
search(arg,title);
//user clicks title on studio submeu
if(arg=="studio")
search(arg,studio);
//user clicks title on year submeu
if(arg=="year")
search(arg,year);
}//end of actionPerfomed method
//Method to enlarge an arry by 1
public String[] enlargeArray(String[]currentArray)
{
String[]newArray=new String [currentArray.length +1];
for(int i = 0; i<currentArray.length;i++)
newArray[i]=currentArray[i];
return newArray;
}//end enlarg arry method
//method to sort arrays
public void sort(String tempArray[])
{
//loop to control number of passes
for(int pass = 1;pass<tempArray.length;pass++)
{
for(int element =0 ; element<tempArray.length -1 ;element++)
if (tempArray[element].compareTo(tempArray[element+1])>0)
{
swap(title,element,element+1);
swap(studio,element, element+1);
swap(studio,element, element+1);
}//end if
}//end of loop
addTextToTextPane();
}//end of sort method
//method to swap two elements of an array
public void swap(String swapArray[], int first, int second)
{
String hold;//temp area to hold for swap
hold = swapArray[first];
swapArray[first] = swapArray[second];
swapArray[second] = hold;
} //end swap method
public void search (String searchField, String searchArray[])
{
try
{
Document doc = textPane.getDocument();//assing text to document object
doc.remove(0,doc.getLength());//clear previous text
//display colomTitles
doc.insertString(0,"TITLE\tSTUDIO\tYEAR\n",textPane.getStyle("large"));
//Prompt users for search data
String search=JOptionPane.showInputDialog(null, "Please enter the " + searchField);
boolean found= false;
//search arrays
for (int i=0; i<title.length; i++)
{
if(search.compareTo(searchArray[i])==0)
{
doc.insertString(doc.getLength(),title[i] + "\t", textPane.getStyle("bold"));
doc.insertString(doc.getLength(),studio[i] + "\t", textPane.getStyle("italic"));
doc.insertString(doc.getLength(),year[i] + "\n", textPane.getStyle("regular"));
}//end if
}//end for
if (found = false)
{
JOptionPane.showMessageDialog(null,"Your search produced no results.", "no results found", JOptionPane.INFORMATION_MESSAGE);
sort(title);
}//end if
}//end try
catch(BadLocationException ble)
{
System.err.println("Couldn't insert text.");
}//end catch
}//End serach method
//main method executes at runtime
public static void main(String args[])
{
JFrame.setDefaultLookAndFeelDecorated(true);
DVD1 f =new DVD1();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setJMenuBar(f.createMenuBar());
f.setContentPane(f.createContentPane());
f.setSize(600,375);
f.setVisible(true);
}//end main method
}//end dvd class
All of your If.. else condition needs to be modified. == can only be used to compare literal values in java, literal values means int, double, float, etc. But String is an object and object can not be compared using ==. If you compare objects using == it will try to compare the references values to those objects, which will hardly be equal in your case. When using String object equals() method is used to compare it. If you are using java 7 then you can also you switch case for Strings. But for now I am giving you example of using equals() method for your code. Change your ActionPerformed method to following.
public void actionPerformed(ActionEvent e)
{
String arg = e.getActionCommand();
//user clicks the sort by combo box
if(e.getSource() == fieldCombo)
{
switch(fieldCombo.getSelectedIndex())
{
case 0:
sort(title);
break;
case 1:
sort(studio);
break;
case 2:
sort(year);
break;
}//end swictch
} //end if
//user clicks exit on file menu
if (arg.equals("Exit"))
System.exit(0);
//user clicks insert new dvd on edit menu
if (arg.equals("insert"))
{
String newTitle = JOptionPane.showInputDialog(null, "Please enter the moive's title");
String newStudio = JOptionPane.showInputDialog(null, "Please enter the studio for" + newTitle);
String newYear = JOptionPane.showInputDialog(null, "Please enter the year for " + newTitle);
//Enlarge arrays
title = enlargeArray(title);
studio = enlargeArray(studio);
year = enlargeArray(year);
//add to arrys
title[title.length-1] = newTitle;
studio[studio.length-1] = newStudio;
year[year.length-1] = newYear;
//call to sort method
sort(title);
fieldCombo.setSelectedIndex(0);
}//end if
//user clicks title on search submeu
if(arg.equals("title"))
search(arg,title);
//user clicks title on studio submeu
if(arg.equals("studio"))
search(arg,studio);
//user clicks title on year submeu
if(arg.equals("year"))
search(arg,year);
}//end of actionPerfomed method
Good afternoon. I have created an application for an introductory java course that allows a user to sort their DVD collection by title, studio, or year. The application also allows the user to add additional DVD's to their collection, thus enlarging their arrays. The code properly compiles, but there is clearly something wrong as the titles, studio, and years are mixing themselves up. To be clear, this code is from a textbook and is part of a lab that requires the use of the exact methods, packages, etc. that you see in the code. I'm not asking for advice on how to make the code more efficient (although that is welcome as I am learning), but specifically what is wrong with the code provided causing the "scramble". Here is the code I have:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.text.*;
public class DVD extends JFrame implements ActionListener
{
// construct components
JLabel sortPrompt = new JLabel("Sort by:");
JComboBox fieldCombo = new JComboBox();
JTextPane textPane = new JTextPane();
// initialize data in arrays
String title[] = {"Casablanca", "Citizen Kane", "Singin' in the Rain", "The Wizard of Oz"};
String studio[] = {"Warner Brothers", "RKO Pictures", "MGM", "MGM"};
String year[] = {"1942", "1941", "1952", "1939"};
// construct instance of DVD
public DVD()
{
super("Classics on DVD");
}
// create the menu system
public JMenuBar createMenuBar()
{
// create an instance of the menu
JMenuBar mnuBar = new JMenuBar();
setJMenuBar(mnuBar);
// construct and populate the File menu
JMenu mnuFile = new JMenu("File", true);
mnuFile.setMnemonic(KeyEvent.VK_F);
mnuFile.setDisplayedMnemonicIndex(0);
mnuBar.add(mnuFile);
JMenuItem mnuFileExit = new JMenu("Exit");
mnuFileExit.setMnemonic(KeyEvent.VK_X);
mnuFileExit.setDisplayedMnemonicIndex(1);
mnuFile.add(mnuFileExit);
mnuFileExit.setActionCommand("Exit");
mnuFileExit.addActionListener(this);
// contruct and populate the Edit menu
JMenu mnuEdit = new JMenu("Edit", true);
mnuEdit.setMnemonic(KeyEvent.VK_E);
mnuEdit.setDisplayedMnemonicIndex(0);
mnuBar.add(mnuEdit);
JMenuItem mnuEditInsert = new JMenuItem("Insert New DVD");
mnuEditInsert.setMnemonic(KeyEvent.VK_I);
mnuEditInsert.setDisplayedMnemonicIndex(0);
mnuEdit.add(mnuEditInsert);
mnuEditInsert.setActionCommand("Insert");
mnuEditInsert.addActionListener(this);
JMenu mnuEditSearch = new JMenu("Search");
mnuEditSearch.setMnemonic(KeyEvent.VK_R);
mnuEditSearch.setDisplayedMnemonicIndex(3);
mnuEdit.add(mnuEditSearch);
JMenuItem mnuEditSearchByTitle = new JMenuItem("by Title");
mnuEditSearchByTitle.setMnemonic(KeyEvent.VK_T);
mnuEditSearchByTitle.setDisplayedMnemonicIndex(3);
mnuEditSearch.add(mnuEditSearchByTitle);
mnuEditSearchByTitle.setActionCommand("title");
mnuEditSearchByTitle.addActionListener(this);
JMenuItem mnuEditSearchByStudio = new JMenuItem("by Studio");
mnuEditSearchByStudio.setMnemonic(KeyEvent.VK_S);
mnuEditSearchByStudio.setDisplayedMnemonicIndex(3);
mnuEditSearch.add(mnuEditSearchByStudio);
mnuEditSearchByStudio.setActionCommand("studio");
mnuEditSearchByStudio.addActionListener(this);
JMenuItem mnuEditSearchByYear = new JMenuItem("by Year");
mnuEditSearchByYear.setMnemonic(KeyEvent.VK_Y);
mnuEditSearchByYear.setDisplayedMnemonicIndex(3);
mnuEditSearch.add(mnuEditSearchByYear);
mnuEditSearchByYear.setActionCommand("year");
mnuEditSearchByYear.addActionListener(this);
return mnuBar;
}
// create the content pane
public Container createContentPane()
{
// populate the JComboBox
fieldCombo.addItem("Title");
fieldCombo.addItem("Studio");
fieldCombo.addItem("Year");
fieldCombo.addActionListener(this);
fieldCombo.setToolTipText("Click the drop-down arrow to display sort fields.");
// construct and populate the north panel
JPanel northPanel = new JPanel();
northPanel.setLayout(new FlowLayout());
northPanel.add(sortPrompt);
northPanel.add(fieldCombo);
// create the JTextPane and center panel
JPanel centerPanel = new JPanel();
setTabsAndStyles(textPane);
textPane = addTextToTextPane();
JScrollPane scrollPane = new JScrollPane(textPane);
scrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
scrollPane.setPreferredSize(new Dimension(500, 200));
centerPanel.add(scrollPane);
// create Container and set attributes
Container c = getContentPane();
c.setLayout(new BorderLayout(10,10));
c.add(northPanel,BorderLayout.NORTH);
c.add(centerPanel,BorderLayout.CENTER);
return c;
}
// method to create tab stops and set font styles
protected void setTabsAndStyles(JTextPane textPane)
{
// create Tab Stops
TabStop[] tabs = new TabStop[2];
tabs[0] = new TabStop(200, TabStop.ALIGN_LEFT, TabStop.LEAD_NONE);
tabs[1] = new TabStop(350, TabStop.ALIGN_LEFT, TabStop.LEAD_NONE);
TabSet tabset = new TabSet(tabs);
// set Tab Style
StyleContext tabStyle = StyleContext.getDefaultStyleContext();
AttributeSet aset =
tabStyle.addAttribute(SimpleAttributeSet.EMPTY, StyleConstants.TabSet, tabset);
textPane.setParagraphAttributes(aset, false);
// set Font styles
Style fontStyle =
StyleContext.getDefaultStyleContext().getStyle(StyleContext.DEFAULT_STYLE);
Style regular = textPane.addStyle("regular", fontStyle);
StyleConstants.setFontFamily(fontStyle, "SansSerif");
Style s = textPane.addStyle("italic", regular);
StyleConstants.setItalic(s, true);
s = textPane.addStyle("bold", regular);
StyleConstants.setBold(s, true);
s = textPane.addStyle("large", regular);
StyleConstants.setFontSize(s, 16);
}
// method to add new text to the JTextPane
public JTextPane addTextToTextPane()
{
Document doc = textPane.getDocument();
try
{
// clear the previous text
doc.remove(0, doc.getLength());
// insert title
doc.insertString(0,"TITLE\tSTUDIO\tYEAR\n",textPane.getStyle("large"));
// insert detail
for (int j = 0; j<title.length; j++)
{
doc.insertString(doc.getLength(), title[j] + "\t", textPane.getStyle("bold"));
doc.insertString(doc.getLength(), studio[j] + "\t", textPane.getStyle("italic"));
doc.insertString(doc.getLength(), year[j] + "\t", textPane.getStyle("regular"));
}
}
catch(BadLocationException ble)
{
System.err.println("Couldn't insert text.");
}
return textPane;
}
// event to process user clicks
public void actionPerformed(ActionEvent e)
{
String arg = e.getActionCommand();
// user clicks the sort by combo box
if (e.getSource() == fieldCombo)
{
switch(fieldCombo.getSelectedIndex())
{
case 0:
sort(title);
break;
case 1:
sort(studio);
break;
case 2:
sort(year);
break;
}
}
// user clicks Exit on the File menu
if (arg == "Exit")
System.exit(0);
// user clicks Insert New DVD on the Edit Menu
if (arg == "Insert")
{
// accept new data
String newTitle = JOptionPane.showInputDialog(null, "Please enter the new movie's title");
String newStudio = JOptionPane.showInputDialog(null, "Please enter the studio for " + newTitle);
String newYear = JOptionPane.showInputDialog(null, "Please enter the year for " + newTitle);
// enlarge arrays
title = enlargeArray(title);
studio = enlargeArray(studio);
year = enlargeArray(year);
// add new data to arrays
title[title.length-1] = newTitle;
studio[studio.length-1] = newStudio;
year[year.length-1] = newYear;
// call sort method
sort(title);
fieldCombo.setSelectedIndex(0);
}
// user clicks Title on the Search submenu
if (arg == "title")
search(arg, title);
// user clicks Studio on the Search submenu
if (arg == "studio")
search(arg, studio);
// user clicks Year on the Search submenu
if (arg == "year")
search(arg, year);
}
// method to enlarge an array by 1
public String[] enlargeArray(String[] currentArray)
{
String[] newArray = new String[currentArray.length + 1];
for (int i = 0; i<currentArray.length; i++)
newArray[i] = currentArray[i];
return newArray;
}
// method to sort arrays
public void sort(String tempArray[])
{
// loop ton control number of passes
for (int pass = 1; pass < tempArray.length; pass++)
{
for (int element = 0; element < tempArray.length - 1; element++)
if (tempArray[element].compareTo(tempArray[element + 1])>0)
{
swap(title, element, element + 1);
swap(studio, element, element + 1);
swap(year, element, element + 1);
}
}
addTextToTextPane();
}
// method to swap two elements of an array
public void swap(String swapArray[], int first, int second)
{
String hold; // temporary holding area for swap
hold = swapArray[first];
swapArray[first] = swapArray[second];
swapArray[second] = hold;
}
public void search(String searchField, String searchArray[])
{
try
{
Document doc = textPane.getDocument(); // assign text to document object
doc.remove(0,doc.getLength()); // clear previous text
// display column titles
doc.insertString(0,"TITLE\tSTUDIO\tYEAR\n",textPane.getStyle("large"));
// prompt user for search data
String search = JOptionPane.showInputDialog(null, "Please enter the "+searchField);
boolean found = false;
// search arrays
for (int i = 0; i<title.length; i++)
{
if (search.compareTo(searchArray[i])==0)
{
doc.insertString(doc.getLength(), title[i] + "\t", textPane.getStyle("bold"));
doc.insertString(doc.getLength(), studio[i] + "\t", textPane.getStyle("italic"));
doc.insertString(doc.getLength(), year[i] + "\t", textPane.getStyle("regular"));
found = true;
}
}
if (found == false)
{
JOptionPane.showMessageDialog(null, "Your search produced no results.","No results found",JOptionPane.INFORMATION_MESSAGE);
sort(title);
}
}
catch(BadLocationException ble)
{
System.err.println("Couldn't insert text.");
}
}
// main method executes at run time
public static void main(String arg[])
{
JFrame.setDefaultLookAndFeelDecorated(true);
DVD f = new DVD();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setJMenuBar(f.createMenuBar());
f.setContentPane(f.createContentPane());
f.setSize(600,375);
f.setVisible(true);
}
}
Here is a screenshot to give you a sense of what I mean be "scrambled".
Obviously, all of the titles should be in the title column, studios in studio, and years in year.
As always, I appreciate the guidance.
The problem is this line
doc.insertString(doc.getLength(), year[j] + "\t", textPane.getStyle("regular"));
where you put a tab ("\t") after the year but instead you want a newline ("\n"). So the line becomes
doc.insertString(doc.getLength(), year[j] + "\n", textPane.getStyle("regular"));
Do you simply miss a newline after adding the year of a DVD to the document? I.e.
doc.insertString(doc.getLength(), year[j] + "\n", textPane.getStyle("regular"));
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.