How do you add an ActionListener onto a JButton in Java











up vote
25
down vote

favorite
8












private JButton jBtnDrawCircle = new JButton("Circle");
private JButton jBtnDrawSquare = new JButton("Square");
private JButton jBtnDrawTriangle = new JButton("Triangle");
private JButton jBtnSelection = new JButton("Selection");


How do I add action listeners to these buttons, so that from a main method I can call actionperformed on them, so when they are clicked I can call them in my program?










share|improve this question




























    up vote
    25
    down vote

    favorite
    8












    private JButton jBtnDrawCircle = new JButton("Circle");
    private JButton jBtnDrawSquare = new JButton("Square");
    private JButton jBtnDrawTriangle = new JButton("Triangle");
    private JButton jBtnSelection = new JButton("Selection");


    How do I add action listeners to these buttons, so that from a main method I can call actionperformed on them, so when they are clicked I can call them in my program?










    share|improve this question


























      up vote
      25
      down vote

      favorite
      8









      up vote
      25
      down vote

      favorite
      8






      8





      private JButton jBtnDrawCircle = new JButton("Circle");
      private JButton jBtnDrawSquare = new JButton("Square");
      private JButton jBtnDrawTriangle = new JButton("Triangle");
      private JButton jBtnSelection = new JButton("Selection");


      How do I add action listeners to these buttons, so that from a main method I can call actionperformed on them, so when they are clicked I can call them in my program?










      share|improve this question















      private JButton jBtnDrawCircle = new JButton("Circle");
      private JButton jBtnDrawSquare = new JButton("Square");
      private JButton jBtnDrawTriangle = new JButton("Triangle");
      private JButton jBtnSelection = new JButton("Selection");


      How do I add action listeners to these buttons, so that from a main method I can call actionperformed on them, so when they are clicked I can call them in my program?







      java swing user-interface jbutton actionlistener






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited Jul 27 '17 at 15:35









      montrealist

      2,94373547




      2,94373547










      asked Nov 12 '08 at 18:40









      user37037

      126123




      126123
























          4 Answers
          4






          active

          oldest

          votes

















          up vote
          45
          down vote













          Two ways:



          1. Implement ActionListener in your class, then use jBtnSelection.addActionListener(this); Later, you'll have to define a menthod, public void actionPerformed(ActionEvent e). However, doing this for multiple buttons can be confusing, because the actionPerformed method will have to check the source of each event (e.getSource()) to see which button it came from.



          2. Use anonymous inner classes:



          jBtnSelection.addActionListener(new ActionListener() { 
          public void actionPerformed(ActionEvent e) {
          selectionButtonPressed();
          }
          } );


          Later, you'll have to define selectionButtonPressed().
          This works better when you have multiple buttons, because your calls to individual methods for handling the actions are right next to the definition of the button.



          The second method also allows you to call the selection method directly. In this case, you could call selectionButtonPressed() if some other action happens, too - like, when a timer goes off or something (but in this case, your method would be named something different, maybe selectionChanged()).






          share|improve this answer























          • you solved my confusion, thanks a lot
            – Space Rocker
            Dec 30 '10 at 4:12










          • @Sara - Glad that helped! If you can think of any further clarifications, I'll be happy to add them to this answer.
            – David Koelle
            Jan 4 '11 at 4:41










          • When someone asks: How can a component handle its own events? is the answer to that question to use anonymous inner classes like you here showed?
            – Marko Kitonjics
            Feb 24 '16 at 10:13










          • Not necessarily. You could have a custom component (e.g., something that extends JComponent) and also implements ActionListener, MouseListener, etc.
            – David Koelle
            Feb 24 '16 at 14:18










          • Don't you have to add @Override for actionPerformed?
            – DoesData
            Nov 3 '17 at 13:47


















          up vote
          7
          down vote













          Your best bet is to review the Java Swing tutorials, specifically the tutorial on Buttons.



          The short code snippet is:



          jBtnDrawCircle.addActionListener( /*class that implements ActionListener*/ );





          share|improve this answer




























            up vote
            1
            down vote













            I'm didn't totally follow, but to add an action listener, you just call addActionListener (from Abstract Button). If this doesn't totally answer your question, can you provide some more details?






            share|improve this answer




























              up vote
              1
              down vote













              idk if this works but I made the variable names



              public abstract class beep implements ActionListener {
              public static void main(String args) {
              JFrame f = new JFrame("beeper");
              JButton button = new JButton("Beep me");
              f.setVisible(true);
              f.setSize(300, 200);
              f.add(button);
              button.addActionListener(new ActionListener() {
              public void actionPerformed(ActionEvent e) {
              //insert code here
              }
              } );

              }


              }






              share|improve this answer





















                Your Answer






                StackExchange.ifUsing("editor", function () {
                StackExchange.using("externalEditor", function () {
                StackExchange.using("snippets", function () {
                StackExchange.snippets.init();
                });
                });
                }, "code-snippets");

                StackExchange.ready(function() {
                var channelOptions = {
                tags: "".split(" "),
                id: "1"
                };
                initTagRenderer("".split(" "), "".split(" "), channelOptions);

                StackExchange.using("externalEditor", function() {
                // Have to fire editor after snippets, if snippets enabled
                if (StackExchange.settings.snippets.snippetsEnabled) {
                StackExchange.using("snippets", function() {
                createEditor();
                });
                }
                else {
                createEditor();
                }
                });

                function createEditor() {
                StackExchange.prepareEditor({
                heartbeatType: 'answer',
                convertImagesToLinks: true,
                noModals: true,
                showLowRepImageUploadWarning: true,
                reputationToPostImages: 10,
                bindNavPrevention: true,
                postfix: "",
                imageUploader: {
                brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
                contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
                allowUrls: true
                },
                onDemand: true,
                discardSelector: ".discard-answer"
                ,immediatelyShowMarkdownHelp:true
                });


                }
                });














                draft saved

                draft discarded


















                StackExchange.ready(
                function () {
                StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f284899%2fhow-do-you-add-an-actionlistener-onto-a-jbutton-in-java%23new-answer', 'question_page');
                }
                );

                Post as a guest















                Required, but never shown

























                4 Answers
                4






                active

                oldest

                votes








                4 Answers
                4






                active

                oldest

                votes









                active

                oldest

                votes






                active

                oldest

                votes








                up vote
                45
                down vote













                Two ways:



                1. Implement ActionListener in your class, then use jBtnSelection.addActionListener(this); Later, you'll have to define a menthod, public void actionPerformed(ActionEvent e). However, doing this for multiple buttons can be confusing, because the actionPerformed method will have to check the source of each event (e.getSource()) to see which button it came from.



                2. Use anonymous inner classes:



                jBtnSelection.addActionListener(new ActionListener() { 
                public void actionPerformed(ActionEvent e) {
                selectionButtonPressed();
                }
                } );


                Later, you'll have to define selectionButtonPressed().
                This works better when you have multiple buttons, because your calls to individual methods for handling the actions are right next to the definition of the button.



                The second method also allows you to call the selection method directly. In this case, you could call selectionButtonPressed() if some other action happens, too - like, when a timer goes off or something (but in this case, your method would be named something different, maybe selectionChanged()).






                share|improve this answer























                • you solved my confusion, thanks a lot
                  – Space Rocker
                  Dec 30 '10 at 4:12










                • @Sara - Glad that helped! If you can think of any further clarifications, I'll be happy to add them to this answer.
                  – David Koelle
                  Jan 4 '11 at 4:41










                • When someone asks: How can a component handle its own events? is the answer to that question to use anonymous inner classes like you here showed?
                  – Marko Kitonjics
                  Feb 24 '16 at 10:13










                • Not necessarily. You could have a custom component (e.g., something that extends JComponent) and also implements ActionListener, MouseListener, etc.
                  – David Koelle
                  Feb 24 '16 at 14:18










                • Don't you have to add @Override for actionPerformed?
                  – DoesData
                  Nov 3 '17 at 13:47















                up vote
                45
                down vote













                Two ways:



                1. Implement ActionListener in your class, then use jBtnSelection.addActionListener(this); Later, you'll have to define a menthod, public void actionPerformed(ActionEvent e). However, doing this for multiple buttons can be confusing, because the actionPerformed method will have to check the source of each event (e.getSource()) to see which button it came from.



                2. Use anonymous inner classes:



                jBtnSelection.addActionListener(new ActionListener() { 
                public void actionPerformed(ActionEvent e) {
                selectionButtonPressed();
                }
                } );


                Later, you'll have to define selectionButtonPressed().
                This works better when you have multiple buttons, because your calls to individual methods for handling the actions are right next to the definition of the button.



                The second method also allows you to call the selection method directly. In this case, you could call selectionButtonPressed() if some other action happens, too - like, when a timer goes off or something (but in this case, your method would be named something different, maybe selectionChanged()).






                share|improve this answer























                • you solved my confusion, thanks a lot
                  – Space Rocker
                  Dec 30 '10 at 4:12










                • @Sara - Glad that helped! If you can think of any further clarifications, I'll be happy to add them to this answer.
                  – David Koelle
                  Jan 4 '11 at 4:41










                • When someone asks: How can a component handle its own events? is the answer to that question to use anonymous inner classes like you here showed?
                  – Marko Kitonjics
                  Feb 24 '16 at 10:13










                • Not necessarily. You could have a custom component (e.g., something that extends JComponent) and also implements ActionListener, MouseListener, etc.
                  – David Koelle
                  Feb 24 '16 at 14:18










                • Don't you have to add @Override for actionPerformed?
                  – DoesData
                  Nov 3 '17 at 13:47













                up vote
                45
                down vote










                up vote
                45
                down vote









                Two ways:



                1. Implement ActionListener in your class, then use jBtnSelection.addActionListener(this); Later, you'll have to define a menthod, public void actionPerformed(ActionEvent e). However, doing this for multiple buttons can be confusing, because the actionPerformed method will have to check the source of each event (e.getSource()) to see which button it came from.



                2. Use anonymous inner classes:



                jBtnSelection.addActionListener(new ActionListener() { 
                public void actionPerformed(ActionEvent e) {
                selectionButtonPressed();
                }
                } );


                Later, you'll have to define selectionButtonPressed().
                This works better when you have multiple buttons, because your calls to individual methods for handling the actions are right next to the definition of the button.



                The second method also allows you to call the selection method directly. In this case, you could call selectionButtonPressed() if some other action happens, too - like, when a timer goes off or something (but in this case, your method would be named something different, maybe selectionChanged()).






                share|improve this answer














                Two ways:



                1. Implement ActionListener in your class, then use jBtnSelection.addActionListener(this); Later, you'll have to define a menthod, public void actionPerformed(ActionEvent e). However, doing this for multiple buttons can be confusing, because the actionPerformed method will have to check the source of each event (e.getSource()) to see which button it came from.



                2. Use anonymous inner classes:



                jBtnSelection.addActionListener(new ActionListener() { 
                public void actionPerformed(ActionEvent e) {
                selectionButtonPressed();
                }
                } );


                Later, you'll have to define selectionButtonPressed().
                This works better when you have multiple buttons, because your calls to individual methods for handling the actions are right next to the definition of the button.



                The second method also allows you to call the selection method directly. In this case, you could call selectionButtonPressed() if some other action happens, too - like, when a timer goes off or something (but in this case, your method would be named something different, maybe selectionChanged()).







                share|improve this answer














                share|improve this answer



                share|improve this answer








                edited Mar 21 '14 at 16:26

























                answered Nov 12 '08 at 18:49









                David Koelle

                14.1k2184123




                14.1k2184123












                • you solved my confusion, thanks a lot
                  – Space Rocker
                  Dec 30 '10 at 4:12










                • @Sara - Glad that helped! If you can think of any further clarifications, I'll be happy to add them to this answer.
                  – David Koelle
                  Jan 4 '11 at 4:41










                • When someone asks: How can a component handle its own events? is the answer to that question to use anonymous inner classes like you here showed?
                  – Marko Kitonjics
                  Feb 24 '16 at 10:13










                • Not necessarily. You could have a custom component (e.g., something that extends JComponent) and also implements ActionListener, MouseListener, etc.
                  – David Koelle
                  Feb 24 '16 at 14:18










                • Don't you have to add @Override for actionPerformed?
                  – DoesData
                  Nov 3 '17 at 13:47


















                • you solved my confusion, thanks a lot
                  – Space Rocker
                  Dec 30 '10 at 4:12










                • @Sara - Glad that helped! If you can think of any further clarifications, I'll be happy to add them to this answer.
                  – David Koelle
                  Jan 4 '11 at 4:41










                • When someone asks: How can a component handle its own events? is the answer to that question to use anonymous inner classes like you here showed?
                  – Marko Kitonjics
                  Feb 24 '16 at 10:13










                • Not necessarily. You could have a custom component (e.g., something that extends JComponent) and also implements ActionListener, MouseListener, etc.
                  – David Koelle
                  Feb 24 '16 at 14:18










                • Don't you have to add @Override for actionPerformed?
                  – DoesData
                  Nov 3 '17 at 13:47
















                you solved my confusion, thanks a lot
                – Space Rocker
                Dec 30 '10 at 4:12




                you solved my confusion, thanks a lot
                – Space Rocker
                Dec 30 '10 at 4:12












                @Sara - Glad that helped! If you can think of any further clarifications, I'll be happy to add them to this answer.
                – David Koelle
                Jan 4 '11 at 4:41




                @Sara - Glad that helped! If you can think of any further clarifications, I'll be happy to add them to this answer.
                – David Koelle
                Jan 4 '11 at 4:41












                When someone asks: How can a component handle its own events? is the answer to that question to use anonymous inner classes like you here showed?
                – Marko Kitonjics
                Feb 24 '16 at 10:13




                When someone asks: How can a component handle its own events? is the answer to that question to use anonymous inner classes like you here showed?
                – Marko Kitonjics
                Feb 24 '16 at 10:13












                Not necessarily. You could have a custom component (e.g., something that extends JComponent) and also implements ActionListener, MouseListener, etc.
                – David Koelle
                Feb 24 '16 at 14:18




                Not necessarily. You could have a custom component (e.g., something that extends JComponent) and also implements ActionListener, MouseListener, etc.
                – David Koelle
                Feb 24 '16 at 14:18












                Don't you have to add @Override for actionPerformed?
                – DoesData
                Nov 3 '17 at 13:47




                Don't you have to add @Override for actionPerformed?
                – DoesData
                Nov 3 '17 at 13:47












                up vote
                7
                down vote













                Your best bet is to review the Java Swing tutorials, specifically the tutorial on Buttons.



                The short code snippet is:



                jBtnDrawCircle.addActionListener( /*class that implements ActionListener*/ );





                share|improve this answer

























                  up vote
                  7
                  down vote













                  Your best bet is to review the Java Swing tutorials, specifically the tutorial on Buttons.



                  The short code snippet is:



                  jBtnDrawCircle.addActionListener( /*class that implements ActionListener*/ );





                  share|improve this answer























                    up vote
                    7
                    down vote










                    up vote
                    7
                    down vote









                    Your best bet is to review the Java Swing tutorials, specifically the tutorial on Buttons.



                    The short code snippet is:



                    jBtnDrawCircle.addActionListener( /*class that implements ActionListener*/ );





                    share|improve this answer












                    Your best bet is to review the Java Swing tutorials, specifically the tutorial on Buttons.



                    The short code snippet is:



                    jBtnDrawCircle.addActionListener( /*class that implements ActionListener*/ );






                    share|improve this answer












                    share|improve this answer



                    share|improve this answer










                    answered Nov 12 '08 at 18:46









                    Alex B

                    18.2k125683




                    18.2k125683






















                        up vote
                        1
                        down vote













                        I'm didn't totally follow, but to add an action listener, you just call addActionListener (from Abstract Button). If this doesn't totally answer your question, can you provide some more details?






                        share|improve this answer

























                          up vote
                          1
                          down vote













                          I'm didn't totally follow, but to add an action listener, you just call addActionListener (from Abstract Button). If this doesn't totally answer your question, can you provide some more details?






                          share|improve this answer























                            up vote
                            1
                            down vote










                            up vote
                            1
                            down vote









                            I'm didn't totally follow, but to add an action listener, you just call addActionListener (from Abstract Button). If this doesn't totally answer your question, can you provide some more details?






                            share|improve this answer












                            I'm didn't totally follow, but to add an action listener, you just call addActionListener (from Abstract Button). If this doesn't totally answer your question, can you provide some more details?







                            share|improve this answer












                            share|improve this answer



                            share|improve this answer










                            answered Nov 12 '08 at 18:48









                            AdamC

                            11.8k74261




                            11.8k74261






















                                up vote
                                1
                                down vote













                                idk if this works but I made the variable names



                                public abstract class beep implements ActionListener {
                                public static void main(String args) {
                                JFrame f = new JFrame("beeper");
                                JButton button = new JButton("Beep me");
                                f.setVisible(true);
                                f.setSize(300, 200);
                                f.add(button);
                                button.addActionListener(new ActionListener() {
                                public void actionPerformed(ActionEvent e) {
                                //insert code here
                                }
                                } );

                                }


                                }






                                share|improve this answer

























                                  up vote
                                  1
                                  down vote













                                  idk if this works but I made the variable names



                                  public abstract class beep implements ActionListener {
                                  public static void main(String args) {
                                  JFrame f = new JFrame("beeper");
                                  JButton button = new JButton("Beep me");
                                  f.setVisible(true);
                                  f.setSize(300, 200);
                                  f.add(button);
                                  button.addActionListener(new ActionListener() {
                                  public void actionPerformed(ActionEvent e) {
                                  //insert code here
                                  }
                                  } );

                                  }


                                  }






                                  share|improve this answer























                                    up vote
                                    1
                                    down vote










                                    up vote
                                    1
                                    down vote









                                    idk if this works but I made the variable names



                                    public abstract class beep implements ActionListener {
                                    public static void main(String args) {
                                    JFrame f = new JFrame("beeper");
                                    JButton button = new JButton("Beep me");
                                    f.setVisible(true);
                                    f.setSize(300, 200);
                                    f.add(button);
                                    button.addActionListener(new ActionListener() {
                                    public void actionPerformed(ActionEvent e) {
                                    //insert code here
                                    }
                                    } );

                                    }


                                    }






                                    share|improve this answer












                                    idk if this works but I made the variable names



                                    public abstract class beep implements ActionListener {
                                    public static void main(String args) {
                                    JFrame f = new JFrame("beeper");
                                    JButton button = new JButton("Beep me");
                                    f.setVisible(true);
                                    f.setSize(300, 200);
                                    f.add(button);
                                    button.addActionListener(new ActionListener() {
                                    public void actionPerformed(ActionEvent e) {
                                    //insert code here
                                    }
                                    } );

                                    }


                                    }







                                    share|improve this answer












                                    share|improve this answer



                                    share|improve this answer










                                    answered Nov 11 at 10:34









                                    Ronald Ortiz

                                    111




                                    111






























                                        draft saved

                                        draft discarded




















































                                        Thanks for contributing an answer to Stack Overflow!


                                        • Please be sure to answer the question. Provide details and share your research!

                                        But avoid



                                        • Asking for help, clarification, or responding to other answers.

                                        • Making statements based on opinion; back them up with references or personal experience.


                                        To learn more, see our tips on writing great answers.





                                        Some of your past answers have not been well-received, and you're in danger of being blocked from answering.


                                        Please pay close attention to the following guidance:


                                        • Please be sure to answer the question. Provide details and share your research!

                                        But avoid



                                        • Asking for help, clarification, or responding to other answers.

                                        • Making statements based on opinion; back them up with references or personal experience.


                                        To learn more, see our tips on writing great answers.




                                        draft saved


                                        draft discarded














                                        StackExchange.ready(
                                        function () {
                                        StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f284899%2fhow-do-you-add-an-actionlistener-onto-a-jbutton-in-java%23new-answer', 'question_page');
                                        }
                                        );

                                        Post as a guest















                                        Required, but never shown





















































                                        Required, but never shown














                                        Required, but never shown












                                        Required, but never shown







                                        Required, but never shown

































                                        Required, but never shown














                                        Required, but never shown












                                        Required, but never shown







                                        Required, but never shown







                                        Popular posts from this blog

                                        Bressuire

                                        Vorschmack

                                        Quarantine