We help IT Professionals succeed at work.

JAVA GUI Program

javadummy2011
on
I am having trouble formatting my code to run the input boxes as seperate boxes as according to the sample in the attached requirements.  Right now, when you run the program, all 5 colors are inputted into one screen.  The requirements show one input at a time and return error message if one of the colors are wrong.  Can someone please help!

Thanks!!!


Program-7-Requirements.pdf
HollyMccormickProg7.java
Comment
Watch Question

Awarded 2011
Awarded 2011

Commented:
Look - you shoul not add all components to one JFrame
You shoul rather make a loop
and create each time a Dialog window
which should differe only with one parameter - color number
"Color1"," Color2", etc, just add the index dependedn ending to the label

Ths adds everything to one frame:- this is wrong
jpncontrols.add(jlcol1);  // add controls to jpncontrols Panel
jpncontrols.add(jtxcolor1);
jpncontrols.add(jlcol2);
jpncontrols.add(jtxcolor2);
jpncontrols.add(jlcol3);
jpncontrols.add(jtxcolor3);
jpncontrols.add(jlcol4);
jpncontrols.add(jtxcolor4);
jpncontrols.add(jlcol5);
jpncontrols.add(jtxcolor5);
Awarded 2011
Awarded 2011

Commented:

You should make only one label, one textbox, but the lable should be variable and you should
have actionListener attached to the JTextField and after use makes carriage return - you store the color
and vhange the text of the label (the ending number dhoul be changed)
So I was prtobably not write about the loop - you just count
the number of evernts - number of times user types carriage return in the textbox

Let me know if you now understand in which direction to change ?
Awarded 2011
Awarded 2011

Commented:
I would prefer that you do thew major changes - I can then help you to debug it
as for_yan wrote, you have to separate the display and the evaluation to be for one field only.
Also I have seen, when you define the TextFields, you provide it with a string, it might eventually be better if you'd used an integer that specifies how many chars long the field should be.

Using your actual code it should be:

            jtxcolor1 = new JTextField(10);
            jtxcolor2 = new JTextField(10);
            jtxcolor3 = new JTextField(10);
            jtxcolor4 = new JTextField(10);
            jtxcolor5 = new JTextField(10);

This you'd still would have to split up, so you get one window for each line!

Author

Commented:
I think I worked out most of the items above, but just a little confused still on getting them to be in seperate emails.  I had attempted a loop, but just ran into many errors and didn't have time to debug that route.  Then I saw the comment not to do a loop.  Stuck on the variable/integer comment.  See attached.
HollyMccormickProg7.java

Author

Commented:
Meant seperate windows**
Awarded 2011
Awarded 2011

Commented:
OK.

Look at this code - try to execute it.

Make sure you can execute it exactly as it is.

Then go into actionPerformed method and add correct functionality there based
on the check if the color is correct.

Do you understand how the event handling should be working ?


/*************************************************************************
* HollyMccormickProg7.java
*
* Holly McCormick
*
*
**************************************************************************/

import java.awt.*;
import javax.swing.*;
import java.awt.event.*;

public class HollyMccormickProg7 extends JFrame implements ActionListener {
    String colors[] = {"red", "white", "yellow", "green", "blue"}; // array with colors to memorize


private JLabel lblEnter;
private JTextField txtColor;


int count = 0;

public HollyMccormickProg7() {

super("Memory Game");

lblEnter = new JLabel("Enter color number " + (count + 1) + ":");
txtColor = new JTextField(10);
txtColor.addActionListener(this);


String sumCol = "";

for(int j=0; j<colors.length; j++)sumCol += colors[j] + " ";

String Firstmessage = "How good is your memory ? \nTry To Memorize the Sequence :\n" + sumCol;
JOptionPane.showMessageDialog(null, Firstmessage,"Memory Game",1 ); //shows the initial message

Container c = this.getContentPane();
c.setLayout(new FlowLayout());
c.add(lblEnter);
c.add(txtColor);

this.setSize(300,300);
this.setLocation(300,300);
this.setVisible(true);

}



public void actionPerformed(ActionEvent ae){

    if(ae.getSource().equals(txtColor)){
            String inputColor = txtColor.getText().trim();
        if(inputColor.equals(colors[count])){
            //print different message based on whetether it matches or not
        }  else {
           //
        }
        count++;

        lblEnter.setText("Enter color number " + (count + 1) + ":");
        txtColor.setText("");

    }

}


public static void main(String[] args)
{

HollyMccormickProg7 prg = new HollyMccormickProg7();  // create A New Prog7 Window
}
}

Open in new window

Author

Commented:
I guess I don't get it?  I am reviewing textbook again to see if I can put this all together....
Awarded 2011
Awarded 2011

Commented:
In what sense you don't get it.

Did you compile and execute the code I posted ?

Author

Commented:
I have to go and get my son real quick....The code works, but keeps repeating and doesn't give an error message when the color is wrong....Trying to figure out how to incorporate into the code to identify the right color input and error message.....
Awarded 2011
Awarded 2011

Commented:
That is how it should be with this code  as I left these parts for you to complte
When you look at the code of for_yan you will find
a) some comments on where to place the code for the Messages
b) and then you will have to add an end criteria and exit the program.

It should be easy for you to complete - also look at the task description you supplied, some texts are still not 100% like they should be, it is all more cosmetic, but I am sure, once you look into it, you should be able to figure out the last lines of code.

Author

Commented:
I take it not much can be used from my previous code I had worked on all week.... I am working on the code now....

Author

Commented:
Added the correct code....See attached.  I can't figure out why it is printing 6 colors, when it is only 5?
HollyMccormickProg7.java
Awarded 2011
Awarded 2011

Commented:
/*************************************************************************
* HollyMccormickProg7.java
*
* Holly McCormick
*
*
**************************************************************************/

import java.awt.*;
import javax.swing.*;
import java.awt.event.*;

public class HollyMccormickProg7 extends JFrame implements ActionListener {
    String colors[] = {"red", "white", "yellow", "green", "blue"}; // array with colors to memorize


private JLabel lblEnter;
private JTextField txtColor;


int count = 0;

public HollyMccormickProg7() {

super("Memory Game");

lblEnter = new JLabel("Enter color number " + (count + 1) + ":");
txtColor = new JTextField(10);
txtColor.addActionListener(this);


String sumCol = "";

for(int j=0; j<colors.length; j++)sumCol += colors[j] + " ";

String Firstmessage = "How good is your memory ? \nTry To Memorize the Sequence :\n" + sumCol;
JOptionPane.showMessageDialog(null, Firstmessage,"Memory Game",1 ); //shows the initial message

Container c = this.getContentPane();
c.setLayout(new FlowLayout());
c.add(lblEnter);
c.add(txtColor);

this.setSize(300,300);
this.setLocation(300,300);
this.setVisible(true);

}



public void actionPerformed(ActionEvent ae){

    if(ae.getSource().equals(txtColor)){
        String errorMessage = "Sorry -wrong color. Eat more antioxidants";
        String congratsMessage= "Congratulations- your memory is perfect!";
        String title ="Memory Game";
        
            String inputColor = txtColor.getText().trim();
        if(inputColor.equals(colors[count]))  //print different message based on whetether it matches or not
    {
	txtColor.requestFocus();  // if true set the focus to jtxcolor2
        }
        else
        {
		JOptionPane.showMessageDialog(null,errorMessage,title,0 );  // if not display error message
		System.exit(0);  // exit with an error(Says to the System Programm exited with an error
	    }
        count++;
        if(count == 5){
              txtColor.setText("");
          JOptionPane.showMessageDialog(null,congratsMessage,title,0 );
            System.exit(0);
        }

        lblEnter.setText("Enter color number " + (count + 1) + ":");
        txtColor.setText("");
		}
}
    


public static void main(String[] args)
{

HollyMccormickProg7 prg = new HollyMccormickProg7();  // create A New Prog7 Window
}
}

Open in new window

Author

Commented:
Isnt the action listener suppose to be private seeing it is an inner class?  Suppose to be in requirements?  Also, how can I begin the extra credit if the colors are not specified with array values?

Ex. red (1)
blue (2)
so on....

Working the hint button now....
Awarded 2011
Awarded 2011

Commented:
In this case the listener is not an inner class. Rather the same main class works as the listener.

In my mind that is much cleaner and logical way to use the listeners.
Perhpas requires typing a few more chracters, but much more transparent in the code.

actionPerformed cannot be private - it should override public and cannot be narrower - compiler reports error if you make it private

Colors are declared one time in an array at the top of the program - that is how it is - this requirement is satisfied

With hints should be very simple just modify
 txtColor.setText( "");
operator
(also for the first color this operator whould be added right after the txtClolor s created by the constructor)

Author

Commented:
I dont see how modifying the txtColor.setText(""); will help me with the hint seeing the user must select the button "hint" in order for the hint to appear in the text box.

If it is true, then would the following be accurate:

if JButton hint is selected
system.out.println (txtColor.setText(txtColor.charAt(0))); // to release the first letter of the color in the textbox....

Author

Commented:
now I have errors when I added the inner class for active listener....

specifically referring to:  txtColor.addActionListener(this);

see attached.  The requirement is to have it as an inner class (hence the reason why I changed it in the code)
HollyMccormickProg7.java
Awarded 2011
Awarded 2011

Commented:

OK, I spoiled the code the way you wanted with anonymous inner class.

Now add hint button with a new anonymous instance added to it.

This is incorrect:
system.out.println (txtColor.setText(txtColor.charAt(0)));

System.out.println() is printout to console - and has no connection
to changing the contents of textfield



/*************************************************************************
* HollyMccormickProg7.java
*
* Holly McCormick
*
*
**************************************************************************/

import java.awt.*;
import javax.swing.*;
import java.awt.event.*;

public class HollyMccormickProg7 extends JFrame {
    String colors[] = {"red", "white", "yellow", "green", "blue"}; // array with colors to memorize


private JLabel lblEnter;
private JTextField txtColor;


int count = 0;

public HollyMccormickProg7() {

super("Memory Game");

lblEnter = new JLabel("Enter color number " + (count + 1) + ":");

txtColor = new JTextField(10);
txtColor.setText( "");      
txtColor.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent ae){

    if(ae.getSource().equals(txtColor)){
        String errorMessage = "Sorry -wrong color. Eat more antioxidants";
        String congratsMessage= "Congratulations- your memory is perfect!";
        String title ="Memory Game";

            String inputColor = txtColor.getText().trim();
        if(inputColor.equals(colors[count]))  //print different message based on whetether it matches or not
    {
	txtColor.requestFocus();  // if true set the focus to jtxcolor2
        }
        else
        {
		JOptionPane.showMessageDialog(null,errorMessage,title,0 );  // if not display error message
		System.exit(0);  // exit with an error(Says to the System Programm exited with an error
	    }
        count++;
        if(count == 5){
              txtColor.setText("");
          JOptionPane.showMessageDialog(null,congratsMessage,title,0 );
            System.exit(0);
        }

        lblEnter.setText("Enter color number " + (count + 1) + ":");

        txtColor.setText("");
		}
}
});


String sumCol = "";

for(int j=0; j<colors.length; j++)sumCol += colors[j] + " ";

String Firstmessage = "How good is your memory ? \nTry To Memorize the Sequence :\n" + sumCol;
JOptionPane.showMessageDialog(null, Firstmessage,"Memory Game",1 ); //shows the initial message

Container c = this.getContentPane();
c.setLayout(new FlowLayout());
c.add(lblEnter);
c.add(txtColor);

this.setSize(300,300);
this.setLocation(300,300);
this.setVisible(true);

}


    


public static void main(String[] args)
{

HollyMccormickProg7 prg = new HollyMccormickProg7();  // create A New Prog7 Window
}
}

Open in new window

Awarded 2011
Awarded 2011

Commented:
This is with the Next button:

/*************************************************************************
* HollyMccormickProg7.java
*
* Holly McCormick
*
*
**************************************************************************/

import java.awt.*;
import javax.swing.*;
import java.awt.event.*;

public class HollyMccormickProg7 extends JFrame {
    String colors[] = {"red", "white", "yellow", "green", "blue"}; // array with colors to memorize


private JLabel lblEnter;
private JTextField txtColor;
private JButton btnNext;


int count = 0;

public HollyMccormickProg7() {

super("Memory Game");

lblEnter = new JLabel("Enter color number " + (count + 1) + ":");

txtColor = new JTextField(10);
txtColor.setText( "");      
txtColor.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent ae){

    if(ae.getSource().equals(txtColor)){
        String errorMessage = "Sorry -wrong color. Eat more antioxidants";
        String congratsMessage= "Congratulations- your memory is perfect!";
        String title ="Memory Game";

            String inputColor = txtColor.getText().trim();
        if(inputColor.equals(colors[count]))  //print different message based on whetether it matches or not
    {
	txtColor.requestFocus();  // if true set the focus to jtxcolor2
        }
        else
        {
		JOptionPane.showMessageDialog(null,errorMessage,title,0 );  // if not display error message
		System.exit(0);  // exit with an error(Says to the System Programm exited with an error
	    }
        count++;
        if(count == 5){
              txtColor.setText("");
          JOptionPane.showMessageDialog(null,congratsMessage,title,0 );
            System.exit(0);
        }

        lblEnter.setText("Enter color number " + (count + 1) + ":");

        txtColor.setText("");
		}
}
});

 btnNext = new JButton("Next");
btnNext.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent ae){
            if(ae.getSource().equals(btnNext)){
                txtColor.setText(colors[count].charAt(0) + "");

            }


    }

});


String sumCol = "";

for(int j=0; j<colors.length; j++)sumCol += colors[j] + " ";

String Firstmessage = "How good is your memory ? \nTry To Memorize the Sequence :\n" + sumCol;
JOptionPane.showMessageDialog(null, Firstmessage,"Memory Game",1 ); //shows the initial message

Container c = this.getContentPane();
c.setLayout(new FlowLayout());
c.add(lblEnter);
c.add(txtColor);
c.add(btnNext);

this.setSize(300,300);
this.setLocation(300,300);
this.setVisible(true);

}


    


public static void main(String[] args)
{

HollyMccormickProg7 prg = new HollyMccormickProg7();  // create A New Prog7 Window
}
}

Open in new window

Author

Commented:
There is an error in your code!  See my updated code please....
HollyMccormickProg7.java
Awarded 2011
Awarded 2011

Commented:
What is the error in my code - I trued it all waorked before I pasted.
Awarded 2011
Awarded 2011

Commented:
tell me what error you see in my code .
Awarded 2011
Awarded 2011

Commented:
I again tried it - it worked without any problems.

Author

Commented:
check the code I sent you.....
Awarded 2011
Awarded 2011

Commented:
no, I see mistkes even with my eyes - there is no reason for me to correct it n times
The code I sent you is working. If not, post the error, so that I can see.

Author

Commented:
but now i have to redo all my comments because you used an old code if i copy yours!

Author

Commented:
my errors!

C:\Users\McCormickH\Desktop\HollyMccormickProg7\HollyMccormickProg7.java:40: illegal start of expression
public void actionPerformed(ActionEvent ae)
^
C:\Users\McCormickH\Desktop\HollyMccormickProg7\HollyMccormickProg7.java:40: illegal start of expression
public void actionPerformed(ActionEvent ae)
       ^
C:\Users\McCormickH\Desktop\HollyMccormickProg7\HollyMccormickProg7.java:40: ';' expected
public void actionPerformed(ActionEvent ae)
                           ^
C:\Users\McCormickH\Desktop\HollyMccormickProg7\HollyMccormickProg7.java:40: ';' expected
public void actionPerformed(ActionEvent ae)
                                          ^
4 errors

Tool completed with exit code 1
Awarded 2011
Awarded 2011

Commented:
Did you try running you code?
Awarded 2011
Awarded 2011

Commented:
>my errors!

what that means ?

Author

Commented:
I have been!

a noticeable error in your code is:

}
});

Author

Commented:
OMG!  Please look at the attached please and help with the attached!  I am getting too confused and when you make changes and dont add comments, it confuses me even more!  I should have stated that earlier though, so my goof!!!
HollyMccormickProg7.java
Awarded 2011
Awarded 2011

Commented:
It is impossible.

My code works.

I paste it again.

Paste it to your IDE,
compile and execute it - add comments - I'll look through them.

I will not debug it for the fourth time your code.
I see without compiler taht this is wriong in your code already:
      txtColor.addActionListener(new ActionListener());
it cannot end with semicolon, and you need to add actionlistener to Hint, which you ddidn't
and perhaps there are more other mistakes.
Besides, in your last file there was some non-ascii symbol -
i had to retype a lot of your file.

 go ahead - paste my code below - it must work.
If it does not post the error with full words - it just simply cannot be - it works ffor me.
Paste once again - it must work.



/*************************************************************************
* HollyMccormickProg7.java
*
* Holly McCormick
*
*
**************************************************************************/

import java.awt.*;
import javax.swing.*;
import java.awt.event.*;

public class HollyMccormickProg7 extends JFrame {
    String colors[] = {"red", "white", "yellow", "green", "blue"}; // array with colors to memorize


private JLabel lblEnter;
private JTextField txtColor;
private JButton btnNext;


int count = 0;

public HollyMccormickProg7() {

super("Memory Game");

lblEnter = new JLabel("Enter color number " + (count + 1) + ":");

txtColor = new JTextField(10);
txtColor.setText( "");      
txtColor.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent ae){

    if(ae.getSource().equals(txtColor)){
        String errorMessage = "Sorry -wrong color. Eat more antioxidants";
        String congratsMessage= "Congratulations- your memory is perfect!";
        String title ="Memory Game";

            String inputColor = txtColor.getText().trim();
        if(inputColor.equals(colors[count]))  //print different message based on whetether it matches or not
    {
	txtColor.requestFocus();  // if true set the focus to jtxcolor2
        }
        else
        {
		JOptionPane.showMessageDialog(null,errorMessage,title,0 );  // if not display error message
		System.exit(0);  // exit with an error(Says to the System Programm exited with an error
	    }
        count++;
        if(count == 5){
              txtColor.setText("");
          JOptionPane.showMessageDialog(null,congratsMessage,title,0 );
            System.exit(0);
        }

        lblEnter.setText("Enter color number " + (count + 1) + ":");

        txtColor.setText("");
		}
}
});

 btnNext = new JButton("Next");
btnNext.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent ae){
            if(ae.getSource().equals(btnNext)){
                txtColor.setText(colors[count].charAt(0) + "");

            }


    }

});


String sumCol = "";

for(int j=0; j<colors.length; j++)sumCol += colors[j] + " ";

String Firstmessage = "How good is your memory ? \nTry To Memorize the Sequence :\n" + sumCol;
JOptionPane.showMessageDialog(null, Firstmessage,"Memory Game",1 ); //shows the initial message

Container c = this.getContentPane();
c.setLayout(new FlowLayout());
c.add(lblEnter);
c.add(txtColor);
c.add(btnNext);

this.setSize(300,300);
this.setLocation(300,300);
this.setVisible(true);

}


    


public static void main(String[] args)
{

HollyMccormickProg7 prg = new HollyMccormickProg7();  // create A New Prog7 Window
}
}

Open in new window

Author

Commented:
It works, but the button says next???  I have been talking about a hint button.....fixing that now and re-adding all my comments for an assignment due 30 min ago....

For next time....if you change any of my code, please add in a comment so i know what you changed....

I dont just sit here and wait for you to respond with an answer....I constantly re-work my code too on my end, so comments are key for the both of us to see what we have been doing!
Awarded 2011
Awarded 2011

Commented:
Don't constantly re-work - isntead look at my code and try to undersatdn asand ask questions.

I'll modiify to Hint, wait 5 minutes.
Awarded 2011
Awarded 2011
Commented:
This is with Hint.

I cannot comment "every time I change any f your code"

Compare this code with what you sent me in the morning and you'll understand why.

If you need it by cetain time - start earlier - not on Sunday.


/*************************************************************************
* HollyMccormickProg7.java
*
* Holly McCormick
*
*
**************************************************************************/

import java.awt.*;
import javax.swing.*;
import java.awt.event.*;

public class HollyMccormickProg7 extends JFrame {
    String colors[] = {"red", "white", "yellow", "green", "blue"}; // array with colors to memorize


private JLabel lblEnter;
private JTextField txtColor;
private JButton btnHint;


int count = 0;

public HollyMccormickProg7() {

super("Memory Game");

lblEnter = new JLabel("Enter color number " + (count + 1) + ":");

txtColor = new JTextField(10);
txtColor.setText( "");
txtColor.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent ae){

    if(ae.getSource().equals(txtColor)){
        String errorMessage = "Sorry -wrong color. Eat more antioxidants";
        String congratsMessage= "Congratulations- your memory is perfect!";
        String title ="Memory Game";

            String inputColor = txtColor.getText().trim();
        if(inputColor.equals(colors[count]))  //print different message based on whetether it matches or not
    {
	txtColor.requestFocus();  // if true set the focus to jtxcolor2
        }
        else
        {
		JOptionPane.showMessageDialog(null,errorMessage,title,0 );  // if not display error message
		System.exit(0);  // exit with an error(Says to the System Programm exited with an error
	    }
        count++;
        if(count == 5){
              txtColor.setText("");
          JOptionPane.showMessageDialog(null,congratsMessage,title,0 );
            System.exit(0);
        }

        lblEnter.setText("Enter color number " + (count + 1) + ":");

        txtColor.setText("");
		}
}
});

 btnHint = new JButton("Hint");
btnHint.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent ae){
            if(ae.getSource().equals(btnHint)){
                txtColor.setText(colors[count].charAt(0) + "");
                txtColor.requestFocusInWindow();

            }


    }

});


String sumCol = "";

for(int j=0; j<colors.length; j++)sumCol += colors[j] + " ";

String Firstmessage = "How good is your memory ? \nTry To Memorize the Sequence :\n" + sumCol;
JOptionPane.showMessageDialog(null, Firstmessage,"Memory Game",1 ); //shows the initial message

Container c = this.getContentPane();
c.setLayout(new FlowLayout());
c.add(lblEnter);
c.add(txtColor);
c.add(btnHint);

this.setSize(300,300);
this.setLocation(300,300);
this.setVisible(true);

}





public static void main(String[] args)
{

HollyMccormickProg7 prg = new HollyMccormickProg7();  // create A New Prog7 Window
}
}

Open in new window

Author

Commented:
I fixed the hint part myself....

Attached is my final code with comments.  I hope it is accurate seeing I just submitted to my professor.  I apologize this was more rushed this week, but got a final tomorrow for my other class and have been more focused on that....

HollyMccormickProg7.java
Awarded 2011
Awarded 2011

Commented:
It is a pity you didn't use my final version- there was one additional useful operator which requested focus after the
hint was pressed and textbox was populted with the first letter - that was in the requiremnt.

Anyway, if you already sent it, I'll not read your comments - no reason to spend tiime for now.

Next week better start earlier.

Author

Commented:
Would have been useful for you to tell me that when you posted the code, not just now....

I'll fix it and resubmit....Doubt the teacher is going to take my work at all seeing I submitted late, so sorry I wasted both our times....At least you get the points!

Awarded 2011
Awarded 2011

Commented:
I was busy arguing with you on bigger issues....

And I always assume that you are going to follow my rather obvious recommendstions and you are for some reason not doing it.
How could I know that you'll not use my code again.

this last correction is just one additional  line
  txtColor.requestFocusInWindow();
after line
   txtColor.setText(colors[count].charAt(0) + "");


in this piece:

btnHint.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent ae){
            if(ae.getSource().equals(btnHint)){
                txtColor.setText(colors[count].charAt(0) + "");
                txtColor.requestFocusInWindow();

            }


    }

});




Author

Commented:
I think the big problem is that communication on both ends is bad!

Your comments may seem obvious to you, but try to think of the people that don't apply any of this at all in their daily activities.  I would never make a comment such as "rather obvious recommendstions" to someone who is having so much trouble with a subject.  

I apologize I don't understand this stuff, but I just don't!  I have been working my butt off the last 8 weeks and after next week, I am never lookingat/writing another program ever again!

Also, for the record I don't see your responses right away because my internet is slow and sometimes you post too quick, then take back what you said previous and that is confusing!  I know you have to get these points earned and you will, but you have worked with me before and know how confused I get!

Hopefully I will finish writing my last program tomorrow (as much as I can write).  If I post a help question, I hope you can be of assistance to kind of try to communicate better next time.