Results 1 to 12 of 12
  1. #1
    kd7vea is offline Member
    Join Date
    Apr 2011
    Posts
    9
    Rep Power
    0

    Default event handler issues

    hello everyone, I have been reading several of the posts, to help me with my current project, but I am having trouble getting my buttons to work. I am still pretty new to java, and it may be one stupid little thing, or I could have it totally messed up. I know this has been done countless times, the app is just a Celsius to Fahrenheit convertor. can anyone give me some input on how to get my buttons to work. I just want the clear button to clear the two text boxes, and the calculate to perform the math. thanks in advance for any help.
    Jake

    Java Code:
    package java.awt.event;
    import javax.swing. *;
    import java.awt.*;
    import javax.swing.JButton;
    
    
    public class calculator extends JFrame{
        public calculator(ActionListener ActionListener, ActionListener calculator){
            super ("Fahrenheit/Celsius Converter");
            setSize (250, 175);
            setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            FlowLayout flow = new FlowLayout();
            JLabel far = new JLabel(" Fahrenheit ");
            final JTextField farTemp = new JTextField(10);
            JLabel cel = new JLabel("Celsius       ");
            final JTextField celTemp = new JTextField(10);
            JButton calculate = new JButton("Calculate");
            JButton clear = new JButton("Clear");
            setLayout (flow);
            add(far);
            add (farTemp);
            add(cel);
            add(celTemp);
            add(calculate);
            add(clear);
            setVisible(true);
        
            // converting string for fahrenheit conversion
               float fTemp = (float) 0.0;
            fTemp += Float.parseFloat(farTemp.getText());
            
            // converting string for Celsius conversion
              float cTemp = (float) 0.0;
            cTemp += Float.parseFloat(celTemp.getText());
    
            //setting up the clear button
            clear.addActionListener(new ActionListenerImpl(farTemp, celTemp) {
                public void actionPerformed(ActionEvent e){
                farTemp.setText("");
                celTemp.setText("");
                }
            });
    
            //setting upcalculate button
            calculate.addActionListener(new ActionListenerImpl1(celTemp, farTemp, cTemp, fTemp){
    
            });
        }
    
        private static class ActionListenerImpl implements ActionListener {
    
            private final JTextField farTemp;
            private final JTextField celTemp;
    
            public ActionListenerImpl(JTextField farTemp, JTextField celTemp) {
                this.farTemp = farTemp;
                this.celTemp = celTemp;
            }
    
            public void actionPerformed(ActionEvent e) {
                farTemp.setText("");
                celTemp.setText("");
            }
        }
    
        private static class ActionListenerImpl1 implements ActionListener {
    
            private final JTextField celTemp;
            private final JTextField farTemp;
            private final float cTemp;
            private final float fTemp;
    
            public ActionListenerImpl1(JTextField celTemp, JTextField farTemp, float cTemp, float fTemp) {
                this.celTemp = celTemp;
                this.farTemp = farTemp;
                this.cTemp = cTemp;
                this.fTemp = fTemp;
            }
    
            public void actionPerformed(ActionEvent e) {
                if (celTemp != null) {
                    farTemp.setText("" + cTemp * 9 / 5 + 32);
                } else {
                    celTemp.setText("" + (fTemp - 32) * 5 / 9);
                }
            }
        }
    
    }
    Attached Files Attached Files
    Last edited by kd7vea; 04-21-2011 at 05:03 AM. Reason: added info

  2. #2
    sunde887's Avatar
    sunde887 is offline Moderator
    Join Date
    Jan 2011
    Location
    Richmond, Virginia
    Posts
    3,069
    Blog Entries
    3
    Rep Power
    8

    Default

    Please wrap your code in code tags
    [ code] //no space here
    YOUR CODE HERE
    [/code]

    Java Code:
    ActionListener ActionListener, ActionListener calculator
    in the constructor is bad, while I understand your goal, a parameter should not have the same name as a class name.


    The code could be done much simpler with inner classes as well.

    Java Code:
    create textfield 1
    create textfield 2
    create clear button
    create calculate button
    add action listener to clear button
    add action listener to calculate button
    create an inner class for the action listeners
    Java Code:
    public class Calculator{
      private class CalculateListener implements ActionListener{
        public void actionPerformed(ActionEvent e){
          //do calculation stuff
        }
      }
      another action listener
      set up stuff
      main
    }
    Last edited by sunde887; 04-21-2011 at 04:51 AM.

  3. #3
    ra4king's Avatar
    ra4king is offline Senior Member
    Join Date
    Apr 2011
    Location
    Atlanta, Georgia, US
    Posts
    396
    Rep Power
    4

    Default

    Please use code tags and formatting so we can easily read your code. Usage: [ code ] code goes here [ /code ] (without the spaces).

    But briskly looking at it, everything looks fine. What exactly is your problem?

    EDIT: hehe I posted while I was typing sunde :P

  4. #4
    kd7vea is offline Member
    Join Date
    Apr 2011
    Posts
    9
    Rep Power
    0

    Default

    thanks for the quick responses. I edited the post and put the code in the tags. the problem I am having is that the buttons do not do anything at all. I have spent almost 10 hours trying to get this thing to work, and i cant get anywhere on it.

    Sunde887
    I find it a little funny that you say you understand my goal, I would love for you to explain it to me, because I am not totally sure what my goal is. I don't think I entered that code that line of code. I don't know if that is one of the "hints" that netbeans adds to the code, or if that was part of what I was doing last night until about 5:00 a.m. either way, what should that line contain? does it need ActionListener and then be given a name?(ActionListener buttonClick)?

    thanks for the info everybody. I really appreciate all the help.

  5. #5
    sunde887's Avatar
    sunde887 is offline Moderator
    Join Date
    Jan 2011
    Location
    Richmond, Virginia
    Posts
    3,069
    Blog Entries
    3
    Rep Power
    8

    Default

    If that's something netbeans added Im not sure. This is what I thought the goal is

    Java Code:
    public Blah(ActionListener blahListener){  //this is a constructor which takes an action listener
      JButton b = new JButton("HI");
      b.addActionListener(blah);
    }
    which means you would pass the action listeners in as the argument to the constructors.

    Using inner classes is nice for small files, and for action listeners you won't be using more than a few times(you can also use anonymous inner classes)

    If you make the action listener an inner class it has access to all the variables directly. For example, the clear listener could simply look like this

    Java Code:
    public class calculator{
      private class ClearListener implements ActionListener{
        public void actionPerformed(ActionEvent e){
          text1.setText("");
          text2.setText("");
        }
      }
    }
    This is similar to what you did, except it has direct access to instance variables.

    Does your code compile correctly?

  6. #6
    kd7vea is offline Member
    Join Date
    Apr 2011
    Posts
    9
    Rep Power
    0

    Default

    the code does compile and run, but it does give me these errors
    Exception in thread "main" java.lang.NumberFormatException: empty String
    at sun.misc.FloatingDecimal.readJavaFormatString(Floa tingDecimal.java:992)
    at java.lang.Float.parseFloat(Float.java:422)
    at calculator.<init>(calculator.java:29)
    at calculator.main(calculator.java:45)
    BUILD SUCCESSFUL (total time: 16 seconds)

    the app opens, I can input numbers into the text fields, and that is it, it does not calculate when the calculate button is pushed, and it does not clear the boxes when the clear button is pushed. basically, I have a 2 line 20 character notepad!!!

  7. #7
    sunde887's Avatar
    sunde887 is offline Moderator
    Join Date
    Jan 2011
    Location
    Richmond, Virginia
    Posts
    3,069
    Blog Entries
    3
    Rep Power
    8

    Default

    snip: removed the spoon fed answer.

    The action listener should be what happens when the item is clicked. Here is a quick example using a anonymous inner class and a private inner class

    Java Code:
    import javax.swing.*;
    import java.awt.event.*;
    import java.awt.*;
    
    public class Listener{
      private JFrame frame;
      private JPanel panel;
      private JButton b1;
      private JLabel l1;
      
      public Listener(){
        frame = new JFrame("FRAME");
        panel = new JPanel();
        panel.setLayout(new FlowLayout());
        b1 = new JButton("CLICK ME");
        l1 = new JLabel("Hello THERE");
        b1.addActionListener(new TextListener()); //option 1, using a private inner class
        b1.addActionListener(new ActionListener(){  //option 2, using an anonymous inner class
          public void actionPerformed(ActionEvent e){
            l1.setText(Math.random() + "");
          }
        });
    	panel.add(b1);
    	panel.add(l1);
    	frame.add(panel);
        frame.setSize(200, 200);
        frame.setVisible(true);
      }
      public static void main(String[] args){
        Listener l = new Listener();
      }
      private class TextListener implements ActionListener{
        public void actionPerformed(ActionEvent e){
          l1.setText("" + Math.random());
        }
      }
    }
    edit:compilable now

    @fubar, I'd like to apologize for the spoonfeeding.

    oops, forgot the anonymous inner class, edited it in.
    Last edited by sunde887; 04-21-2011 at 06:29 AM.

  8. #8
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    26

    Default

    You're trying to extract text from the JTextFields in the main class's constructor -- which is before anyone has had a chance to type anything into the text fields.

    I recommend:
    • I don't see a need for your to pass an ActionListener into your class's constructor, at least not as currently created, so you should probably get those parameters out of the constructor.
    • Don't try to extract information from the JTextFields until the user has had a chance to enter text in first. Thus this should be done in your ActionListener's actionPerformed code which is activated on button press.
    • Please learn and adhere to Java naming conventions if you want us to be able to better help you. Using non-standard capitalization and such makes it hard for others to understand your code and help (or grade) you.


    Luck

    edit: my post was added before I saw the spoonfeeding. My points are still valid even if you use someone else's code.

  9. #9
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    26

    Default

    Quote Originally Posted by sunde887 View Post
    snip: removed the spoon fed answer.

    The action listener should be what happens when the item is clicked. Here is a quick example using a anonymous inner class and a private inner class

    Java Code:
    public class Listener{
      private JFrame frame;
      private JPanel panel;
      private JButton b1;
      private JLabel l1;
      
      public Listener(){
        frame = new JFrame("FRAME");
        panel = new JPanel();
        panel.setLayout(new FlowLayout());
        b1 = new JButton("CLICK ME");
        l1 = new JLabel("Hello THERE");
        b1.addActionListener(new TextListener());
        frame.setSize(200, 200);
        frame.setVisible(true);
      }
      private TextListener implements ActionListener{
        public void actionPerformed(ActionEvent e){
          l1.setText("" + Math.random());
        }
      }
    }
    @fubar, I'd like to apologize for the spoonfeeding.
    It's OK, but does your code above compile? Is there an anonymous inner class?

  10. #10
    kd7vea is offline Member
    Join Date
    Apr 2011
    Posts
    9
    Rep Power
    0

    Default

    Thanks for the help everyone. I am going to tinker with this some more tonight and see if I can get it running. I know this is one of those projects that everyone does in school, and I remember doing this same project in one of my java classes. this is not a school project, I am trying to refresh my self on java. I graduated a few months ago, and I am needing to practice a little to hopefully some day get a job in programming. the funny thing is that the code that I have written is what follows how the book describes to do it. as a couple of you have said, I am going about this the hard way. is there a good book that can give me a better grasp? I have been reading "sams Teach Yourself JAVA in 24 hours" , because I thought it would bring me back up to speed before I started getting into the more complex stuff, but apparently its not giving me the simplest approach. thanks again
    Jake

  11. #11
    ra4king's Avatar
    ra4king is offline Senior Member
    Join Date
    Apr 2011
    Location
    Atlanta, Georgia, US
    Posts
    396
    Rep Power
    4

    Default

    Head First Java is a very good book that I recommend.

  12. #12
    sunde887's Avatar
    sunde887 is offline Moderator
    Join Date
    Jan 2011
    Location
    Richmond, Virginia
    Posts
    3,069
    Blog Entries
    3
    Rep Power
    8

    Default

    I agree with him 100%, the book does an amazing job covering the basics and gives you a fairly decent intro to some of the more complex stuff. The oracle tutorials will also be very helpful to refresh on anything you are unsure of. There are a lot of other really good books besides head first java.

    For this example I suggest you read the tutorials on action listeners, that along with my example should give you enough to finish the celcius conversion. Also, always have the API handy.

Similar Threads

  1. Replies: 0
    Last Post: 03-22-2010, 06:45 AM
  2. zip a file tp data handler
    By beginer@1234 in forum New To Java
    Replies: 2
    Last Post: 04-27-2009, 06:04 AM
  3. event handler not working properly
    By H3rtaherta in forum Java 2D
    Replies: 3
    Last Post: 11-24-2008, 02:39 AM
  4. JList and JButton event handler not working
    By H3rtaherta in forum AWT / Swing
    Replies: 3
    Last Post: 11-22-2008, 12:00 AM
  5. Help with Handler
    By baltimore in forum AWT / Swing
    Replies: 1
    Last Post: 08-04-2007, 09:42 PM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •