Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 3 of 3
  1. #1
    New to the CF scene
    Join Date
    Apr 2013
    Posts
    1
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Java GUI trip calculator

    Hello everyone,

    I am new to Java and I am trying to complete this exercise. I have most of it working but I am running into some issues with it. The problem I am having is solely with the durationText portion. I need to find a way to make it change as I change other parts of the calculator. However, it doesn't do this and even its simple calculation is giving me bizarre results. Its driving me mad.
    PHP Code:
        //Import GUI Packages
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import java.io.*;
    import java.util.Scanner;
    import java.text.DecimalFormat;   //Formats numeric data



    public class TripCalculator extends JFrame
    {
       
    // Set constant for file used to provide input data
       
    final String INPUT_FILE "Mileage.txt";

       
    // Set constants for window size
       
    private final int WIDTH 350;
       private final 
    int HEIGHT 250;
       
       
    // Set constants for array size
       
    private final int ROWS 7;
       private final 
    int COLUMNS 8;
       
       
    // Declare 2-dimensional array for holding data from text file
       
    private String[][] fileData = new String[ROWS][COLUMNS];
        
        
        
    //This string has the values for the average speeds
        
    private String[] speeds = {"","50","60","70","80","90","100","110","120"};

       
    // Declare panel and panel components
        
    private JPanel panel;                         // Panel
       
    private JMenuBar menuBar;                     // Menu bar
       
    private JMenu fileMenu;                       // File menu
       
    private JMenuItem fileExitItem;               // File Exit menu item
       
    private JMenu optionsMenu;                    // Help menu
       
    private JMenuItem optionsAboutItem;           // Help tool tips
        
    private JLabel destinationLabel;              // Label for Desination box
        
    private JComboBox destinationBox;             // Destination Dropbox
        
    private JLabel originLabel;                   // Label for Origin
        
    private JComboBox originBox;                  // Origin Destination Drop Box
        
    private JRadioButton milesRadioButton;        // Radio button selecting miles
        
    private JRadioButton kilometersRadioButton;   // Radio button selecting kilometers
        
    private ButtonGroup radioButtonGroup;         // For grouping the radio buttons
        
    private JLabel distanceLabel;                 // Label for the distance field after calculation
        
    private JTextField distanceText;              // Results for the distance calculation
        
    private JLabel avgspeedLabel;                 // Label for the average speed drop box
        
    private JComboBox avgspeedBox;                // Average Speed Drop box
        
    private JLabel durationLabel;                 // Label for the trip duration
        
    private JTextField durationText;              // Duration output text box
        
    private int rowcolumn;                      // Designates int values for rows/columns
        
    private boolean inKm;                         // Boolean true/false value for km/miles metric conversion

        
        
    DecimalFormat tripD = new DecimalFormat ("#0.0"); // Decimal Format to put ditance to a single decimal point 
        
       
       // Constructor.
       
    public TripCalculator()
       {
          
    // Call method to load data from text file
          
    loadData();

          
    // Set window attributes
          
    setTitle("Trip Calculator");                    // Set window title
          
    setSize(WIDTHHEIGHT);                         // Set window size
          
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // Set close button behavior
            
    setResizable (false);                           // Set window to be unresizable

          //Call method to build menu bar        
            
    buildMenuBar(); 

          
    // Call method to build panel
          
    buildPanel();
          
          
    // Add panel to the frame's content pane
          
    add(panel);
                
          
    // Display window
          
    setVisible(true);
            
            
    //Centers the window on screen
            
    setLocationRelativeTo(null);
       }
        

        
    //This will load the Mileage.txt data into the array
        
    private void loadData()
        {
            
    // Declare local variables
          
    File file;
          
    Scanner input;
          
    String fileRow;
          
    String[] rowItems;

          
    // Use exception handling block to verify existence of data file
          
    try
          {
             
    file = new File(INPUT_FILE);
             
    input = new Scanner(file);

             
    //Reads data from file and stores it in array
             
    for (int row 0row ROWSrow++)
             {
                
    fileRow input.nextLine();
                
    rowItems fileRow.split(",");
                
                for (
    int col 0col COLUMNScol++)
                {
                   
    fileData[row][col] = rowItems[col];
                }
             }
          }
          catch (
    FileNotFoundException e)
          {
             
    JOptionPane.showMessageDialog(null"Data file not found. ");
             
    System.exit(0);
          }
            
       }

        
        
    //configures the panel
        
    private void buildPanel()
        {
           
    //Create the Destination and Origin City labels and combo boxes tying    them to the arrayed data
            
    destinationLabel = new JLabel ("Destination City: ");
            
    destinationBox = new JComboBox();
            for (
    int index 1index ROWSindex++)
             
    destinationBox.addItem(fileData[index][0]);
         
            
            
    originLabel = new JLabel ("Origin City: ");
            
    originBox = new JComboBox();
            for (
    int index 1index COLUMNSindex++)
             
    originBox.addItem(fileData[0][index]);

          
    //Label and box for Avg speed
            
    avgspeedLabel = new JLabel ("Avg. Speed(mph): ");
            
    avgspeedBox = new JComboBox(speeds);
            
            
                        
            
            
    //Distance label and text
            
    distanceLabel = new JLabel ("Distance (Miles): ");
            
    distanceText = new JTextField(10);
          
    distanceText.setEditable(false); // Make text field read-only 
          
    distanceText.setFont(new Font("SansSerif"Font.BOLD12));
            
    distanceText.setText("0");
          
            
            
    //Duration
            
    durationLabel = new JLabel("Trip Duration (hours): ");
            
    durationText = new JTextField(10);
          
    durationText.setEditable(false); // Make text field read-only 
            
    durationText.setFont(new Font("SansSerif"Font.BOLD12));
              
                
            
    //Register action for the combo boxes
            
    originBox.addActionListener(new ComboBoxListener());
            
    destinationBox.addActionListener(new ComboBoxListener());
            
    avgspeedBox.addActionListener(new SpeedListener());
            
            
    // Create radio buttons for miles and kilometer conversion
          
    milesRadioButton = new JRadioButton("Miles"true);
          
    kilometersRadioButton = new JRadioButton("Kilometers");
            
          
    //Actionlisteners for the radio buttons
          
    kilometersRadioButton.addActionListener(new RadioButtonListener());
            
    milesRadioButton.addActionListener(new RadioButtonListener());

            
            
    //Create Button Group
            
    radioButtonGroup = new ButtonGroup();
          
    radioButtonGroup.add(milesRadioButton);
          
    radioButtonGroup.add(kilometersRadioButton);
            
    milesRadioButton.setSelected(true);
          
       
            
    // Create panel and add components to it
          
    panel = new JPanel();
          
    panel.setLayout(new GridLayout(63));
          
    panel.add(destinationLabel);
          
    panel.add(destinationBox);
            
    panel.add(originLabel);
            
    panel.add(originBox);
            
    panel.add(milesRadioButton);
          
    panel.add(kilometersRadioButton);
            
    panel.add(distanceLabel);
            
    panel.add(distanceText);
            
    panel.add(avgspeedLabel);
            
    panel.add(avgspeedBox);
            
    panel.add(durationLabel);
            
    panel.add(durationText);
        }    
                
      
    //builds the menubar
        
    private void buildMenuBar()
       {
          
    // Create the menu bar
          
    menuBar = new JMenuBar();
          
          
    // Create the File and Options menus
          
    buildFileMenu();
          
    buildOptionsMenu();
          
          
    // Add File and Options menus to menu bar
          
    menuBar.add(fileMenu);
          
    menuBar.add(optionsMenu);
          
          
    //Set the window's menu bar
          
    setJMenuBar(menuBar);
        }
        
        
    //builds the file menu
        
    private void buildFileMenu()
        {
            
            
    // Create File menu
          
    fileMenu = new JMenu("File");
          
    fileMenu.setMnemonic(KeyEvent.VK_F);

          
    // Create Exit menu item
          
    fileExitItem = new JMenuItem("Exit");
          
    fileExitItem.setMnemonic(KeyEvent.VK_X);
          
    fileExitItem.addActionListener(new ExitItemListener());
          
          
    // Add Exit menu item to File menu
          
    fileMenu.add(fileExitItem);
        }
        private class 
    ExitItemListener implements ActionListener
       
    {
          public 
    void actionPerformed(ActionEvent e)
          {
             
    System.exit(0); // Exit program
          
    }
        }

        
        
    //builds the options menu
        
    private void buildOptionsMenu()
       {
          
    optionsMenu = new JMenu("Help");
          
    optionsMenu.setMnemonic(KeyEvent.VK_O);

          
    // Create Color menu item
          
    optionsAboutItem = new JMenuItem("About");
          
    optionsAboutItem.setMnemonic(KeyEvent.VK_C);
          
    optionsAboutItem.addActionListener(new AboutItemListener());

         
    // Add Color menu item to Options menu
          
    optionsMenu.add(optionsAboutItem);
       }
        private class 
    AboutItemListener implements ActionListener
        
    {
            public 
    void actionPerformed(ActionEvent e)
            {
                
    JOptionPane.showMessageDialog(null"Trip Calculator Application" "\nCopyright 2013 - T. Todd");
            }
        }
        
        
    //This combines the two row/column values so we can update them with a single class
          
    private void setCities(int rowint column
        {
        
    this.row row;
        
    this.column column;
        }

        
    //This boolean makes it so that we can call the methods through radio buttons as an false/true statement
        //By using it we can designate the km or miles calculation with true/false
        
    private void setKm(boolean inKm
        {
        
        
    this.inKm inKm;
         
        }

        
    // This gives one place to set the distance text, so it can be used later as we will just call it. 
        
        
    private void updateDistanceText() 
        {
        
    String text fileData[row+1][column+1];
         
        if (
    inKm
         {
            
            
    text String.format("%.0f"MetricConverter.milesToKilometers(Double.valueOf(text))); //This expression formats our result to a single decimal place      
              
        
    }
          
        
    distanceText.setText(text);
        }  
        
        private 
    void updateTripDurationText()
        {
            
            
    String speed = (String)avgspeedBox.getSelectedItem();
            
    String dist = (String)distanceText.getText();
            
            
            
            
    double s Double.parseDouble(speed);
            
    double d Double.parseDouble(dist);
            
    double durationTime d/s;
            
    String dTime String.format("1%.1f"Double.valueOf(durationTime));
            
            
            
    durationText.setText(dTime);
            
                                         
       }
        
        private class 
    SpeedListener implements ActionListener
        
    {
            public 
    void actionPerformed(ActionEvent e)
            {
            
    updateTripDurationText();
            }
        }

        
        private class 
    ComboBoxListener implements ActionListener
       
    {
            
            
          public 
    void actionPerformed(ActionEvent e)
          {
                
                
    setCities(destinationBox.getSelectedIndex(),originBox.getSelectedIndex());
             
    updateDistanceText();
                
    updateTripDurationText();        
                
           }
            
       }
        
        
    //This is the actionlistender that triggers our actions when the radio buttons are used. Miles is selected  by default however.
        
    private class RadioButtonListener implements ActionListener
       
    {
                 
          public 
    void actionPerformed (ActionEvent event)
          {    
              
            if (
    event.getSource() == kilometersRadioButton)
             {
                     
    distanceLabel.setText("Distance (kilometers):");
                    
    avgspeedLabel.setText("Avg. Speeg (kph): ");
                    
    setKm(true);
                    
                
             }
             else if (
    event.getSource() == milesRadioButton)
             {
                    
    distanceLabel.setText("Distance (miles): ");
                    
    avgspeedLabel.setText("Avg. Speeg (mph): ");
                    
    setKm(false);
                
             }
                
    updateDistanceText();
                
    updateTripDurationText();
                
            }
             
       }
        
        public static 
    void main(String[] args)
       {
          new 
    TripCalculator();
       }

    This is the code for it, the problem has something to do with how I dealt with TripDurationText. It gives me ridiculous results, such that 682/50 == 113 when I am using kilometers or miles.

    Thank you for your assistance.
    Last edited by Fou-Lu; 04-12-2013 at 09:49 PM.

  • #2
    Regular Coder
    Join Date
    Jan 2013
    Location
    Germany
    Posts
    578
    Thanks
    4
    Thanked 77 Times in 77 Posts
    This is the Javascript forum, not Java. They are entirely different languages. Also, please use code-Tags to display your code correctly.

  • #3
    God Emperor Fou-Lu's Avatar
    Join Date
    Sep 2002
    Location
    Saskatoon, Saskatchewan
    Posts
    16,994
    Thanks
    4
    Thanked 2,662 Times in 2,631 Posts
    This is a lot of code to go through just to see what you are trying to do.
    You can always go the long way, which is to simply issue a change in this field on every possible listener attached to the ones controlling it. There are alternatives as well depending on the overall picture, things like DocumentListeners and change listeners can be added to work the other way around. So instead of directly calling a change to acomponent.setText for example, you then chain the .addDocumentListener to a JTextField's document, so whenever it changes you can capture the change in the documentlistener handler. That can then be used to control another textfield, so this has the benefit of keeping them separate so that a change in xJTextField doesn't need to concern itself with changing yJTextField. If that makes sense. You can do it with straight action listeners themselves as well, these are stackable event handlers, so one is triggered and then the next, and so on. It just depends on exactly what you want to do for what you want to change. I typically use change and action listeners over most other types, but if I were doing something like a pattern match for input (I've done this with barcode scanners for example), I use documentlisteners to trigger as the text is being input into the field instead of needing to click something.
    PHP Code:
    header('HTTP/1.1 420 Enhance Your Calm'); 
    Been gone for a few months, and haven't programmed in that long of a time. Meh, I'll wing it ;)


  •  

    Posting Permissions

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