11 Replies - 546 Views - Last Post: 22 December 2013 - 03:26 PM Rate Topic: -----

#1 streek405  Icon User is offline

  • D.I.C Addict

Reputation: 10
  • View blog
  • Posts: 535
  • Joined: 10-March 13

How to check if the user pressed a button

Posted 19 December 2013 - 07:11 PM

Im writing a GUI program and I was wondering how I can check to see if the user pressed a button, like "YES" or "OK".
Is This A Good Question/Topic? 0
  • +

Replies To: How to check if the user pressed a button

#2 ChrisNt  Icon User is online

  • D.I.C Addict

Reputation: 200
  • View blog
  • Posts: 621
  • Joined: 31-July 13

Re: How to check if the user pressed a button

Posted 19 December 2013 - 07:43 PM

You should add actionListener to your JButton,you could have an inner class which implements ActionListener .

Listener listener = new Listener();
yesBtn.addActionListener(listener);
okBtn.addActionListener(listener);



class Listener implements ActionListener {

      public void actionPerformed(ActionEvent e) {
             
             Object source = e.getSource();
            
             if( source == yesBtn ) {
                 System.out.println("yes button pressed");
             }
             else if( source == okBtn) {
                 System.out.println("ok button pressed");
             }
      }
}


or a faster way would be anonymous class

okBtn.addActionListener(new ActionListener() {

      public void actionPerformed(ActionEvent e) {
             System.out.println("ok was pressed");
      }
});

This post has been edited by ChrisNt: 19 December 2013 - 07:45 PM

Was This Post Helpful? 1
  • +
  • -

#3 streek405  Icon User is offline

  • D.I.C Addict

Reputation: 10
  • View blog
  • Posts: 535
  • Joined: 10-March 13

Re: How to check if the user pressed a button

Posted 19 December 2013 - 07:54 PM

Ok thanks! I've always wondered what action listener was used for...

EDIT* WAIT! What does this do?
Object source = e.getSource();
Also, can I just have any class implement ActionListener or must I make a class like the above one?

This post has been edited by andrewsw: 20 December 2013 - 04:27 AM
Reason for edit:: Removed previous quote

Was This Post Helpful? 0
  • +
  • -

#4 CY5  Icon User is offline

  • D.I.C Regular

Reputation: 12
  • View blog
  • Posts: 336
  • Joined: 28-September 12

Re: How to check if the user pressed a button

Posted 19 December 2013 - 11:40 PM

Object source = e.getSource();

Returns:
The object on which the Event initially occurred.

getSource()
Was This Post Helpful? 0
  • +
  • -

#5 streek405  Icon User is offline

  • D.I.C Addict

Reputation: 10
  • View blog
  • Posts: 535
  • Joined: 10-March 13

Re: How to check if the user pressed a button

Posted 21 December 2013 - 04:06 PM

View PostChrisNt, on 19 December 2013 - 07:43 PM, said:

Listener listener = new Listener();
yesBtn.addActionListener(listener);
okBtn.addActionListener(listener);


If Im using the premade buttons, like from this
JOptionPane.YES_NO_OPTION
I wouldnt need to create new buttons right, i.e. the 3 lines of code from above?
Was This Post Helpful? 0
  • +
  • -

#6 streek405  Icon User is offline

  • D.I.C Addict

Reputation: 10
  • View blog
  • Posts: 535
  • Joined: 10-March 13

Re: How to check if the user pressed a button

Posted 21 December 2013 - 04:51 PM

This post kinda follows up from my last post. I tried incorporating the suggestions that one user stated but I do not think it would work for this situation, but I could be wrong...

Anyways, I'm just trying to check to see if the user pressed the YES, NO, OK, or CANCEL.

I currently am getting some compiler errors though, such as:
OkListener is not abstract and does not override abstract method actionPerformed(ActionEvent) in ActionListener


which is pointing to the OKListener class, line 41.

and a bunch of "cannot find symbol" errors for lines 43, 47, 57, 60.

My apologizes for this being messy.

/*
This program will teach the user some of the basics, but
foundational materials of Calculus and Algebra.
*/

   import java.awt.FlowLayout;//the lay out of the GUI
   import javax.swing.JFrame;//features of the GUI
   import javax.swing.JOptionPane;
   import java.awt.event.*;//action listener stuff?

   class CalculusTutorial extends JFrame{	
   
   //method for basic derivatives
      public void Derivatives(){
         JOptionPane.showConfirmDialog(null, "Example 1: Derive 24 \n Since 24 is a constant without a variable the derivative is 0"
            +"\nExample 2: Derive 5X^2 \nRecall that the formula for the derivative of X^n is n*X^(n-1) \nSo first we multiply the power"
            +" of the variable, in this case 2, with the constant infront, 5. 5 * 2 = 10. Then, you subtract the power by 1. "
            +"\n2 - 1 = 1. So the derivative of 5X^2 is 10X. \n Example 3: Derive 13Y \n Since the power of Y is 1, we get 13 * 1 which is 13"
            +" then we subract the power of Y by 1. 1 - 1 = 0. ANYTHING to the power of 0 becomes 1. \nSo now we have 13*1*Y^(1-1) which is "
            +" 13Y^0 which simplifies to 13! \n\n Would you like a few more examples? Please click YES or NO.", "Examples of Derivatives",
            JOptionPane.YES_NO_OPTION);
      //special case for 'e'
      }		
   
   //method for basic integrals
      public void Integrals(){
      
      //special case for 'e'
      }
   } 

   class AlgebraTutorial extends JFrame{
   
   //non variable multiplication/division
   
   //then with variables
   
   //test if they know powers
   
   }
   class OkListener implements ActionListener{
   
		TestMathTutorial source1 = event.getSource();//NOT SURE IF THIS IS RIGHT	
		
      public boolean actionPerformed(ActionEvent event){
            
         if(source == okBtn){
            return true;
         }
         else{ //cancel was pressed
            return false;
         }
      }
   }
   class YesListener implements ActionListener{
	
		TestMathTutorial source2 = event.getSource();//NOT SURE IF THIS IS RIGHT	
   
      public boolean actionPerformed(ActionEvent event){
         if(source == yesBtn){
            return true;
         }
         else{ //no was pressed
            return false;
         }
      }
   }
	
   class TestMathTutorial{
   
      public static void main(String[] args){
      //create the objects
         CalculusTutorial calc = new CalculusTutorial();
         AlgebraTutorial algebra = new AlgebraTutorial();
      	
         OkListener okList = new OkListener();
         YesListener yesList = new YesListener();
      
         String cal = "calculus";
         String alg = "algebra";
         String deriv = "derivatives";
         String intg = "integrals";
         String withOut = "without";
         String with = "with";
         String y = "yes";
         String n = "no";
      
      //ask the user which topic they will like to learn
         String introQuestion = JOptionPane.showInputDialog("Hello. What topic would you like to learn: Algebra or Calculus? "
            +"Please enter your choice below:");
      // calc
         if(introQuestion.equalsIgnoreCase(cal)){
            String subQuestion = JOptionPane.showInputDialog("Which topic of Calculus would you like to learn: "
               +"Derivates or Integrals? Please enter your choice below:");
            if(subQuestion.equalsIgnoreCase(intg)){
               int integralIntro = JOptionPane.showConfirmDialog(null, "Today you will learn the basics for integrating. "
                  +"If you want to integrate X^n \nthen the formula for this problem is this:  X^(n+1)/(n+1). Let 'X' represent a "
                  +"\nvariable and 'n' represent a number, or some constant. \n\n                     Would you like to see an example of this?",
                  "Intro to Integrals", JOptionPane.YES_NO_OPTION);
            //check if they pressed yes or no
               if(yesList.actionPerformed() == true){//yes was pressed. I KNOW THE PARAMETER SHOULD NOT BE EMPTY, BUT I //DO NOT KNOW FIX IT...
                  System.out.println("YES...");
               }
               else{
                  System.out.println("NO...");
               }
            }
            else if(subQuestion.equalsIgnoreCase(deriv)){
               int derivativeIntro = JOptionPane.showConfirmDialog(null, "Today you will learn the basics for differentiating, or deriving. "
                  +"\nIf you have X^n, where 'X' is some variable and 'n' is some constant,\nor a number, then the formula for "
                  +"differentiating X^n is: n*X^(n-1).\nIn addition to that, if you derive a constant without a varible, then \nthe derivative"
                  +" is zero. This applies for ANY constant by itself. \n\n               Would you like to see an example of this?", "Intro to Derivatives",
                  JOptionPane.YES_NO_OPTION);
            	//check if they pressed yes or no. if yes call object
               if(yesList.actionPerformed() == true){//yes was pressed
                  System.out.println("YES...");
               }
               else{
                  System.out.println("NO...");
               }
            }
            
            else{
               JOptionPane.showMessageDialog(null, "I am sorry, but that is an invalid option. Please restart from the beginning",
                  "Error", JOptionPane.PLAIN_MESSAGE);
            	//check if they pressed yes or no. if yes call object
               if(yesList.actionPerformed() == true){//yes was pressed
                  System.out.println("YES...");
               }
               else{
                  System.out.println("NO...");
               }
            }
         } 
         // algebra
         else if(introQuestion.equalsIgnoreCase(alg)){
         
            JOptionPane.showConfirmDialog(null, "The goal this topic is to always get the variables on one side and the numbers, or constants,"
               +"on the other side of the equal sign. \nI will show you some examples. Please press 'ok' to continue", "Intro to Algebra",
               JOptionPane.OK_CANCEL_OPTION);
         //if they pressed yes, go to the object
         }
         
         else{
            JOptionPane.showConfirmDialog(null, "I am sorry, but that is an invalid option. Please restart the program",
               "Error", JOptionPane.PLAIN_MESSAGE);
         }
      }
   }


This post has been edited by streek405: 21 December 2013 - 04:53 PM

Was This Post Helpful? 0
  • +
  • -

#7 macosxnerd101  Icon User is offline

  • Self-Trained Economist
  • member icon




Reputation: 10363
  • View blog
  • Posts: 38,355
  • Joined: 27-December 08

Re: How to check if the user pressed a button

Posted 21 December 2013 - 04:54 PM

Duplicate threads merged. Please avoid duplicate posting.
Was This Post Helpful? 0
  • +
  • -

#8 andrewsw  Icon User is online

  • Fire giant boob nipple gun!
  • member icon

Reputation: 3175
  • View blog
  • Posts: 10,625
  • Joined: 12-December 12

Re: How to check if the user pressed a button

Posted 21 December 2013 - 06:57 PM

public boolean actionPerformed(ActionEvent event){

This should be public void which is why you receive the first error message. (Events don't return values - where would they go?)

TestMathTutorial source2 = event.getSource();//NOT SURE IF THIS IS RIGHT

No, because event doesn't exist at that line, it is available within the actionPerformed().

However, if you are using JOptionPane.showConfirmDialog (and related dialogs) then you don't need action-listeners. This dialog, for example, returns an integer value that you can store, and check, to see which button was clicked.

The problem is that you only indicated that you were using these dialogs in post #5. The information you were given prior to this is not relevant for these simple dialogs.

This post has been edited by andrewsw: 21 December 2013 - 07:00 PM

Was This Post Helpful? 1
  • +
  • -

#9 streek405  Icon User is offline

  • D.I.C Addict

Reputation: 10
  • View blog
  • Posts: 535
  • Joined: 10-March 13

Re: How to check if the user pressed a button

Posted 22 December 2013 - 12:38 PM

View Postandrewsw, on 21 December 2013 - 06:57 PM, said:

However, if you are using JOptionPane.showConfirmDialog (and related dialogs) then you don't need action-listeners. This dialog, for example, returns an integer value that you can store, and check, to see which button was clicked.

Whoa, I never knew that it returned an int! But how do I know or assign the integer?
Would I do something like this for this line of code?
  int integralIntro = JOptionPane.showConfirmDialog(null, "Today you will learn the basics for integrating. "
                  +"If you want to integrate X^n \nthen the formula for this problem is this:  X^(n+1)/(n+1). Let 'X' represent a "
                  +"\nvariable and 'n' represent a number, or some constant. \n\n                     Would you like to see an example of this?",
                  "Intro to Integrals", JOptionPane.YES_NO_OPTION);


and then
return integralIntro
?

Hmm it all makes sense now why confirm dialogs are an int type...oh Java you...

Quote

The problem is that you only indicated that you were using these dialogs in post #5. The information you were given prior to this is not relevant for these simple dialogs.

So the only time I would use the above info for actionListeners is if I am NOT using built in stuff, but rather making it on my own?
Was This Post Helpful? 0
  • +
  • -

#10 andrewsw  Icon User is online

  • Fire giant boob nipple gun!
  • member icon

Reputation: 3175
  • View blog
  • Posts: 10,625
  • Joined: 12-December 12

Re: How to check if the user pressed a button

Posted 22 December 2013 - 12:46 PM

Quote

So the only time I would use the above info for actionListeners is if I am NOT using built in stuff, but rather making it on my own?

Yes.

To clarify, the showXxxDialogs are special built-in, modal, forms. You don't need to do anything with them other than store, and check, the value they return. For any forms you build yourself (using Swing or other libraries) you need to create, and attach, the event-procedures (actionListeners) that respond to events, such as clicking a button.
Was This Post Helpful? 1
  • +
  • -

#11 streek405  Icon User is offline

  • D.I.C Addict

Reputation: 10
  • View blog
  • Posts: 535
  • Joined: 10-March 13

Re: How to check if the user pressed a button

Posted 22 December 2013 - 12:53 PM

View Postandrewsw, on 22 December 2013 - 12:46 PM, said:

Quote

So the only time I would use the above info for actionListeners is if I am NOT using built in stuff, but rather making it on my own?

Yes.

To clarify, the showXxxDialogs are special built-in, modal, forms. You don't need to do anything with them other than store, and check, the value they return. For any forms you build yourself (using Swing or other libraries) you need to create, and attach, the event-procedures (actionListeners) that respond to events, such as clicking a button.

Ok thank you very much! You have no idea how happy I am right now! ^0^
Was This Post Helpful? 0
  • +
  • -

#12 andrewsw  Icon User is online

  • Fire giant boob nipple gun!
  • member icon

Reputation: 3175
  • View blog
  • Posts: 10,625
  • Joined: 12-December 12

Re: How to check if the user pressed a button

Posted 22 December 2013 - 03:26 PM

You are welcome ;)
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1