Java Notes

Example - Kilometers to Miles - Complete

KmToMi user interface

Here is the entire working program. The code that adds and defines a button listener is at Note 1 and Note 2.

  1 
  2 
  3 
  4 
  5 
  6 
  7 
  8 
  9 
 10 
 11 
 12 
 13 
 14 
 15 
 16 
 17 
 18 
 19 
 20 
 21 
 22 
 23 
 24 
 25 
 26 
 27 
 28 
 29 
 30 
 31 
 32 
 33 
 34 
 35 
 36 
 37 
 38 
 39 
 40 
 41 
 42 
 43 
 44 
 45 
 46 
 47 
 48 
 49 
 50 
 51 
 52 
 53 
 54 
 55 
 56 
 57 
 58 
 59 
 60 
 61 
 62 
 63 
 64 
 65 
 66 
 67 
 68 
 69 
 70 
 71 
// intro-window/KmToMiles.java - Converts Kilometers to Miles.
// Fred Swartz, 2004-10-28

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;

//////////////////////////////////////////////////////// class KmToMiles
class KmToMiles {
    //====================================================== method main
    public static void main(String[] args) {
        JFrame window = new KmToMilesGUI();
        window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        window.setVisible(true);
    }
}


///////////////////////////////////////////////////// class KmToMilesGUI
class KmToMilesGUI extends JFrame {
    //======================================= instance variables
    private JTextField m_milesTf      = new JTextField(10);
    private JTextField m_kilometersTf = new JTextField(10);
    private JButton    m_convertBtn   = new JButton("Convert");


    //====================================================== constructor
    public KmToMilesGUI() {
        //... Create content panel, set layout, add components
        JPanel content = new JPanel();
        content.setLayout(new FlowLayout());   // use FlowLayout
        content.add(new JLabel("Kilometers")); // create, add label
        content.add(m_kilometersTf);           // add input field
        content.add(m_convertBtn);             // add button
        content.add(new JLabel("Miles"));      // create, add label
        content.add(m_milesTf);                // add output field
        this.setContentPane(content); 
        this.pack();
        
        //... Add listener                               //Note 1
        m_convertBtn.addActionListener(new ConvertBtnListener());
        
        //... Set window characteristics
        this.setTitle("Kilometers to Miles");
    }//end constructor  
    
    
    //================================================ ConvertBtnListener
    class ConvertBtnListener implements ActionListener {  //Note 2
        public void actionPerformed(ActionEvent e) {
            //... Get the value from the km textfield.
            String kmStr = m_kilometersTf.getText();      //Note 3
            double km = Double.parseDouble(kmStr);
            
            //... Convert it
            double mi = convertKmToMi(km);                //Note 4
            
            //... Convert it to a string and set mi textfield
            m_milesTf.setText("" + mi);                   //Note 5
        }
    }
    
    
    //===================================================== convertKmToMi
    public static double convertKmToMi(double kilometers) {
        // Assume there are 0.621 miles in a kilometer.
        double miles = kilometers * 0.621;
        return miles;
    }
}//end class KmToMilesGUI

Notes



Note 1: The addActionListener() method is called to add a "listener" to a button. When the button is pressed, the actionPerformed() method of the listener object is called. See below.

Note 2: There are many ways to define a listener. This is one of most common - define an inner class that "implements ActionListener", and in that class define the actionPerformed() method.

Note 3: Get the text from a JTextField with a call to its getText() method. This always returns a string. In this case the string must be converted to a number before it can be used in the computation.

Note 4: We could have jsut put this simple computation right here instead of calling another function, but it's a good idea to get used to separating the user interface code from the "model" or "logic" code.

Note 5: Set the value of a JTextField by calling its setText() method and passing a string to it.

Other Possibilities

Some other common variations to structuring a program.