GridLayout( )

 

Introduction.  As stated previously, without examples, a GridLayout( ) is essentially a table layout with rows, columns d cell padding.  The two main constructors are
  • GridLayout(int rows, int columns)
    • rows is the number of rows
    • columns is the number of columns
  • GridLayout(int rows, int columns, int horizontalPadding, int verticalPadding)
    • rows is the number of rows
    • columns is the number of columns
    • horizontalPadding is the number of pixels of padding between contiguous horizontal cells
    • verticalPadding is the number of pixels of padding between contiguous vertical cells

This applet will allow the user to convert degrees Fahrenheit to Celsius and vice-versa.  This program should be called ConvertTemperature.java.

 

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

public class ConvertTemperature extends JApplet implements ActionListener
{

// graphical user interface components
JLabel lblToCelsius, lblToFahrenheit, lblFromCelsius, lblFromFahrenheit;
JTextField txtToCelsius, txtToFahrenheit, txtFromCelsius, txtFromFahrenheit;
JButton cmdToCelsius, cmdToFahrenheit;
JPanel panConvert;

public void init( )
{

// setup graphical user interface components
JPanel panAdjust = new JPanel();
panAdjust.setLayout( new GridLayout(2, 5, 4, 4) );

// developing first row of the conversion form
lblFromCelsius = new JLabel( "Enter the degrees Celsius: ", SwingConstants.RIGHT );
// adds components across the row first
panAdjust.add( lblFromCelsius );

txtFromCelsius = new JTextField( 5 );
panAdjust.add( txtFromCelsius );

cmdToFahrenheit = new JButton( "Convert to Fahrenheit" );
cmdToFahrenheit.addActionListener(this);
panAdjust.add( cmdToFahrenheit );

lblToFahrenheit = new JLabel( " in Fahrenheit is: ", SwingConstants.RIGHT );
panAdjust.add( lblToFahrenheit );

txtToFahrenheit = new JTextField( 5 );
txtToFahrenheit.setEditable(false);
panAdjust.add( txtToFahrenheit );

// developing the second row of the conversion form
lblFromFahrenheit = new JLabel( "Enter the degrees Fahrenheit: ", SwingConstants.RIGHT );
// adds them across the second row
panAdjust.add( lblFromFahrenheit );

txtFromFahrenheit = new JTextField( 5 );
panAdjust.add( txtFromFahrenheit );

cmdToCelsius = new JButton( "Convert to Celsius" );
cmdToCelsius.addActionListener(this);
panAdjust.add( cmdToCelsius );

lblToCelsius = new JLabel( " in Celsius is ", SwingConstants.RIGHT);
panAdjust.add( lblToCelsius );

txtToCelsius = new JTextField( 5 );
txtToCelsius.setEditable(false);
panAdjust.add( txtToCelsius );

setContentPane(panAdjust);

} // end method init( )

// the actionEvent handler
public void actionPerformed(ActionEvent userClick)
{

double degreesCelsius = 0.0;
double degreesFahrenheit = 0.0;
boolean validInput = true;
// if statement to determine source
// of user event/click

if (userClick.getSource() == cmdToFahrenheit)
{

try
{

degreesCelsius = Double.parseDouble(txtFromCelsius.getText());

}

catch (NumberFormatException nfeFloat)
{

JOptionPane.showMessageDialog(null, "You need to enter a number", "Input Error", JOptionPane.ERROR_MESSAGE);
validInput = false;
txtFromCelsius.setText("");

}

if (validInput)

convertToFahrenheit(degreesCelsius);

}

else if (userClick.getSource() == cmdToCelsius)
{

try
{

degreesFahrenheit = Double.parseDouble(txtFromFahrenheit.getText());

}

catch (NumberFormatException nfeFloat)
{

JOptionPane.showMessageDialog(null, "You need to enter a number", "Input Error", JOptionPane.ERROR_MESSAGE);
validInput = false;
txtFromFahrenheit.setText("");

}

if (validInput)

convertToCelsius(degreesFahrenheit);

}

} // end actionPerformed( )

public void convertToFahrenheit(double celsiusTemp)
{

double fahrenheitTemp;
fahrenheitTemp = (1.8 * celsiusTemp) + 32.0;
txtToFahrenheit.setText(Double.toString(fahrenheitTemp));

} // end method convertToFahrenheit( )


public void convertToCelsius(double fahrenheitTemp)
{

double celsiusTemp;
celsiusTemp = (fahrenheitTemp - 32.0)*5.0/9.0;
txtToCelsius.setText(Double.toString(celsiusTemp));

} // end method convertToCelsius( )

} // end ConvertTemperature class

 

You should run this before we discuss the code.

The ConvertTemperature.html file follows

 

<html>
<applet code="ConvertTemperature.class" width=900 height=100>
</applet>
</html>

 

When running this you should see something similar to the following.  I used 100F and 212C.

Unfortunately, the controls fill the cells.  We are not likely to improve on this until we get to GridBagLayouts( ) at either the end of this semester or the beginning of the next.

 

 

You should try alternative inputs and flawed inputs to see the exception handling in action.

This program does the following

  • the first section of code
    • imports both the swing and awt packages and all their classes
    • imports the event classes in the awt package in order for the program to be able to respond to user inputs
    • extends JApplet
    • implements ActionListener
  • declares the GUI components within the overall inclusive ConvertTemperature class so that they will be available in all other methods in the class
  • within the method init( )
    • initializes a panel called panAdjust to contain the components
    • assigns a GridLayout with 2 rows and 5 columns to the panel
      • cell padding is 4 pixels in both horizontal and vertical firections
    • instantiates an object of the JLabel class called lblFromCelsius
      • its constructor contains a string  "Enter the degrees Celsius: "
      • it also contains the SwingConstants.Right
    • adds this label to the panel
    • instantiates an object of the JTextField class called txtFromCelsius
      • its constructor contains a 5 for the width
      • this is where the user should enter a Celsius temperature they want to convert to Fahrenheit
    • adds this text field to the panel
    • instantiates an object of the JButton class called cmdToFahrenheit
      • its constructor contains a string  "Convert To Fahrenheit"
    • adds the actionListener making use of the this operator
    • adds this button to the panel
    • instantiates an object of the JLabel class called lblToFahrenheit
      • its constructor contains a string  " in Fahrenheit is  "
      • it also contains the SwingConstants.Right
    • adds this label to the panel
    • instantiates an object of the JTextField class called txtToFahrenheit
      • its constructor contains a 5 for the width
      • its editable property is set to false so the user can't enter numbers
      • this is where the converted temperature in Fahrenheit is written
    • adds this text field to the panel
    • instantiates an object of the JLabel class called lblFromFahrenheit
      • its constructor contains a string  "Enter the degrees Fahrenheit: "
      • it also contains the SwingConstants.Right
    • adds this label to the panel
    • instantiates an object of the JTextField class called txtFromFahrenheit
      • its constructor contains a 5 for the width
      • this is where the user should enter a Fahrenheit temperature they want to convert to Celsius
    • adds this text field to the panel
    • instantiates an object of the JButton class called cmdToCelsius
      • its constructor contains a string  "Convert To Celsius"
    • adds the actionListener making use of the this operator
    • adds this button to the panel
    • instantiates an object of the JLabel class called lblToCelsius
      • its constructor contains a string  " in Celsius is  "
      • it also contains the SwingConstants.Right
    • adds this label to the panel
    • instantiates an object of the JTextField class called txtToCelsius
      • its constructor contains a 5 for the width
      • its editable property is set to false so the user can't enter numbers
      • this is where the converted temperature in Celsius is written
    • adds this text field to the panel
    • sets the overall content pane for the applet window to the panel
    • then it ends the method init( )

 

  • now the actionPerformed( ) method is declared and defined
  • an if ( expression ) else if ( expression ) code segment is used to determine which button the user clicked
    • the expressions are based on userClick.getSource( )
    • if they clicked cmdToFahrenheit
      • a try and catch block are developed to handle inputs that can't be parsed to doubles
        • the getText( ) method is used within the
        • Double.parseDouble( ) method
      • the catch block
        • gives an error message
        • sets a boolean variable relating to validInput to false
        • blanks what the user entered
      • an if statement prevents the actual conversion unless the input is valid
      • if the input is valid
        • a method convertToFahrenheit(  ) is passed the degreesCelsius obtained from the user
    • if they clicked cmdToCelsius
    • a try and catch block are developed to handle inputs that can't be parsed to doubles
      • the getText( ) method is used within the
      • Double.parseDouble( ) method
    • the catch block
      • gives an error message
      • sets a boolean variable relating to validInput to false
      • blanks what the user entered
    • an if statement prevents the actual conversion unless the input is valid
    • if the input is valid
      • a method convertToCelsius(  ) is passed the degreesFahrenheit obtained from the user

 

  • the convertToFahrenheit( ) method
    • requires an input passed from a successful try
    • declares a double for the fahhrenheitTemp
    • does the conversion
    • sets the text in the appropriate text field
      • converts the double to a String for display
      • uses setText( ) to write it in the txtToFahrenheit text field

 

 

  • the convertToCelsius( ) method
    • requires an input passed from a successful try
    • declares a double for the celsiusTemp
    • does the conversion
    • sets the text in the appropriate text field
      • converts the double to a String for display
      • uses setText( ) to write it in the txtToCelsius text field

So this ends up being the most sophisticated program we have done so far.

Notice how you can continue to work with the GUI and don't have to restart it all the time to handle new inputs and display new outputs.