Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

Page 1 of 2 12 LastLast
Results 1 to 25 of 30

Thread: GUI Calculator: Adding Answer Button? Please Help

  1. #1
    Member Staticity's Avatar
    Join Date
    Jul 2011
    Location
    Texas
    Posts
    105
    My Mood
    Inspired
    Thanks
    3
    Thanked 5 Times in 5 Posts

    Question GUI Calculator: Adding Answer Button? Please Help

    public class event implements ActionListener{
    		public void actionPerformed(ActionEvent operations){
    			String check = operations.getActionCommand();
     
    			if(check.equals("Add")){
     
    			try{
    				field1.setText("");
    				field2.setText("");
    				field3.setText("");
    				popup.setText("" + trademark);
    				double num1, num2, answer;
    				field2.setVisible(false);
    				mainprompt.setText("Enter Numbers Below");
    				prompt1.setText("Number");
    				prompt2.setText("+");
    				prompt3.setText("Number");
    				num1 = Double.parseDouble(field1.getText());
    				num2 = Double.parseDouble(field3.getText());
    				answer = num1 + num2;
    				popup.setText("The sum of " + num1 + " and " + num2 + " is " + answer + ".");
    				mainprompt.setText("Choose Operation Above");
     
    //Reset Fields Once Answer is Received
     
    				prompt1.setText("Number");
    				prompt2.setText("Number");
    				prompt3.setText("Number");
    				field1.setVisible(true);
    				field2.setVisible(true);
    				field3.setVisible(true);
    				field1.setText("");
    				field2.setText("");
    				field3.setText("");
    			}catch(Exception e){
     
    //Fixes another error
    					prompt1.setText("Number");
    					prompt2.setText("+");
    					prompt3.setText("Number");
    					field1.setVisible(true);
    					field2.setVisible(false);
    					field3.setVisible(true);
    					field1.setText("");
    					field2.setText("");
    					field3.setText("");
    			}
    		}
    	}
    }


    This portion of code adds functionality to my "Add" button. I have an "Answer" button created, that currently does nothing. I'm trying to place that "Answer" button within the if statement so that if the user clicks the button, it will return (popup.setText("The sum of " + num1 + " and " + num2 + " is " + answer + ".")).

    If more code is needed, I'll put up my condensed version of my calculator (183 lines).


  2. #2
    Crazy Cat Lady KevinWorkman's Avatar
    Join Date
    Oct 2010
    Location
    Washington, DC
    Posts
    5,424
    My Mood
    Hungover
    Thanks
    144
    Thanked 636 Times in 540 Posts

    Default Re: GUI Calculator: Adding Answer Button? Please Help

    What's your question? What have you tried?
    Useful links: How to Ask Questions the Smart Way | Use Code Tags | Java Tutorials
    Static Void Games - Play indie games, learn from game tutorials and source code, upload your own games!

  3. #3
    Member Staticity's Avatar
    Join Date
    Jul 2011
    Location
    Texas
    Posts
    105
    My Mood
    Inspired
    Thanks
    3
    Thanked 5 Times in 5 Posts

    Default Re: GUI Calculator: Adding Answer Button? Please Help

    Question: How can I add a button, INSIDE the 'if' statement, that will set the text of a JLabel to the answer.

    Attempts:

    1. I've attempted to add an 'if(check.equals("Answer")) statement within the 'if(check.equals("Add"))' statement however, the button's functions act like a reset button (reset all labels, and textfields).

    2. I've also attempted to make an ''if' statement outside the 'if(check.equals("Add"))' statement and simply setting the text to an answer once the button is clicked, but the answer variable is not recognized within this if statement.

    3. Lastly, I've made this program work by using JOptionPane, however I don't want a popup to reveal the answer.. I would like to have my answer displayed within the same window.

  4. #4
    Crazy Cat Lady KevinWorkman's Avatar
    Join Date
    Oct 2010
    Location
    Washington, DC
    Posts
    5,424
    My Mood
    Hungover
    Thanks
    144
    Thanked 636 Times in 540 Posts

    Default Re: GUI Calculator: Adding Answer Button? Please Help

    Sorry, I'm confused- why do you want to add a JButton inside the if statement? Do you mean you want to set the text of a JButton? Or do you mean you want to add the ActionListener to another JButton?
    Useful links: How to Ask Questions the Smart Way | Use Code Tags | Java Tutorials
    Static Void Games - Play indie games, learn from game tutorials and source code, upload your own games!

  5. #5
    Member Staticity's Avatar
    Join Date
    Jul 2011
    Location
    Texas
    Posts
    105
    My Mood
    Inspired
    Thanks
    3
    Thanked 5 Times in 5 Posts

    Default Re: GUI Calculator: Adding Answer Button? Please Help

    I completely worded my question wrong..

    I already have an "Answer" button created. It has an ActionListener as well.. Let me show you how my program works so far.

    User clicks JButton "Add" -> 'Program sets two fields visible for user input' -> User enters numbers into both fields -> User clicks JButton answer -> Nothing Happens.

    I want that JButton "Answer" that I have created to set the text of one of my labels, to the answer.

    Sorry, I'm really trying to make this clear.

    So, knowing I have an Answer Button with an ActionListener, and I also have a JLabel created to show the answer.. My question is. How do I make that Answer Button set the JLabel's text to the answer.

  6. #6
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,042
    Thanks
    63
    Thanked 2,708 Times in 2,658 Posts

    Default Re: GUI Calculator: Adding Answer Button? Please Help

    I want that JButton "Answer" that I have created to set the text of one of my labels, to the answer.
    Add an action listener to the Answer button. In that listener's actionPerformed method, do what you want done when the button is pressed.

    "Answer" button created. It has an ActionListener as well
    What is done in that listener? Why not set the text there?

  7. #7
    Member Staticity's Avatar
    Join Date
    Jul 2011
    Location
    Texas
    Posts
    105
    My Mood
    Inspired
    Thanks
    3
    Thanked 5 Times in 5 Posts

    Default Re: GUI Calculator: Adding Answer Button? Please Help

    Quote Originally Posted by Norm View Post
    Add an action listener to the Answer button. In that listener's actionPerformed method, do what you want done when the button is pressed.
    So create a new Method specifically for the Answer button?

    Quote Originally Posted by Norm
    What is done in that listener? Why not set the text there?
    Because in my If Statement for my Add Button, I have the variable, answer, that cannot be identified in the If Statement for the Answer Button. (My Terminology may be off)
    Last edited by Staticity; July 26th, 2011 at 02:30 PM.
    Simplicity calls for Complexity. Think about it.

  8. #8
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,042
    Thanks
    63
    Thanked 2,708 Times in 2,658 Posts

    Default Re: GUI Calculator: Adding Answer Button? Please Help

    So create a new Method specifically for the Answer button?
    Not a method, a new listener class.
    You will need a reference to the answer variable if you want to use its value.
    If answer is a class reference you can pass it to the constructor for the listener so that the listener can call its methods.

  9. #9
    Member Staticity's Avatar
    Join Date
    Jul 2011
    Location
    Texas
    Posts
    105
    My Mood
    Inspired
    Thanks
    3
    Thanked 5 Times in 5 Posts

    Default Re: GUI Calculator: Adding Answer Button? Please Help

    Quote Originally Posted by Norm View Post
    If answer is a class reference you can pass it to the constructor for the listener so that the listener can call its methods.
    Sorry, but I don't entirely understand this. It is only my 4th day learning Java.
    Simplicity calls for Complexity. Think about it.

  10. #10
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,042
    Thanks
    63
    Thanked 2,708 Times in 2,658 Posts

    Default Re: GUI Calculator: Adding Answer Button? Please Help

    Passing a value to a method or constructor:

    objRef.method(answer); // pass answer to the method

    AClass aClass = new AClass(answer); // pass answer to the constructor

    Example of the Constructor:
    class AClass implements ActionListener {
    <answer's data type here> answer; // define class variable
     
    public AClass(<answer's data type here> answer) {  // the constructor
       this.answer = answer; // save the value for use later
    ...
    // answer can be used by any method in this class
    }

  11. The Following User Says Thank You to Norm For This Useful Post:

    Staticity (July 26th, 2011)

  12. #11
    Member Staticity's Avatar
    Join Date
    Jul 2011
    Location
    Texas
    Posts
    105
    My Mood
    Inspired
    Thanks
    3
    Thanked 5 Times in 5 Posts

    Default Re: GUI Calculator: Adding Answer Button? Please Help

    Thank you very much Norm. However, this did not work for me. I found a less appealing, but simpler way to return the answer... The Program runs like so..

    User clicks JButton "Add" -> 'Program sets two fields visible for user input' -> User enters numbers into both fields -> User clicks JButton "Add" -> JLabel reveals answer.

    This is the original way I made my program to run. I'm completely okay with this, but the idea of an Answer Button is still enticing.. If you want to keep working with me, to try and solve this, that'd be fantastic. But if not, thanks for everything!
    Simplicity calls for Complexity. Think about it.

  13. #12
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,042
    Thanks
    63
    Thanked 2,708 Times in 2,658 Posts

    Default Re: GUI Calculator: Adding Answer Button? Please Help

    As you gain experience you'll be able to create new classes as needed.

  14. #13
    Member
    Join Date
    Jun 2011
    Posts
    182
    My Mood
    Where
    Thanks
    15
    Thanked 8 Times in 8 Posts

    Default Re: GUI Calculator: Adding Answer Button? Please Help

    Quote Originally Posted by Staticity View Post
    Thank you very much Norm. However, this did not work for me. I found a less appealing, but simpler way to return the answer... The Program runs like so..

    User clicks JButton "Add" -> 'Program sets two fields visible for user input' -> User enters numbers into both fields -> User clicks JButton "Add" -> JLabel reveals answer.

    This is the original way I made my program to run. I'm completely okay with this, but the idea of an Answer Button is still enticing.. If you want to keep working with me, to try and solve this, that'd be fantastic. But if not, thanks for everything!
    All you really need is an inner class that implements ActionListener, add the actionPerformed method, and within it, obtain the user's inputs and display the answer. Example:

    [CODE]
    import java.awt.event.*;
    import javax.swing.*;
     
    public class Calculator {
    //GUI code... blah blah blah
    JButton answer = new JButton("Solve");
    answer.addActionListener(new ListenForSolve());
    //more code..
     
    class ListenForSolve implements ActionListener {
    //note it's still within class Calculator's body...
        public void actionPerformed(ActionEvent e) {
            //Obtain user input fields (probably through parsing the contents of a JTextField?)
            //Process inputs (a+b=c)
            //Set JLabel to display answer or set another field/call a method to do so.
        }
    }  //end of ListenForSolve body
    }  // end of Calculator body
    [/CODE]

  15. #14
    Member Staticity's Avatar
    Join Date
    Jul 2011
    Location
    Texas
    Posts
    105
    My Mood
    Inspired
    Thanks
    3
    Thanked 5 Times in 5 Posts

    Default Re: GUI Calculator: Adding Answer Button? Please Help

    Quote Originally Posted by bgroenks96 View Post
    All you really need is an inner class that implements ActionListener, add the actionPerformed method, and within it, obtain the user's inputs and display the answer. Example:
    Thanks, but I already know all of that. That's how my whole Calculator works. Just for some odd reason, I can't find a way to set the Answer Button's functions... I don't know how to explain it any further..

    Quote Originally Posted by Norm
    As you gain experience you'll be able to create new classes as needed
    I surely hope so. Time will only tell, and again.. Thanks.
    Simplicity calls for Complexity. Think about it.

  16. #15
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,042
    Thanks
    63
    Thanked 2,708 Times in 2,658 Posts

    Default Re: GUI Calculator: Adding Answer Button? Please Help

    Just for some odd reason
    That sounds like an error message from a compiler.

  17. #16
    Forum old-timer
    Join Date
    Nov 2008
    Location
    Faversham, Kent, UK
    Posts
    472
    My Mood
    Mellow
    Thanks
    4
    Thanked 58 Times in 54 Posts

    Default Re: GUI Calculator: Adding Answer Button? Please Help

    Quote Originally Posted by Staticity View Post
    Just for some odd reason, I can't find a way to set the Answer Button's functions... I don't know how to explain it any further..
    IIUIC, the Answer button's function is to set some text in a text component. The ActionListener's actionPerformed(..) method is what should do this. If you make the ActionListener an inner class (i.e. declare it inside the class that contains the text component and the button), as bgroenks96 suggested, it will have direct access to that class's member variables, including the text component, so it will be able to set the text into it directly.

  18. #17
    Member Staticity's Avatar
    Join Date
    Jul 2011
    Location
    Texas
    Posts
    105
    My Mood
    Inspired
    Thanks
    3
    Thanked 5 Times in 5 Posts

    Default Re: GUI Calculator: Adding Answer Button? Please Help

    Quote Originally Posted by dlorde View Post
    IIUIC, the Answer button's function is to set some text in a text component. The ActionListener's actionPerformed(..) method is what should do this. If you make the ActionListener an inner class (i.e. declare it inside the class that contains the text component and the button), as bgroenks96 suggested, it will have direct access to that class's member variables, including the text component, so it will be able to set the text into it directly.
    Here is an example of what I need to do. I'm going to make up something...

    import javax.swing.*;
     
    public class test{
    	public static void main(String args[]){
     
    		JButton button1 = new JButton("Bob");
    		JButton button2 = new JButton("Sarah");
    		JButton button3 = new JButton("");
     
    		if(button2.equals("Sarah")){
    			button3.setText("" + answer);
    		}
     
    		if(button1.equals("Bob"));
    		double num1, num2, answer;
    		num1 = 1;
    		num2 = 2;
    		answer = num1 + num2;
    	}
    }

    ^^^
    I need to do that within the Inner Class that implements ActionListener. Or that is what I am attempting to do. I need a way of putting that answer variable within that first if statement.
    Simplicity calls for Complexity. Think about it.

  19. #18
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,042
    Thanks
    63
    Thanked 2,708 Times in 2,658 Posts

    Default Re: GUI Calculator: Adding Answer Button? Please Help

    You need to move ALL of the component definitions OUT of the main method to the class level.
    Nothing that you define in a method will be known outside of the method.
    Defining a variable is not the same as assigning it a value.

    class AClass {
      Component aComp;        // define a variable of type Component
     
      public static void main(String[] args) {
          aComp = new Component();   // assign a value to aComp
          ...
      } // end main()
     
      ...
    } // end class AClass

    Comment on your code:
    if(button1.equals("Bob"));
    Leave the ending ; off this statement. When you code an if statement, after the condition in ()s immediately add a { at the end (or the next line and a } on the next line after that.
     if(some conditions) {
     // Then fill in the stuff to do when true
    }
    Last edited by Norm; July 26th, 2011 at 08:12 PM.

  20. #19
    Member Staticity's Avatar
    Join Date
    Jul 2011
    Location
    Texas
    Posts
    105
    My Mood
    Inspired
    Thanks
    3
    Thanked 5 Times in 5 Posts

    Default Re: GUI Calculator: Adding Answer Button? Please Help

    Quote Originally Posted by Norm View Post
    You need to move ALL of the component definitions OUT of the main method to the class level.
    It was an example. The Main Method is at the bottom of all my code. It's not involved with the class that implements ActionListener.

    Quote Originally Posted by Norm
    Nothing that you define in a method will be known outside of the method.
    Defining a variable is not the same as assigning it a value.
    I understand the difference between defining a variable and assigning it a value :\ I've just been looking for a way to use the variable inside of one if statement, in another if statement.
    Last edited by Staticity; July 26th, 2011 at 08:16 PM.
    Simplicity calls for Complexity. Think about it.

  21. #20
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,042
    Thanks
    63
    Thanked 2,708 Times in 2,658 Posts

    Default Re: GUI Calculator: Adding Answer Button? Please Help

    a way to use the variable inside of one if statement, in another if statement.
    Same type of problem dealing with the scope of a variable. You need to define the variable at a level that the code in both if statements can see it.

  22. #21
    Member Staticity's Avatar
    Join Date
    Jul 2011
    Location
    Texas
    Posts
    105
    My Mood
    Inspired
    Thanks
    3
    Thanked 5 Times in 5 Posts

    Default Re: GUI Calculator: Adding Answer Button? Please Help

    Quote Originally Posted by Norm View Post
    define the variable at a level that the code in both if statements can see it.
    That's my predicament. I don't know how to.
    Simplicity calls for Complexity. Think about it.

  23. #22
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,042
    Thanks
    63
    Thanked 2,708 Times in 2,658 Posts

    Default Re: GUI Calculator: Adding Answer Button? Please Help

    If the variable only needs to be known in the method with the if statements, define the variable at the method level: inside of the {}s that hold the method's statements and not inside of an {}s within the method:
    public void aMethod() {
      int aMethodVar = 0;  // define this variable at the method level
      if (cond) {
         int x = 0;  // define this variable inside of the if{} it goes away at the ending }
     
         // aMethodVar is known here
      } // end of if x is now gone
     
      int anotherVar = 33; // define this variable at the method level
     
      if(cond2) {
         // anotherVar and aMethodVar are known here. x is NOT known
      }
    } // end aMethod()

  24. #23
    Member Staticity's Avatar
    Join Date
    Jul 2011
    Location
    Texas
    Posts
    105
    My Mood
    Inspired
    Thanks
    3
    Thanked 5 Times in 5 Posts

    Default Re: GUI Calculator: Adding Answer Button? Please Help

    Quote Originally Posted by Norm View Post
    If the variable only needs to be known in the method with the if statements, define the variable at the method level: inside of the {}s that hold the method's statements and not inside of an {}s within the method
    I also understand this. but I cannot define the variable at method level because the answer variable is bound to the if statements. In my Calculator, I have 9 different operations that the user can choose from.

    Here is a Fake Example of my issue.

     
     
    public void aMethod(){
    	double answer; //number is never initialized to a value.
     
    	if(add.isSelected()){
    		double num1, num2;
    		answer = num1 + num2;	//answer = num1 + num2.. only in this if statement
    	}
    	if(div.isSelected()){
    		double num1, num2;
    		answer = num1 / num2;	//answer = num1 /num2.. only in this if statement
    	}
    	if(quad.isSelected()){
    		double num1, num2, num3, answer1, answer2; //Quadratic Formula calls for 2 answers(conflicts with method variable)
    		answer1 = ((-num2)+Math.sqrt((num2*num2)-(4*num1*num3)))/(2);
    		answer2 = ((-num2)-Math.sqrt((num2*num2)-(4*num1*num3)))/(2);
    	}
     
    	if(answerbutton.isSelected()){
    		fakelabel.setText("Your answer is" + answer); //answer still has no value, can't set text.
    	}
    }
    Last edited by Staticity; July 27th, 2011 at 12:11 PM.
    Simplicity calls for Complexity. Think about it.

  25. #24
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,042
    Thanks
    63
    Thanked 2,708 Times in 2,658 Posts

    Default Re: GUI Calculator: Adding Answer Button? Please Help

    the answer variable is bound to the if statements.
    This doesn't make any sense to me. The variable answer is a method level variable.
    I have no idea what you mean by "is bound to". Can you explain?

    Your simple example seems to have another variable: answer that is an object. See:
    if(answer.isSelected()){

  26. #25
    Member Staticity's Avatar
    Join Date
    Jul 2011
    Location
    Texas
    Posts
    105
    My Mood
    Inspired
    Thanks
    3
    Thanked 5 Times in 5 Posts

    Default Re: GUI Calculator: Adding Answer Button? Please Help

    Quote Originally Posted by Norm View Post
    This doesn't make any sense to me. The variable answer is a method level variable.
    I have no idea what you mean by "is bound to". Can you explain?{
    In the if statements, the variable answer is initialized. Outside the if statements, it has no value. This is what I was trying to say by "is bound to".

    Quote Originally Posted by NORM
    Your simple example seems to have another variable: answer that is an object. See:
    if(answer.isSelected())
    I fixed that just now.. It was supposed to be "answerbutton".
    Simplicity calls for Complexity. Think about it.

Page 1 of 2 12 LastLast

Similar Threads

  1. Replies: 1
    Last Post: July 20th, 2011, 08:03 AM
  2. need answer for these
    By satishbs in forum Java Theory & Questions
    Replies: 2
    Last Post: April 15th, 2011, 01:46 AM
  3. Adding Radio Button Values
    By bazazu in forum What's Wrong With My Code?
    Replies: 6
    Last Post: November 13th, 2010, 10:41 AM
  4. Adding fixed size picture and button to panel
    By Javabeginner in forum AWT / Java Swing
    Replies: 10
    Last Post: August 23rd, 2010, 06:07 PM
  5. [SOLVED] Problem with a tutorial program(Adding the answer of two squared numbers together)
    By Melawe in forum What's Wrong With My Code?
    Replies: 20
    Last Post: April 7th, 2010, 09:03 AM