User Input

Classic programmed-learning exercises, refreshed for modern Java and presented in the current MrStyner.com portfolio style.

Modern Java noteThis archive has been refreshed for Java 25 LTS. Core language concepts remain useful, while outdated setup instructions and browser-era Java are labeled or replaced. Java 26 is the current feature release; Java 25 is used here as the stable teaching baseline.
go to previous page   go to home page   go to next page

Answer:

JTextField.getText()

User Input

A JTextField holds the text that the user entered into the field. Your program can get that text using the getText() method. But, even though the user might have entered a string of digits, you can't retrieve a numeric type (like int) from the field. Your program must retrieve the text, and then convert it to a number.

Luckily, the parseInt() method of the wrapper class Integer can convert appropriate text into an int. It is a static method, so you do not need to construct an object to use it.

Here is the program so far. To finish it fill in the remaining blanks.

  1. Use the getText() method to get the user's input.
  2. Use the parseInt() static method of the wrapper class Integer to convert the input to an int.
  3. Use the setText() method to convert and display the result in outCel.
import java.awt.*; 
import java.awt.event.*;
   
public class FahrConvert extends JFrame implements ActionListener
{
  JLabel heading  = new JLabel("Convert Fahrenheit to Celsius");
  JLabel inLabel  = new JLabel("Fahrenheit    ");
  JLabel outLabel = new JLabel("Celsius ");
   
  JTextField inFahr = new JTextField( 7 );
  JTextField outCel = new JTextField( 7 );
    
  int fahrTemp ;
  int celsTemp ;
   
   . . . .
   
  public void actionPerformed( ActionEvent evt)  
  {
    String userIn = inFahr. ;
    fahrTemp = Integer. ( userIn );
    celsTemp = convert( fahrTemp ) ;
  
    outCel.( celsTemp + "" );
    repaint();                  
  }
   . . . .  
}

QUESTION 6:

What is going on with:

outCel.setText( celsTemp+"" );