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.

Results 1 to 9 of 9

Thread: Event Handler For a JTextField

  1. #1
    Junior Member
    Join Date
    Nov 2012
    Posts
    29
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Event Handler For a JTextField

    /*
     *
     *
    */
     
    import java.io.*;
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import java.text.*;
    import java.util.*;
     
     
    public class TripCalcUpdated extends JFrame implements ActionListener
    {
       //Declare output stream
       DataOutputStream output;
     
       String[] startStrings = { "Detroit Lakes", "Minneapolis", "Duluth", "Bemidji", "Rochester", "StCloud", "Daytona", "Darlington", "Charlotte", "Talladega", "Richmond", "Bristol" };
       float costPG, miles, vehiclempg, index;
       int i, j, k, l, m, n, o, p;
     
     
     
       //construct components
       JLabel typePrompt = new JLabel("Vehicle Type");
       JComboBox typeCombo = new javax.swing.JComboBox();
       JTextPane typePane = new JTextPane();
     
       JLabel fuelPrompt = new JLabel("Fuel Type");
       JComboBox fuelCombo = new javax.swing.JComboBox();
       JTextPane fuelPane = new JTextPane();
     
       JLabel startPrompt = new JLabel("Starting Location");
       JComboBox startCombo = new javax.swing.JComboBox();
       JTextPane startPane = new JTextPane();
     
       JLabel endPrompt = new JLabel("Ending Location");
       JComboBox endCombo = new javax.swing.JComboBox();
       JTextPane endPane = new JTextPane();
     
     
     
        // Panel Creation
        JPanel firstRow = new JPanel();
        JPanel secondRow = new JPanel();
     
     
        // Panel for Fields and Buttons
        JPanel fieldPanel = new JPanel();
        JPanel buttonPanel = new JPanel();
     
        // Construct Labels and TextBoxes
        JLabel Miles = new JLabel("Miles planning to travel"         );
          JTextField distance = new JTextField(5);
        JLabel Fuelcost = new JLabel("What is the price per gallon?"              );
          JTextField fuelprice = new JTextField(3);
        JLabel MPG = new JLabel("What is the Vehicles MPG?"         );
          JTextField VMPG = new JTextField(3);
        JLabel Total = new JLabel("Your total cost for the trip will be " + index + "."        );
     
     
        JButton submitJButton = new JButton("Submit");
        JButton clearJButton = new JButton("Clear Fields");
     
     
     //main method executes at run time
     public static void main(String args[])
        {
      TripCalc f = new TripCalc();
      f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      f.setContentPane(f.createContentPane());
      f.setTitle("Trip Calculator");
      f.setSize(800,300);
      f.setVisible(true);
        }
     
     
       //create the content pane
       public Container createContentPane()
       {
        //populate the JCombobox
        typeCombo.addItem("Compact");
        typeCombo.addItem("Mid-Size");
        typeCombo.addItem("Luxury");
        typeCombo.addItem("SUV");
        typeCombo.addActionListener(this);
     
        fuelCombo.addItem("Leaded");
        fuelCombo.addItem("Unleaded");
        fuelCombo.addItem("Super Unleaded");
        fuelCombo.addItem("Diesel");
        fuelCombo.addActionListener(this);
     
        startCombo.addItem("Minneapolis");
        startCombo.addItem("Duluth");
        startCombo.addItem("Bemidji");
        startCombo.addItem("Rochester");
        startCombo.addItem("Detroit Lakes");
        startCombo.addItem("St.Cloud");
        startCombo.addActionListener(this);
     
        endCombo.addItem("Daytona");
        endCombo.addItem("Darlington");
        endCombo.addItem("Las Vegas");
        endCombo.addItem("Talladega");
        endCombo.addItem("Richmond");
        endCombo.addItem("Bristol");
        endCombo.addActionListener(this);
     
        //construct and populate the north panel
        JPanel northPanel = new JPanel();
        northPanel.setLayout(new FlowLayout());
        northPanel.add(typePrompt);
        northPanel.add(typeCombo);
        northPanel.add(fuelPrompt);
        northPanel.add(fuelCombo);
        northPanel.add(startPrompt);
        northPanel.add(startCombo);
        northPanel.add(endPrompt);
        northPanel.add(endCombo);
     
        JPanel southPanel = new JPanel();
        southPanel.setLayout(new FlowLayout());
        southPanel.add(submitJButton);
        southPanel.add(clearJButton);
     
        clearJButton.addActionListener(this);
        submitJButton.addActionListener(this);
     
        JPanel centerPanel = new JPanel();
        centerPanel.setLayout(new FlowLayout());
        centerPanel.add(Miles);
        centerPanel.add(distance);
        centerPanel.add(Fuelcost);
        centerPanel.add(fuelprice);
     
     
        centerPanel.add(VMPG);
        centerPanel.add(MPG);
        centerPanel.add(Total);
     
     
     
         //createContainer and set attributes
         Container f = getContentPane();
         setLayout(new BorderLayout(40,40));
         fieldPanel.setLayout(new GridLayout(1,1));
         buttonPanel.setLayout(new FlowLayout(FlowLayout.LEFT));
         add(northPanel,BorderLayout.NORTH);
         add(southPanel,BorderLayout.SOUTH);
         add(centerPanel,BorderLayout.CENTER);
         setLocation(200,200);
         return f;
         }
     
     
     
         // event to process user clicks
      public void actionPerformed(ActionEvent e)
      {
           if(e.getSource() == submitJButton)
           {
            costPG = Float.parseFloat(fuelprice.getText());
            vehiclempg = Float.parseFloat(MPG.getText());
            miles = Float.parseFloat(distance.getText());
     
            index = (miles / vehiclempg) *(costPG);
            Total.setText("index");
         }
            else if(e.getSource() == clearJButton)
            {
            distance.setText("");
            VMPG.setText("");
            fuelprice.setText("");
     
            }
      }
    }

    I am trying to get the action listener so when I enter a value in each of the fields the answer is index which would fill the JLabel Total but obviously it's not working otherwise why would I be here.

    I've read the javadocs help for eventhandler but my mind is not grasping it. is the eGetSource method wrong, do I need something else?

    Thanks


  2. #2
    Super Moderator pbrockway2's Avatar
    Join Date
    Jan 2012
    Posts
    965
    Thanks
    7
    Thanked 205 Times in 181 Posts

    Default Re: Event Handler For a JTextField

    vehiclempg = Float.parseFloat(MPG.getText());
    That doesn't look right to me because MPG is a JLabel with the text "What is the Vehicles MPG?". And parsing that text as a float won't lead to anything good...

    ---

    A couple of observations - First, use standard Java coding conventions as this will enable others to follow your code more easily. Classes (and other types like interfaces) begin with a capital letter while variables and methods all begin with a lowercase one. So MPG is not a good thing to use as a variable. Although not part of the conventions some people use variable names with a suffix that shows the sort of thing they are: so mpgL and mpgTF might have been a better choice than MPG and VMPG.

    Secondly, actually describing the problem is always good. That is: say what you did (what you entered in the fields, what you clicked) and what happened (what the gui displayed, but also the full text of any runtime exceptions that happened). To be useful you have to post the actual code you used. If you're anything like me you'll make typos or other mistakes if you don't actually copy and paste the code exactly as you ran it.

  3. #3
    Junior Member
    Join Date
    Nov 2012
    Posts
    29
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Event Handler For a JTextField

    /* 
     *
     *
    */
     
    import java.io.*;
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.event.*;
    import javax.swing.text.*;
    import java.text.*;
    import java.util.*;
     
    import java.beans.PropertyChangeListener;
    import java.beans.PropertyChangeEvent;
     
    public class TripCalcUpdated extends JFrame implements PropertyChangeListener
     
    {
       //Declare output stream
       DataOutputStream output;
     
       String[] startStrings = { "Detroit Lakes", "Minneapolis", "Duluth", "Bemidji", "Rochester", "StCloud", "Daytona", "Darlington", "Charlotte", "Talladega", "Richmond", "Bristol" };
       double distance, fuelprice, gallons, totalCost, index;
       int i, j, k, l, m, n, o, p;
     
     
     
       //construct components
       JLabel typePrompt = new JLabel("Vehicle Type");
       JComboBox typeCombo = new javax.swing.JComboBox();
       JTextPane typePane = new JTextPane();
     
       JLabel fuelPrompt = new JLabel("Fuel Type");
       JComboBox fuelCombo = new javax.swing.JComboBox();
       JTextPane fuelPane = new JTextPane();
     
       JLabel startPrompt = new JLabel("Starting Location");
       JComboBox startCombo = new javax.swing.JComboBox();
       JTextPane startPane = new JTextPane();
     
       JLabel endPrompt = new JLabel("Ending Location");
       JComboBox endCombo = new javax.swing.JComboBox();
       JTextPane endPane = new JTextPane();
     
       JFormattedTextField distance;
       JFormattedTextField fuelprice;
       JFormattedTextField mpg;
       JFormattedTextField totalCost;
     
       NumberFormat distanceFormat;
       NumberFormat fuelpriceFormat;
       NumberFormat mpgFormat;
       NumberFormat totalCostFormat;
     
     
        // Panel Creation
        JPanel firstRow = new JPanel();
        JPanel secondRow = new JPanel();
     
     
        // Panel for Fields and Buttons
        JPanel fieldPanel = new JPanel();
        JPanel buttonPanel = new JPanel();
     
        // Construct Labels and TextBoxes
        JLabel Miles = new JLabel("Miles planning to travel"         );
        distance = new JFormattedTextField(distanceFormat);
        distance.setValue(new Double(distance));
        distance.setColumns(5);
        distance.addPropertyChangeListener("value", this);
     
        JLabel Fuelcost = new JLabel("What is the price per gallon?"              );
        fuelprice = new JFormattedTextField(fuelpriceFormat);
        fuelprice.setValue(new Double (fuelprice));
        fuelprice.setColumns(5);
        fuelprice.addPropertyChangeListener("value", this);
     
        JLabel FuelAmount = new JLabel("What is your vehicle's MPG?"         );
        mpg = new JFormattedTextField(mpgFormat);
        mpg.setValue(new Double(mpg));
        mpg.setColumns(5);
        mpg.addPropertyChangeListener("value", this);
     
        JLabel Total = new JLabel("Your total cost for the trip will be "       );
        totalCost = new JFormattedTextField(totalCostFormat);
        totalCost.setValue(new Double(totalCost));
     
     
        JButton submitJButton = new JButton("Submit");
        JButton clearJButton = new JButton("Clear Fields");
     
     
     //main method executes at run time
     public static void main(String args[])
        {
      TripCalc f = new TripCalc();
      f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      f.setContentPane(f.createContentPane());
      f.setTitle("Trip Calculator");
      f.setSize(800,300);
      f.setVisible(true);
        }
     
     
       //create the content pane
       public Container createContentPane()
       {
        //populate the JCombobox
        typeCombo.addItem("Compact");
        typeCombo.addItem("Mid-Size");
        typeCombo.addItem("Luxury");
        typeCombo.addItem("SUV");
        typeCombo.addActionListener(this);
     
        fuelCombo.addItem("Leaded");
        fuelCombo.addItem("Unleaded");
        fuelCombo.addItem("Super Unleaded");
        fuelCombo.addItem("Diesel");
        fuelCombo.addActionListener(this);
     
        startCombo.addItem("Minneapolis");
        startCombo.addItem("Duluth");
        startCombo.addItem("Bemidji");
        startCombo.addItem("Rochester");
        startCombo.addItem("Detroit Lakes");
        startCombo.addItem("St.Cloud");
        startCombo.addActionListener(this);
     
        endCombo.addItem("Daytona");
        endCombo.addItem("Darlington");
        endCombo.addItem("Las Vegas");
        endCombo.addItem("Talladega");
        endCombo.addItem("Richmond");
        endCombo.addItem("Bristol");
        endCombo.addActionListener(this);
     
        //construct and populate the north panel
        JPanel northPanel = new JPanel();
        northPanel.setLayout(new FlowLayout());
        northPanel.add(typePrompt);
        northPanel.add(typeCombo);
        northPanel.add(fuelPrompt);
        northPanel.add(fuelCombo);
        northPanel.add(startPrompt);
        northPanel.add(startCombo);
        northPanel.add(endPrompt);
        northPanel.add(endCombo);
     
        JPanel southPanel = new JPanel();
        southPanel.setLayout(new FlowLayout());
        southPanel.add(submitJButton);
        southPanel.add(clearJButton);
     
        clearJButton.addActionListener(this);
        submitJButton.addActionListener(this);
     
        JPanel centerPanel = new JPanel();
        centerPanel.setLayout(new FlowLayout());
        centerPanel.add(Miles);
        centerPanel.add(distance);
        centerPanel.add(Fuelcost);
        centerPanel.add(fuelprice);
     
     
        centerPanel.add(FuelAmount);
        centerPanel.add(gallons);
        centerPanel.add(Total);
     
     
     
         //createContainer and set attributes
         Container f = getContentPane();
         setLayout(new BorderLayout(40,40));
         fieldPanel.setLayout(new GridLayout(1,1));
         buttonPanel.setLayout(new FlowLayout(FlowLayout.LEFT));
         add(northPanel,BorderLayout.NORTH);
         add(southPanel,BorderLayout.SOUTH);
         add(centerPanel,BorderLayout.CENTER);
         setLocation(200,200);
         return f;
         }
     
     
     
         // event to process user clicks
      public void actionPerformed(ActionEvent e)
      {
         String arg = e.getActionCommand();
     
     
     
         Object target = e.getSource();
           if(target == submitJButton)
           {
     
            fuelprice = ((Number)fuelprice.getValue()).doubleValue();
            mpg = ((Number)gallons.getValue()).doubleValue();
            distance = ((Number)distance.getValue()).doubleValue();
     
            index = (distance/mpg)* fuelprice;
            totalCost.setText(index);
         }
            else if(target == clearJButton)
            {
            distance.setText("");
            gallons.setText("");
            fuelprice.setText("");
     
            }
      }
    }

    I did some reading and modified the code to have formattedTextFields for the different variables.

    These are the errors i'm getting.

    52 errors found:
    [line: 69]
    Error: <identifier> expected
    [line: 70]
    Error: <identifier> expected
    [line: 70]
    Error: illegal start of type
    [line: 70]
    Error: ')' expected
    File: C:\Users\James Turnham\Documents\Rasmussen School Folder\Winter 2013\Java Assignments\TripCalcUpdated.java [line: 70]
    Error: ';' expected
    File: C:\Users\James Turnham\Documents\Rasmussen School Folder\Winter 2013\Java Assignments\TripCalcUpdated.java [line: 70]
    Error: <identifier> expected
    File: C:\Users\James Turnham\Documents\Rasmussen School Folder\Winter 2013\Java Assignments\TripCalcUpdated.java [line: 70]
    Error: illegal start of type
    File: C:\Users\James Turnham\Documents\Rasmussen School Folder\Winter 2013\Java Assignments\TripCalcUpdated.java [line: 70]
    Error: <identifier> expected
    File: C:\Users\James Turnham\Documents\Rasmussen School Folder\Winter 2013\Java Assignments\TripCalcUpdated.java [line: 70]
    Error: ';' expected
    File: C:\Users\James Turnham\Documents\Rasmussen School Folder\Winter 2013\Java Assignments\TripCalcUpdated.java [line: 71]
    Error: illegal start of type
    File: C:\Users\James Turnham\Documents\Rasmussen School Folder\Winter 2013\Java Assignments\TripCalcUpdated.java [line: 71]
    Error: illegal start of type
    File: C:\Users\James Turnham\Documents\Rasmussen School Folder\Winter 2013\Java Assignments\TripCalcUpdated.java [line: 72]
    Error: <identifier> expected
    File: C:\Users\James Turnham\Documents\Rasmussen School Folder\Winter 2013\Java Assignments\TripCalcUpdated.java [line: 72]
    Error: illegal start of type
    File: C:\Users\James Turnham\Documents\Rasmussen School Folder\Winter 2013\Java Assignments\TripCalcUpdated.java [line: 72]
    Error: illegal start of type
    File: C:\Users\James Turnham\Documents\Rasmussen School Folder\Winter 2013\Java Assignments\TripCalcUpdated.java [line: 75]
    Error: <identifier> expected
    File: C:\Users\James Turnham\Documents\Rasmussen School Folder\Winter 2013\Java Assignments\TripCalcUpdated.java [line: 76]
    Error: <identifier> expected
    File: C:\Users\James Turnham\Documents\Rasmussen School Folder\Winter 2013\Java Assignments\TripCalcUpdated.java [line: 76]
    Error: illegal start of type
    File: C:\Users\James Turnham\Documents\Rasmussen School Folder\Winter 2013\Java Assignments\TripCalcUpdated.java [line: 76]
    Error: ')' expected
    File: C:\Users\James Turnham\Documents\Rasmussen School Folder\Winter 2013\Java Assignments\TripCalcUpdated.java [line: 76]
    Error: ';' expected
    File: C:\Users\James Turnham\Documents\Rasmussen School Folder\Winter 2013\Java Assignments\TripCalcUpdated.java [line: 76]
    Error: <identifier> expected
    File: C:\Users\James Turnham\Documents\Rasmussen School Folder\Winter 2013\Java Assignments\TripCalcUpdated.java [line: 76]
    Error: illegal start of type
    File: C:\Users\James Turnham\Documents\Rasmussen School Folder\Winter 2013\Java Assignments\TripCalcUpdated.java [line: 76]
    Error: <identifier> expected
    File: C:\Users\James Turnham\Documents\Rasmussen School Folder\Winter 2013\Java Assignments\TripCalcUpdated.java [line: 76]
    Error: ';' expected
    File: C:\Users\James Turnham\Documents\Rasmussen School Folder\Winter 2013\Java Assignments\TripCalcUpdated.java [line: 77]
    Error: illegal start of type
    File: C:\Users\James Turnham\Documents\Rasmussen School Folder\Winter 2013\Java Assignments\TripCalcUpdated.java [line: 77]
    Error: illegal start of type
    File: C:\Users\James Turnham\Documents\Rasmussen School Folder\Winter 2013\Java Assignments\TripCalcUpdated.java [line: 78]
    Error: <identifier> expected
    File: C:\Users\James Turnham\Documents\Rasmussen School Folder\Winter 2013\Java Assignments\TripCalcUpdated.java [line: 78]
    Error: illegal start of type
    File: C:\Users\James Turnham\Documents\Rasmussen School Folder\Winter 2013\Java Assignments\TripCalcUpdated.java [line: 78]
    Error: illegal start of type
    File: C:\Users\James Turnham\Documents\Rasmussen School Folder\Winter 2013\Java Assignments\TripCalcUpdated.java [line: 81]
    Error: <identifier> expected
    File: C:\Users\James Turnham\Documents\Rasmussen School Folder\Winter 2013\Java Assignments\TripCalcUpdated.java [line: 82]
    Error: <identifier> expected
    File: C:\Users\James Turnham\Documents\Rasmussen School Folder\Winter 2013\Java Assignments\TripCalcUpdated.java [line: 82]
    Error: illegal start of type
    File: C:\Users\James Turnham\Documents\Rasmussen School Folder\Winter 2013\Java Assignments\TripCalcUpdated.java [line: 82]
    Error: ')' expected
    File: C:\Users\James Turnham\Documents\Rasmussen School Folder\Winter 2013\Java Assignments\TripCalcUpdated.java [line: 82]
    Error: ';' expected
    File: C:\Users\James Turnham\Documents\Rasmussen School Folder\Winter 2013\Java Assignments\TripCalcUpdated.java [line: 82]
    Error: <identifier> expected
    File: C:\Users\James Turnham\Documents\Rasmussen School Folder\Winter 2013\Java Assignments\TripCalcUpdated.java [line: 82]
    Error: illegal start of type
    File: C:\Users\James Turnham\Documents\Rasmussen School Folder\Winter 2013\Java Assignments\TripCalcUpdated.java [line: 82]
    Error: <identifier> expected
    File: C:\Users\James Turnham\Documents\Rasmussen School Folder\Winter 2013\Java Assignments\TripCalcUpdated.java [line: 82]
    Error: ';' expected
    File: C:\Users\James Turnham\Documents\Rasmussen School Folder\Winter 2013\Java Assignments\TripCalcUpdated.java [line: 83]
    Error: illegal start of type
    File: C:\Users\James Turnham\Documents\Rasmussen School Folder\Winter 2013\Java Assignments\TripCalcUpdated.java [line: 83]
    Error: illegal start of type
    File: C:\Users\James Turnham\Documents\Rasmussen School Folder\Winter 2013\Java Assignments\TripCalcUpdated.java [line: 84]
    Error: <identifier> expected
    File: C:\Users\James Turnham\Documents\Rasmussen School Folder\Winter 2013\Java Assignments\TripCalcUpdated.java [line: 84]
    Error: illegal start of type
    File: C:\Users\James Turnham\Documents\Rasmussen School Folder\Winter 2013\Java Assignments\TripCalcUpdated.java [line: 84]
    Error: illegal start of type
    File: C:\Users\James Turnham\Documents\Rasmussen School Folder\Winter 2013\Java Assignments\TripCalcUpdated.java [line: 87]
    Error: <identifier> expected
    File: C:\Users\James Turnham\Documents\Rasmussen School Folder\Winter 2013\Java Assignments\TripCalcUpdated.java [line: 88]
    Error: <identifier> expected
    File: C:\Users\James Turnham\Documents\Rasmussen School Folder\Winter 2013\Java Assignments\TripCalcUpdated.java [line: 88]
    Error: illegal start of type
    File: C:\Users\James Turnham\Documents\Rasmussen School Folder\Winter 2013\Java Assignments\TripCalcUpdated.java [line: 88]
    Error: ')' expected
    File: C:\Users\James Turnham\Documents\Rasmussen School Folder\Winter 2013\Java Assignments\TripCalcUpdated.java [line: 88]
    Error: ';' expected
    File: C:\Users\James Turnham\Documents\Rasmussen School Folder\Winter 2013\Java Assignments\TripCalcUpdated.java [line: 88]
    Error: <identifier> expected
    File: C:\Users\James Turnham\Documents\Rasmussen School Folder\Winter 2013\Java Assignments\TripCalcUpdated.java [line: 88]
    Error: illegal start of type
    File: C:\Users\James Turnham\Documents\Rasmussen School Folder\Winter 2013\Java Assignments\TripCalcUpdated.java [line: 88]
    Error: <identifier> expected
    File: C:\Users\James Turnham\Documents\Rasmussen School Folder\Winter 2013\Java Assignments\TripCalcUpdated.java [line: 88]
    Error: ';' expected
    File: C:\Users\James Turnham\Documents\Rasmussen School Folder\Winter 2013\Java Assignments\TripCalcUpdated.java [line: 91]
    Error: <identifier> expected

    Let's just say I used the information from Oracle located here How to Use Formatted Text Fields (The Java™ Tutorials > Creating a GUI With JFC/Swing > Using Swing Components) to do this, but what am I doing wrong?

  4. #4
    Super Moderator pbrockway2's Avatar
    Join Date
    Jan 2012
    Posts
    965
    Thanks
    7
    Thanked 205 Times in 181 Posts

    Default Re: Event Handler For a JTextField

    You have variables like distance declared twice and this is causing no end of problems.

    At the risk of repeating myself, having sensible (descriptive) variables stops the problem from ever arising: distance for the distance, distanceTF for the associated text field etc.

    ---

    Formatted text fields are a reasonable idea where - as in this case - you want fields for the user to input numbers. But you might make faster progress if you worked a small step at a time addressing each of the compiler's concerns as they arise. I'm guessing you didn't address the problems in the first version of the code since the main() method which was buggy there is repeated without change.

    Honestly: keep it simple. Keep the formatted text fields for later when you have a functional gui and want to address the specific problem of the user entering invalid data. Start with as simple a gui as you can. The fewer components, the better. Add them one at a time. Add the event handling code one piece at a time.

    At *every* step have code that compiles without any messages and is tested and found to run as you intend. That way you can have some manageable number of compiler messages to ask about (don't forget to say which is line is 69 or whatever), or some specific runtime behaviour to correct.

  5. #5
    Junior Member
    Join Date
    Nov 2012
    Posts
    29
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Event Handler For a JTextField

    Quote Originally Posted by pbrockway2 View Post
    You have variables like distance declared twice and this is causing no end of problems.

    At the risk of repeating myself, having sensible (descriptive) variables stops the problem from ever arising: distance for the distance, distanceTF for the associated text field etc.

    ---

    Formatted text fields are a reasonable idea where - as in this case - you want fields for the user to input numbers. But you might make faster progress if you worked a small step at a time addressing each of the compiler's concerns as they arise. I'm guessing you didn't address the problems in the first version of the code since the main() method which was buggy there is repeated without change.

    Honestly: keep it simple. Keep the formatted text fields for later when you have a functional gui and want to address the specific problem of the user entering invalid data. Start with as simple a gui as you can. The fewer components, the better. Add them one at a time. Add the event handling code one piece at a time.

    At *every* step have code that compiles without any messages and is tested and found to run as you intend. That way you can have some manageable number of compiler messages to ask about (don't forget to say which is line is 69 or whatever), or some specific runtime behaviour to correct.
    /*
     *
     *
    */
     
    import java.io.*;
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import java.text.*;
    import java.util.*;
    import java.awt.event.ActionListener;
     
     
    public class TripCalcUpdated extends JFrame implements ActionListener
    {
       //Declare output stream
       DataOutputStream output;
     
       String[] startStrings = { "Detroit Lakes", "Minneapolis", "Duluth", "Bemidji", "Rochester", "StCloud"};
       String[] endStrings = { "Daytona", "Darlington", "Charlotte", "Talladega", "Richmond", "Bristol"};
       float index;
     
     
       //construct components
       JLabel typePrompt = new JLabel("Vehicle Type");
       JComboBox typeCombo = new javax.swing.JComboBox();
       JTextPane typePane = new JTextPane();
     
       JLabel fuelPrompt = new JLabel("Fuel Type");
       JComboBox fuelCombo = new javax.swing.JComboBox();
       JTextPane fuelPane = new JTextPane();
     
       JLabel startPrompt = new JLabel("Starting Location");
       JComboBox startCombo = new javax.swing.JComboBox();
       JTextPane startPane = new JTextPane();
     
       JLabel endPrompt = new JLabel("Ending Location");
       JComboBox endCombo = new javax.swing.JComboBox();
       JTextPane endPane = new JTextPane();
     
     
     
        // Panel Creation
        JPanel firstRow = new JPanel();
        JPanel secondRow = new JPanel();
     
     
        // Panel for Fields and Buttons
        JPanel fieldPanel = new JPanel();
        JPanel buttonPanel = new JPanel();
     
        // Construct Labels and TextBoxes
        JLabel Miles = new JLabel("Distance to travel" );
        JTextField distance = new JTextField(5);
        JLabel Fuelcost = new JLabel("Price per gallon?"  );
        JTextField fuelprice = new JTextField(3);
        JLabel Milespergallon = new JLabel("Vehicle miles per gallon?"  );
        JTextField mpg = new JTextField(3);
        JLabel Total = new JLabel("Your estimated cost will be "   );
        JTextField totalcost = new JTextField(5);
     
        JButton submit = new JButton("Submit");
        JButton clear = new JButton("Clear Fields");
     
     
     //main method executes at run time
     public static void main(String args[])
        {
      TripCalcUpdated f = new TripCalcUpdated();
      f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      f.setContentPane(f.createContentPane());
      f.setTitle("Trip Calculator");
      f.setSize(800,300);
      f.setVisible(true);
        }
     
     
       //create the content pane
       public Container createContentPane()
       {
        //populate the JCombobox
        typeCombo.addItem("Compact");
        typeCombo.addItem("Mid-Size");
        typeCombo.addItem("Luxury");
        typeCombo.addItem("SUV");
        typeCombo.addActionListener(this);
     
        fuelCombo.addItem("Leaded");
        fuelCombo.addItem("Unleaded");
        fuelCombo.addItem("Super Unleaded");
        fuelCombo.addItem("Diesel");
        fuelCombo.addActionListener(this);
     
        startCombo.addItem("Minneapolis");
        startCombo.addItem("Duluth");
        startCombo.addItem("Bemidji");
        startCombo.addItem("Rochester");
        startCombo.addItem("Detroit Lakes");
        startCombo.addItem("St.Cloud");
        startCombo.addActionListener(this);
     
        endCombo.addItem("Daytona");
        endCombo.addItem("Darlington");
        endCombo.addItem("Las Vegas");
        endCombo.addItem("Talladega");
        endCombo.addItem("Richmond");
        endCombo.addItem("Bristol");
        endCombo.addActionListener(this);
     
        //construct and populate the north panel
        JPanel northPanel = new JPanel();
        northPanel.setLayout(new FlowLayout());
        northPanel.add(typePrompt);
        northPanel.add(typeCombo);
        northPanel.add(fuelPrompt);
        northPanel.add(fuelCombo);
        northPanel.add(startPrompt);
        northPanel.add(startCombo);
        northPanel.add(endPrompt);
        northPanel.add(endCombo);
     
        JPanel southPanel = new JPanel();
        southPanel.setLayout(new FlowLayout());
        southPanel.add(submit);
        southPanel.add(clear);
     
     
        clear.addActionListener(this);
        submit.addActionListener(this);
     
        JPanel centerPanel = new JPanel();
        centerPanel.setLayout(new FlowLayout());
        centerPanel.add(Miles);
        centerPanel.add(distance);
        centerPanel.add(Fuelcost);
        centerPanel.add(fuelprice);
        centerPanel.add(Milespergallon);
        centerPanel.add(mpg);
        centerPanel.add(Total);
        centerPanel.add(totalcost);
     
     
     
         //createContainer and set attributes
         Container f = getContentPane();
         setLayout(new BorderLayout(40,40));
         fieldPanel.setLayout(new GridLayout(1,1));
         buttonPanel.setLayout(new FlowLayout(FlowLayout.LEFT));
         add(northPanel,BorderLayout.NORTH);
         add(southPanel,BorderLayout.SOUTH);
         add(centerPanel,BorderLayout.CENTER);
         setLocation(200,200);
         return f;
         }
     
     
     
         // event to process user clicks
      public void actionPerformed(ActionEvent e)
      {
     
     
     
        String arg = e.getActionCommand();
     
     
     
         Object target = e.getSource();
           if(target == submit)
            {
             float d = Float.parseFloat(distance.getText());
             float f = Float.parseFloat(Fuelcost.getText());
             float g = Float.parseFloat(mpg.getText());
             index = (d + f + g);
             totalcost.setText("index");
            }
            else if(target == clear)
            {
            distance.setText("");
            mpg.setText("");
            fuelprice.setText("");
     
            }
      }
    }

    I've done as suggested and went with simple. My code i've kept as basic and my gui compiles and will run. When I put in numbers for the distance, mpg and price and hit submit I get plenty of errors. The same if I hit the clear fields button.

    Exception in thread "AWT-EventQueue-0" java.lang.NumberFormatException: For input string: "Price per gallon?"
    at sun.misc.FloatingDecimal.readJavaFormatString(Unkn own Source)
    at java.lang.Float.parseFloat(Unknown Source)
    at TripCalcUpdated.actionPerformed(TripCalcUpdated.ja va:173)
    at javax.swing.AbstractButton.fireActionPerformed(Unk nown Source)
    at javax.swing.AbstractButton$Handler.actionPerformed (Unknown Source)
    at javax.swing.DefaultButtonModel.fireActionPerformed (Unknown Source)
    at javax.swing.DefaultButtonModel.setPressed(Unknown Source)
    at javax.swing.plaf.basic.BasicButtonListener.mouseRe leased(Unknown Source)
    at java.awt.Component.processMouseEvent(Unknown Source)
    at javax.swing.JComponent.processMouseEvent(Unknown Source)
    at java.awt.Component.processEvent(Unknown Source)
    at java.awt.Container.processEvent(Unknown Source)
    at java.awt.Component.dispatchEventImpl(Unknown Source)
    at java.awt.Container.dispatchEventImpl(Unknown Source)
    at java.awt.Component.dispatchEvent(Unknown Source)
    at java.awt.LightweightDispatcher.retargetMouseEvent( Unknown Source)
    at java.awt.LightweightDispatcher.processMouseEvent(U nknown Source)
    at java.awt.LightweightDispatcher.dispatchEvent(Unkno wn Source)
    at java.awt.Container.dispatchEventImpl(Unknown Source)
    at java.awt.Window.dispatchEventImpl(Unknown Source)
    at java.awt.Component.dispatchEvent(Unknown Source)
    at java.awt.EventQueue.dispatchEventImpl(Unknown Source)
    at java.awt.EventQueue.access$200(Unknown Source)
    at java.awt.EventQueue$3.run(Unknown Source)
    at java.awt.EventQueue$3.run(Unknown Source)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.security.ProtectionDomain$1.doIntersectionPri vilege(Unknown Source)
    at java.security.ProtectionDomain$1.doIntersectionPri vilege(Unknown Source)
    at java.awt.EventQueue$4.run(Unknown Source)
    at java.awt.EventQueue$4.run(Unknown Source)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.security.ProtectionDomain$1.doIntersectionPri vilege(Unknown Source)
    at java.awt.EventQueue.dispatchEvent(Unknown Source)
    at java.awt.EventDispatchThread.pumpOneEventForFilter s(Unknown Source)
    at java.awt.EventDispatchThread.pumpEventsForFilter(U nknown Source)
    at java.awt.EventDispatchThread.pumpEventsForHierarch y(Unknown Source)
    at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
    at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
    at java.awt.EventDispatchThread.run(Unknown Source)

  6. #6
    Super Moderator pbrockway2's Avatar
    Join Date
    Jan 2012
    Posts
    965
    Thanks
    7
    Thanked 205 Times in 181 Posts

    Default Re: Event Handler For a JTextField

    You read the stack trace from the top down until you reach a line which mentions your code. This is a good place to begin looking for the source of the problem.

    In this case the problem is occurring at line 173 of TripCalcUpdate.java which, I assume, is

    float f = Float.parseFloat(Fuelcost.getText());

    The stacktrace describes the problem as

    java.lang.NumberFormatException: For input string: "Price per gallon?"
    In other words Fuelcost.getText() is the string "Price per gallon?" and it appears you are working with the label not the text field.

    --- Update ---

    I don't see any problem with the clear fields button.

  7. #7
    Junior Member
    Join Date
    Nov 2012
    Posts
    29
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Event Handler For a JTextField

    Quote Originally Posted by pbrockway2 View Post
    You read the stack trace from the top down until you reach a line which mentions your code. This is a good place to begin looking for the source of the problem.

    In this case the problem is occurring at line 173 of TripCalcUpdate.java which, I assume, is

    float f = Float.parseFloat(Fuelcost.getText());

    The stacktrace describes the problem as



    In other words Fuelcost.getText() is the string "Price per gallon?" and it appears you are working with the label not the text field.

    --- Update ---

    I don't see any problem with the clear fields button.
    Thanks. I saw that but couldn't figure out til you pointed it out. It works now, but I still have little tweaks to do.

  8. #8
    Super Moderator pbrockway2's Avatar
    Join Date
    Jan 2012
    Posts
    965
    Thanks
    7
    Thanked 205 Times in 181 Posts

    Default Re: Event Handler For a JTextField

    I'm glad you've got it sorted out.

    There seem to be some other problems with that event handler that should come to light as you test it. (Make sure the answers you get are reasonable!)

  9. #9
    Junior Member
    Join Date
    Nov 2012
    Posts
    29
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Event Handler For a JTextField

    Quote Originally Posted by pbrockway2 View Post
    I'm glad you've got it sorted out.

    There seem to be some other problems with that event handler that should come to light as you test it. (Make sure the answers you get are reasonable!)
    Floats aren't very precise so I will probably switch the textboxes to a formatted text box and I still need to get the comboboxes active, but I got over the first hurdle without to much difficulty. Thanks again for your help and I will probably post again with other questions.

Similar Threads

  1. JButton event handler
    By gkelly642 in forum What's Wrong With My Code?
    Replies: 3
    Last Post: April 3rd, 2013, 10:01 PM
  2. Separate Event Handler Class
    By beer-in-box in forum AWT / Java Swing
    Replies: 2
    Last Post: April 1st, 2013, 10:19 AM
  3. Replies: 0
    Last Post: June 19th, 2012, 01:58 PM
  4. Replies: 8
    Last Post: May 28th, 2012, 12:29 PM
  5. JButton event handler
    By Jsri in forum AWT / Java Swing
    Replies: 1
    Last Post: October 25th, 2011, 08:02 AM