Convert Inches to Centimetres

Java, Swing 14.10.2011 No Comments
Convert Inches to Centimetres

The next example was kindly shared by one of our members. She had a Java Swing assignment to create a Swing GUI for converting Inches to Centimetres and had no idea where to start. We helped her break down the problem and come up with a solution. The resulting code can be found below.

package com.learnjava.swing;

import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.Container;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.text.NumberFormat;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.Spring;
import javax.swing.SpringLayout;
import javax.swing.SwingUtilities;

public class DistanceConverter extends JPanel {

	private JTextField inchesEntry = new JTextField();
	private JTextField centimetresEntry = new JTextField();
	public DistanceConverter() {
		super(new BorderLayout());
		// Create the form to allow the user to enter:
		// the value to be converted
		// and the converted value
		JPanel form = new JPanel();
		JLabel inchesLabel = new JLabel("Inches:");
		JLabel cmLabel = new JLabel("Centimetres:");
		// Use StringLayout to layout the form
		springLayoutForm(form, 2, 2);
		add(BorderLayout.CENTER, form);
		// Add the buttons
		JPanel controls = new JPanel();
		JButton convert = new JButton("Convert");
		JButton clear = new JButton("Clear");
		JButton quit = new JButton("Quit");
		add(BorderLayout.SOUTH, controls);
		// finally wire up the buttons
		// We do this by adding an ActionListener to each button
		// We use an inner class to call the method we want invoked
		// when the button is pressed

		convert.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {

		clear.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {

		quit.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
	 * Performs the actual conversion
	private void convert() {
		try {
			// Get the inches valued entered and convert it to a double
			double inches = Double.parseDouble(inchesEntry.getText());
			// Heres where we do the actual conversion from inches to cm's
			double centimetres = inches * 2.54;
			// Finally display the centimetre value
			// We use the NumberFormat class to format the double value
		} catch (Exception ex) {
			// If the value entered by the user cannot be parsed
			// then an Exception is thrown by parseDouble()
			// And execution will end up here
				"Please enter a valid number");

	 * Clears the gui
	private void clear() {
		// Clear both text fields

	 * Create and setup the main window
	private static void createAndShowGUI() {
		JFrame frame = new JFrame("Distance Converter");
		// We want the application to exit when the window is closed

		// Add the converter panel to window
		frame.getContentPane().add(new DistanceConverter());
		// Display the window.

	public static void main(String[] args) {
		SwingUtilities.invokeLater(new Runnable() {
			public void run() {

	* Aligns the rows and columns of a form
	* using a SpringLayout
	* NB. We'll covers this in more detail in a future discussion on layouts
	* One of our tutors will be happy to discuss it with you if need be
	private static void springLayoutForm(Container form, int rows, int cols) {
		SpringLayout layout = new SpringLayout();
		// Align labels and text fields in each column
		Spring x = Spring.constant(10);
		for (int c = 0; c < cols; c++) {
			Spring width = Spring.constant(0);
			for (int r = 0; r < rows; r++) {
				width = Spring.max(width, 
					getConstraints(r, c, form, cols).getWidth());
			for (int r = 0; r < rows; r++) {
				SpringLayout.Constraints constraints =
					getConstraints(r, c, form, cols);
			x = Spring.sum(x, Spring.sum(width, Spring.constant(5)));
		// Align all labels and text fields in each row
		// and make them the same height.
		Spring y = Spring.constant(10);
		for (int r = 0; r < rows; r++) {
			Spring height = Spring.constant(0);
			for (int c = 0; c < cols; c++) {
				height = Spring.max(height,
					getConstraints(r, c, form, cols).getHeight());
			for (int c = 0; c < cols; c++) {
				SpringLayout.Constraints constraints =
					getConstraints(r, c, form, cols);
			y = Spring.sum(y, 
					Spring.sum(height, Spring.constant(5)));
		//Set the form's size.
		SpringLayout.Constraints formConstraints = 
		formConstraints.setConstraint(SpringLayout.SOUTH, y);
		formConstraints.setConstraint(SpringLayout.EAST, x);

	private static SpringLayout.Constraints getConstraints(
            int row, int col, Container parent, int cols) {
		SpringLayout layout = (SpringLayout) parent.getLayout();
		Component c = parent.getComponent(row * cols + col);
		return layout.getConstraints(c);

Leave a Reply