Solved

Button Listener

Posted on 2006-07-05
10
263 Views
Last Modified: 2010-03-31
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
public class Chapter636 extends JApplet
{
      private static final long serialVersionUID = 1L;
      public void init()
      {
            Container Form = getContentPane();
            Form.setLayout(new BorderLayout());
            JButton Calculate = new JButton("Calculate");
            Form.add(Calculate,BorderLayout.SOUTH);
            JPanel Panel = new JPanel();
            final JTextField Base = new JTextField("Base",5);
            final JTextField Exp = new JTextField("Exp",5);
            Panel.add(Base,BorderLayout.NORTH);
            Panel.add(Exp,BorderLayout.SOUTH);
            Form.add(Panel,BorderLayout.NORTH);
            Calculate.addActionListener(
                        new ActionListener()
                        {
                                    public void actionPerformed(ActionEvent e)
                                    {
                                          if (IsNum(Base.getText()) && IsNum(Exp.getText()))
                                          {
                                                int B,E;
                                                B = Integer.parseInt(Base.getText());
                                                E = Integer.parseInt(Exp.getText());
                                                JOptionPane.showMessageDialog(null,B +"^" + E
                                                            +"=" + Exp(B,E));
                                          }
                                          else
                                                JOptionPane.showMessageDialog(null,
                                                            "Numeric input only! No negatives, no decimals.");
                                    }
                        });
      }
      private boolean IsNum(String Str)
      {
            for(int i=0;i<Str.length();i++)
            {
                  if ((int)Str.charAt(i) <48 || (int)Str.charAt(i) > 57)
                        return false;
            }
            return true;
      }
      private int Exp(int NBase,int NExp)
      {
            if(NExp <1)
                  return 1;
            if (NExp >1)
            {
                  NBase = NBase * Exp(NBase,NExp-1);
            }
            return NBase;
      }
}

In the above completed application, how would I move the action listener to be its own class rather than disturbing the flow
of code in method init?
0
Comment
Question by:List244
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 6
  • 4
10 Comments
 
LVL 86

Expert Comment

by:CEHJ
ID: 17045521
You have two options:

1. Use a private named class that implements ActionListener
2. Make you applet implement ActionListener

The second is simpler
0
 
LVL 86

Accepted Solution

by:
CEHJ earned 250 total points
ID: 17045535
2.

Calculate.addActionListener(this);

and have the actionPerformed method as a method of your applet
0
 
LVL 8

Author Comment

by:List244
ID: 17045645
I have been unable to accomplish either of these methods, can you show a more specific example?
Maybe an implementation to my code, or even a smaller example which implements a button with a
detached listener?
0
Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
LVL 86

Expert Comment

by:CEHJ
ID: 17045667
>>I have been unable to accomplish either of these methods, can you show a more specific example?

What was the problem? There's really nothing more to it than the code in my last comment
0
 
LVL 8

Author Comment

by:List244
ID: 17045728
Well, take a look at this:

import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
public  class Chapter636 extends JApplet
{
      //Not sure on the below line, Eclipse put it there..
      private static final long serialVersionUID = 1L;
      public void init()
      {
            Container Form = getContentPane();
            Form.setLayout(new BorderLayout());
            JButton Calculate = new JButton("Calculate");
            Form.add(Calculate,BorderLayout.SOUTH);
            JPanel Panel = new JPanel();
            final JTextField Base = new JTextField("Base",5);
            final JTextField Exp = new JTextField("Exp",5);
            Panel.add(Base,BorderLayout.NORTH);
            Panel.add(Exp,BorderLayout.SOUTH);
            Form.add(Panel,BorderLayout.NORTH);
            final JLabel Label = new JLabel("Result:");
            Form.add(Label,BorderLayout.CENTER);
            Calculate.addActionListener(this); //The method addActionListener(ActionListener) in the type AbstractButton is not
                                //is not applicapable for the arguments (Chapter636)
      }

      public void actionPerformed(ActionEvent e)
      {
            if (IsNum(Base.getText()) && IsNum(Exp.getText()))
            {
                  int B,E;
                  B = Integer.parseInt(Base.getText());
                  E = Integer.parseInt(Exp.getText());
                  Label.setText("Result: " + B + "^" + E +
                              " = " + Exp(B,E));
                  //JOptionPane.showMessageDialog(null,B +"^" + E
                              //+"=" + ;
            }
            else
                  JOptionPane.showMessageDialog(null,
                              "Numeric input only! No negatives, no decimals.");
      }
      private boolean IsNum(String Str)
      {
            for(int i=0;i<Str.length();i++)
            {
                  if ((int)Str.charAt(i) <48 || (int)Str.charAt(i) > 57)
                        return false;
            }
            return true;
      }
      private int Exp(int NBase,int NExp)
      {
            if(NExp <1)
                  return 1;
            if (NExp >1)
            {
                  NBase = NBase * Exp(NBase,NExp-1);
            }
            return NBase;
      }
}

There is an error commented above:
//The method addActionListener(ActionListener) in the type AbstractButton is not
                                //is not applicapable for the arguments (Chapter636)

And, all items of the form become inaccessible to the listener, would that be fixed by a more global-scope, or is there a better way?
0
 
LVL 86

Expert Comment

by:CEHJ
ID: 17045743
Replace

>>public  class Chapter636 extends JApplet

with

public  class Chapter636 extends JApplet implements ActionListener
0
 
LVL 8

Author Comment

by:List244
ID: 17045824
Okay, that works.

If I were to add another button, would there be a way to differentiate which was clicked?
0
 
LVL 86

Expert Comment

by:CEHJ
ID: 17045847
Yes

public void actionPerformed(ActionEvent e) {
    Object initiator = e.getSource();
    if (initiator == buttonA) {
        //
    }
    else if (initiator == buttonB) {
        //
    }
}
0
 
LVL 8

Author Comment

by:List244
ID: 17045931
That works, thanks.
0
 
LVL 86

Expert Comment

by:CEHJ
ID: 17045953
:-)
0

Featured Post

On Demand Webinar - Networking for the Cloud Era

This webinar discusses:
-Common barriers companies experience when moving to the cloud
-How SD-WAN changes the way we look at networks
-Best practices customers should employ moving forward with cloud migration
-What happens behind the scenes of SteelConnect’s one-click button

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
how to see all occupied ports on windows 10 laptop 15 83
by zero exception 10 70
ejb mdb examples 1 19
jsp error 6 45
Go is an acronym of golang, is a programming language developed Google in 2007. Go is a new language that is mostly in the C family, with significant input from Pascal/Modula/Oberon family. Hence Go arisen as low-level language with fast compilation…
Introduction This article is the second of three articles that explain why and how the Experts Exchange QA Team does test automation for our web site. This article covers the basic installation and configuration of the test automation tools used by…
Viewers learn about the scanner class in this video and are introduced to receiving user input for their programs. Additionally, objects, conditional statements, and loops are used to help reinforce the concepts. Introduce Scanner class: Importing…
The viewer will learn how to implement Singleton Design Pattern in Java.

756 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question