Displaying an array of Strings in a JTextArea - java

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...

Related

Troubleshooting Vignere Cipher using JFileChooser and JPasswordField

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.

How do I make my count variable increment correctly?

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;

How do I make my code find out which button was pressed within a reasonable amount of time?

Alright, this one is a bit of a doozy, its about 240 lines long, but on to my point. The point is that it doesn't work. I'm pretty new to coding in general and some help would be really appreciated. I know where the problem is, it's in the last bits of it in the for loops, I went under the false presumption that if you click a JButton, it is then selected. How do I implement the .setSelected method to my program without rewriting the entire code? This code is a make-shift jeopardy of sorts btw.
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import sun.audio.*;
import java.io.*;
public class Jeopardy implements ActionListener
{
public static JFrame frame = new JFrame("Jeopardy!");
public static JButton[] row1Buttons = new JButton[6];
public static JButton[] row2Buttons = new JButton[6];
public static JButton[] row3Buttons = new JButton[6];
public static JButton[] row4Buttons = new JButton[6];
public static JButton[] row5Buttons = new JButton[6];
//Creates 5 arrays, each with 6 JButtons in each (otherwise mass confusion
//is going to ensue because I would have to individually add 30 JButtons to the pane,
//all of which I would have to remember what they contain.)
public static JPanel pane = new JPanel();
public static JLabel[] labels = new JLabel[6];
//Creates an array of 6 JLabels
public static void main(String[] args)
{
frame.setSize(800, 600);
frame.setVisible(true);
frame.toFront();
frame.setContentPane(pane);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Font font = new Font("ComicSans", Font.PLAIN, 20);
Color colour = new Color(0, 0, 240);
for(int a = 0; a < row1Buttons.length; a++)
{
row1Buttons[a] = new JButton("$200");
row2Buttons[a] = new JButton("$400");
row3Buttons[a] = new JButton("$600");
row4Buttons[a] = new JButton("$800");
row5Buttons[a] = new JButton("$1000");
//Gives text to all 30 JButtons
row1Buttons[a].addActionListener(new Jeopardy());
row2Buttons[a].addActionListener(new Jeopardy());
row3Buttons[a].addActionListener(new Jeopardy());
row4Buttons[a].addActionListener(new Jeopardy());
row5Buttons[a].addActionListener(new Jeopardy());
//adds action listener to all 30
row1Buttons[a].setBackground(colour);
row2Buttons[a].setBackground(colour);
row3Buttons[a].setBackground(colour);
row4Buttons[a].setBackground(colour);
row5Buttons[a].setBackground(colour);
//sets background colour
row1Buttons[a].setForeground(Color.yellow);
row2Buttons[a].setForeground(Color.yellow);
row3Buttons[a].setForeground(Color.yellow);
row4Buttons[a].setForeground(Color.yellow);
row5Buttons[a].setForeground(Color.yellow);
}
labels[0] = new JLabel("Mathematics");
labels[1] = new JLabel("Computer Science");
labels[2] = new JLabel("Historical Events");
labels[3] = new JLabel("Chemistry");
labels[4] = new JLabel("TBD");
labels[5] = new JLabel("TBD");
for(int k = 0; k < labels.length; k++)
{
labels[k].setForeground(Color.yellow);
}
pane.setLayout(new GridLayout(6, 6, 6, 6));
for(int b = 0; b < labels.length; b++)
{
pane.add(labels[b]);
pane.add(row1Buttons[b]);
pane.add(row2Buttons[b]);
pane.add(row3Buttons[b]);
pane.add(row4Buttons[b]);
pane.add(row5Buttons[b]);
}
pane.setBackground(Color.blue);
}
public void actionPerformed(ActionEvent event)
{
String[] answerRow1 = new String[6];
String[] answerRow2 = new String[6];
String[] answerRow3 = new String[6];
String[] answerRow4 = new String[6];
String[] answerRow5 = new String[6];
String[] questionsRow1 = new String[6];
//Write $200 questions
questionsRow1[0] = "Question";
questionsRow1[1] = "Question";
questionsRow1[2] = "Question";
questionsRow1[3] = "Question";
questionsRow1[4] = "Question";
questionsRow1[5] = "Question";
String[] questionsRow2 = new String[6];
//Write $400 questions
questionsRow2[0] = "Question";
questionsRow2[1] = "Question";
questionsRow2[2] = "Question";
questionsRow2[3] = "Question";
questionsRow2[4] = "Question";
questionsRow2[5] = "Question";
String[] questionsRow3 = new String[6];
//Write $600 questions
questionsRow3[0] = ("The function y=3(2)^x will have this for a y value when x = 3.");
questionsRow3[1] = "Question";
questionsRow3[2] = "Question";
questionsRow3[3] = "Question";
questionsRow3[4] = "Question";
questionsRow3[5] = "Question";
String[] questionsRow4 = new String[6];
//Write $800 questions
questionsRow4[0] = "Question";
questionsRow4[1] = "Question";
questionsRow4[2] = "Question";
questionsRow4[3] = "Question";
questionsRow4[4] = "Question";
questionsRow4[5] = "Question";
String[] questionsRow5 = new String[6];
//Write $1000 questions
questionsRow5[0] = "Question";
questionsRow5[1] = "Question";
questionsRow5[2] = "Question";
questionsRow5[3] = "Question";
questionsRow5[4] = "Question";
questionsRow5[5] = "Question";
for(int j = 0; j < questionsRow1.length; j++)
{
if(row1Buttons[j].getModel().isPressed())
{
try
{
InputStream in = new FileInputStream("sounds/x.wav");
AudioStream openSound = new AudioStream(in);
AudioPlayer.player.start(openSound);
}
catch(Exception e)
{
JOptionPane.showMessageDialog(null, "You don't have the sound clip for this");
}
answerRow1[j] = JOptionPane.showInputDialog(null, questionsRow1[j]);
}
}
for(int a = 0; a < questionsRow2.length; a++)
{
if(row2Buttons[a].isSelected())
{
try
{
InputStream in = new FileInputStream("sounds/x.wav");
AudioStream openSound = new AudioStream(in);
AudioPlayer.player.start(openSound);
}
catch(Exception e)
{
JOptionPane.showMessageDialog(null, "You don't have the sound clip for this");
}
JOptionPane.showInputDialog(null, questionsRow2[a]);
}
}
for(int r = 0; r < questionsRow3.length; r++)
{
if(row3Buttons[r].isSelected())
{
try
{
InputStream in = new FileInputStream("sounds/x.wav");
AudioStream openSound = new AudioStream(in);
AudioPlayer.player.start(openSound);
}
catch(Exception e)
{
JOptionPane.showMessageDialog(null, "You don't have the sound clip for this");
}
JOptionPane.showInputDialog(null, questionsRow3[r]);
}
}
for(int e = 0; e < questionsRow4.length; e++)
{
if(row4Buttons[e].isSelected())
{
try
{
InputStream in = new FileInputStream("sounds/x.wav");
AudioStream openSound = new AudioStream(in);
AudioPlayer.player.start(openSound);
}
catch(Exception exception)
{
JOptionPane.showMessageDialog(null, "You don't have the sound clip for this");
}
JOptionPane.showInputDialog(null, questionsRow4[e]);
}
}
for(int d = 0; d < questionsRow5.length; d++)
{
if(row5Buttons[d].isSelected())
{
try
{
InputStream in = new FileInputStream("sounds/x.wav");
AudioStream openSound = new AudioStream(in);
AudioPlayer.player.start(openSound);
}
catch(Exception e)
{
JOptionPane.showMessageDialog(null, "You don't have the sound clip for this");
}
JOptionPane.showInputDialog(null, questionsRow5[d]);
}
}
}
}
The problem is that you make the frame visible and then add your components. Instead, call setVisible() at the end of your constructor, after you pack() the frame.
public static void main(String[] args) {
...
pane.setBackground(Color.blue);
frame.pack();
frame.setVisible(true);
}
try to create a new class for buttons
public class Response_Button extends JButton {
public Response_Button(final JPanel container, final String name) {
this.setText(name);
this.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
JOptionPane.showMessageDialog(container, "clicked " + name);
}
});
}
like this each button will respond through it's own method
This is what fixes it:
if(event.getSource()== row1Buttons[j])
Yes, that makes it so that it will do all of the category in one fell swoop, but it doesn't matter. Thanks for all who tried and gave positive and helpful answers.
EDIT: nope, it doesn't do it all in one go, I just labeled it wrong.

Getting Null Pointed exception error but runs fine? Java JComboBox (DropDown box)

So Integer N here is controlled by a JComboBox basically a drop down menu 1-4. My problem is that I get a nullpointerexception error when I initially set N from the box..any ideas how to fix this? I tested it by printing out what N was in both actionlistener instances and it's null in the first one and it's correct in the second one.
import java.awt.GridLayout;
import javax.swing.JFrame;
import java.awt.event.*;
import javax.swing.*;
import java.awt.*;
import java.io.*;
import java.util.Scanner;
import java.util.Arrays;
import javax.swing.JComboBox;
public class Lab10 extends JPanel
{
private StringBuilder string, string2, string3, string4; //loads SuperStrings faster by appending all at once
private JRadioButton occurrence, alphabetical;
private JPanel text;
private JComboBox<Integer> input;
private JLabel label, file1,file2, unique, unique2;
private JButton load, go,go2;
private CountLinkedList<SuperString> words, words3; //Change impliments CountList to extends BinaryCountTree
private OrderedLinkedList<SuperString> words2, words4;//Change impliments CountList to extends BinaryCountTree
private String filename,filename2;
private int width = 450;
private int height = 550;
private TextArea textarea,textarea2;
Scanner scan;
public Lab10()
{
string = new StringBuilder();
string2 = new StringBuilder();
string3 = new StringBuilder();
string4 = new StringBuilder();
ButtonListener listener = new ButtonListener();
Button2Listener listener2 = new Button2Listener();
Integer [] select = {1,2,3,4};
input = new JComboBox<Integer>(select);
text = new JPanel(new GridLayout(1,2));
go = new JButton("Select Text File 1: ");
go2 = new JButton("Select Text File 2: ");
label = new JLabel("N: " );
unique = new JLabel("");
unique2 = new JLabel("");
file1 = new JLabel("");
file1.setFont(new Font("Helvetica",Font.PLAIN,24));
unique.setFont(new Font("Helvetica",Font.PLAIN,24));
file2 = new JLabel("");
file2.setFont(new Font("Helvetica",Font.PLAIN,24));
unique2.setFont(new Font("Helvetica",Font.PLAIN,24));
occurrence= new JRadioButton("Occurrence");
occurrence.setMnemonic(KeyEvent.VK_O);
occurrence.addActionListener(listener);
occurrence.addActionListener(listener2);
occurrence.setSelected(true);
alphabetical = new JRadioButton("Alphabetical");
alphabetical.setMnemonic(KeyEvent.VK_A);
alphabetical.addActionListener(listener);
alphabetical.addActionListener(listener2);
ButtonGroup group = new ButtonGroup();
group.add(occurrence);
group.add(alphabetical);
go.addActionListener(listener);
go2.addActionListener(listener2);
input.addActionListener(listener);
input.addActionListener(listener2);
textarea = new TextArea("",0,0,TextArea.SCROLLBARS_VERTICAL_ONLY);
textarea2 = new TextArea("",0,0,TextArea.SCROLLBARS_VERTICAL_ONLY);
textarea.setFont(new Font("Helvetica",Font.PLAIN,24));
textarea2.setFont(new Font("Helvetica",Font.PLAIN,24));
textarea.setPreferredSize(new Dimension(width,height));
textarea2.setPreferredSize(new Dimension(width,height));
setPreferredSize(new Dimension(1000,700));
text.add(textarea);
text.add(textarea2);
add(occurrence);
add(alphabetical);
add(label);
add(input);
add(go);
add(file1);
add(unique);
add(go2);
add(file2);
add(unique2);
add(text);
textarea.setText("No File Selected");
textarea2.setText("No File Selected");
}
public class ButtonListener implements ActionListener //makes buttons do things
{
JFileChooser chooser = new JFileChooser("../Text");
public void actionPerformed(ActionEvent event)
{
Integer N = input.getSelectedIndex()+1;
if(event.getSource() == go)
{
int returnvalue = chooser.showOpenDialog(null);
if(returnvalue == JFileChooser.APPROVE_OPTION)
{
try
{
File file = chooser.getSelectedFile();
String text1= file.getName();
file1.setText(text1);
filename = file.getName();
System.err.println(filename);
scan = new Scanner(file);
}
catch (IOException e)
{
System.err.println("IO EXCEPTION");
return;
}
}
else
{
return;
}
String[] storage = new String[N];
words = new CountLinkedList<SuperString>();
words2 = new OrderedLinkedList<SuperString>();
for(int i=1;i<N;i++)
storage[i] = scan.next().toLowerCase().replaceAll("[^A-Za-z0-9]", "")
.replaceAll("[.,':]","");
while(scan.hasNext())
{
for(int i=0;i<=N-2;i++)
storage[i] = storage[i+1];
storage[N-1] = scan.next().toLowerCase();
storage[N-1] = storage[N-1].replace(",","").replace(".","").replaceAll("[^A-Za-z0-9]", "")
.replaceAll("[.,':]","");
SuperString ss = new SuperString(storage);
SuperString ss2= new SuperString(storage);
words.add(ss );
words2.add(ss2 );
}
textarea.setText("");
}
SuperString[] ss = new SuperString[words.size()];
SuperString[] ss2 = new SuperString[words2.size()];
int i=0;
int count =0, count2= 0;
for(SuperString word: words)
{
ss[i] = word;
i++;
}
int j=0;
for(SuperString word: words2)
{
ss2[j] = word;
j++;
}
Arrays.sort(ss, new SuperStringCountOrder());
for(SuperString word : ss)
{
count++;
string.append(Integer.toString(count)+ " "+ word+ "\n");
}
if(occurrence.isSelected())
{
textarea.setText("");
textarea.append(" "+filename+" has wordcount: "+words.size()+
"\n-------------------------\n\n");
textarea.append(string.toString());
}
for(SuperString word : ss2)
{
count2++;
string2.append(Integer.toString(count2)+ " "+ word.toString()+ "\n");
}
if(alphabetical.isSelected())
{
textarea.setText("");
textarea.append(" "+filename+" has wordcount: "+words.size()+
"\n-------------------------\n\n");
textarea.append(string2.toString());
}
unique.setText("Unique Count: "+ Integer.toString(words.size()));
}
}
public class Button2Listener implements ActionListener
{
JFileChooser chooser = new JFileChooser("../Text");
public void actionPerformed(ActionEvent event)
{
Integer N = input.getSelectedIndex()+1;
if(event.getSource() == go2)
{
int returnvalue = chooser.showOpenDialog(null);
if(returnvalue == JFileChooser.APPROVE_OPTION)
{
try
{
File file = chooser.getSelectedFile();
String text2= file.getName();
file2.setText(text2);
filename2 = file.getName();
System.err.println(filename);
scan = new Scanner(file);
}
catch (IOException e)
{
System.err.println("IO EXCEPTION");
return;
}
}
else
{
return;
}
String[] storage = new String[N];
words3 = new CountLinkedList<SuperString>();
words4 = new OrderedLinkedList<SuperString>();
for(int i=1;i<N;i++)
storage[i] = scan.next().toLowerCase().replace(",","").replace(".","");
while(scan.hasNext())
{
for(int i=0;i<=N-2;i++)
storage[i] = storage[i+1];
storage[N-1] = scan.next().toLowerCase();
storage[N-1] = storage[N-1].replace(",","").replace(".","").replaceAll("[^A-Za-z0-9]", "")
.replaceAll("[.,':]","");
SuperString ss = new SuperString(storage);
SuperString ss2= new SuperString(storage);
words3.add(ss );
words4.add(ss2 );
}
textarea2.setText("");
}
SuperString[] sstwo = new SuperString[words3.size()];
SuperString[] ss2two = new SuperString[words4.size()];
int i=0;
int count =0, count2= 0;
for(SuperString word2: words3)
{
sstwo[i] = word2;
i++;
}
int j=0;
for(SuperString word2: words4)
{
ss2two[j] = word2;
j++;
}
Arrays.sort(sstwo, new SuperStringCountOrder());
for(SuperString word2 : sstwo)
{
count++;
string3.append(Integer.toString(count)+ " "+ word2+ "\n");
}
if(occurrence.isSelected())
{
textarea2.setText("");
textarea2.append(" "+filename2+" has wordcount: "+words3.size()+
"\n-------------------------\n\n");
textarea2.append(string3.toString());
}
for(SuperString word2 : ss2two)
{
count2++;
string4.append(count2+" "+ " "+word2+"\n");
}
if(alphabetical.isSelected())
{
textarea2.setText("");
textarea2.append(" "+filename2+" has wordcount: "+words3.size()+
"\n-------------------------\n\n");
textarea2.append(string4.toString());
}
unique2.setText("Unique Count: "+ Integer.toString(words3.size()));
}
}
public static void main(String[] arg)
{
JFrame frame = new JFrame("Lab 10");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(new Lab10());
frame.pack();
frame.setVisible(true);
}
}
Your question doesn't make sense as written:
Integer N = input.getSelectedIndex()+1;
System.out.println(N);
The println cannot possibly tell you that N is null.
If the expression on the RHS of the = executes without an exception, then N is guaranteed to be non-null. The getSelectedIndex() call returns an int, and the result of the addition will be an int. That will then be autoboxed to an Integer, and autoboxing can NEVER give you a null.
If the expression on the RHS of the = throws an exception, then the println statement won't be executed.
In other words, what you are describing is Impossible.
So what I think is actually happening is one of the following:
Your code is throwing a NullPointerException in the first statement because input is null, and you have misdiagnosed that as meaning that N is null.
This code is sufficiently different from your actual code that it is not possible to understand what is really going on.
You have made a mistake in the compiling / running / deploying of your code, such that you are running a stale binary.
Your code isn't compilable the way it is now. You can't have multiple public classes in the same file. Also, to access the selected index from a JComboBox, this is what your actionPerformed method should look like.
public void actionPerformed(ActionEvent e) {
JComboBox cb = (JComboBox)e.getSource();
int n = cb.getSelectedIndex();
//etc
}

hangman picture isn't changing

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.

Categories