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:");
		inchesLabel.setLabelFor(inchesEntry);
		JLabel cmLabel = new JLabel("Centimetres:");
		cmLabel.setLabelFor(centimetresEntry);
		centimetresEntry.setEditable(false);
		
		form.add(inchesLabel);
		form.add(inchesEntry);
		form.add(cmLabel);
		form.add(centimetresEntry);
		
		// 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");
		controls.add(convert);
		controls.add(clear);
		controls.add(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() {
			@Override
			public void actionPerformed(ActionEvent e) {
				convert();
			}
		});

		clear.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent e) {
				clear();
			}
		});

		quit.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent e) {
				System.exit(0);
			}
		});
	}
	
	/**
	 * 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
			
			centimetresEntry.setText(
				NumberFormat.getInstance().format(centimetres));
		
		} 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
			
			JOptionPane.showMessageDialog(this,
				"Please enter a valid number");
		}
			
	}

	/**
	 * Clears the gui
	 */
	
	private void clear() {
		
		// Clear both text fields
		
		inchesEntry.setText("");
		centimetresEntry.setText("");
	}

	/**
	 * 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
		
		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

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

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

	/**
	* 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();
		form.setLayout(layout);
	
		// 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);
				constraints.setX(x);
				constraints.setWidth(width);
			}
			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);
				constraints.setY(y);
				constraints.setHeight(height);
			}
			y = Spring.sum(y, 
					Spring.sum(height, Spring.constant(5)));
		}
	
		//Set the form's size.
	
		SpringLayout.Constraints formConstraints = 
			layout.getConstraints(form);
		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

s2Member®