{"id":214,"date":"2011-10-14T16:37:23","date_gmt":"2011-10-14T05:37:23","guid":{"rendered":"https:\/\/learn-java-by-example.com\/?p=214"},"modified":"2011-11-22T11:00:47","modified_gmt":"2011-11-22T00:00:47","slug":"convert-inches-centimetres","status":"publish","type":"post","link":"https:\/\/learn-java-by-example.com\/java\/convert-inches-centimetres\/","title":{"rendered":"Convert Inches to Centimetres"},"content":{"rendered":"

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. <\/p>\n

\r\npackage com.learnjava.swing;\r\n\r\nimport java.awt.BorderLayout;\r\nimport java.awt.Component;\r\nimport java.awt.Container;\r\nimport java.awt.event.ActionEvent;\r\nimport java.awt.event.ActionListener;\r\nimport java.text.NumberFormat;\r\n\r\nimport javax.swing.JButton;\r\nimport javax.swing.JFrame;\r\nimport javax.swing.JLabel;\r\nimport javax.swing.JOptionPane;\r\nimport javax.swing.JPanel;\r\nimport javax.swing.JTextField;\r\nimport javax.swing.Spring;\r\nimport javax.swing.SpringLayout;\r\nimport javax.swing.SwingUtilities;\r\n\r\npublic class DistanceConverter extends JPanel {\r\n\r\n\tprivate JTextField inchesEntry = new JTextField();\r\n\tprivate JTextField centimetresEntry = new JTextField();\r\n\t\r\n\tpublic DistanceConverter() {\r\n\t\tsuper(new BorderLayout());\r\n\t\t\r\n\t\t\/\/ Create the form to allow the user to enter:\r\n\t\t\/\/ the value to be converted\r\n\t\t\/\/ and the converted value\r\n\t\t\r\n\t\tJPanel form = new JPanel();\r\n\t\tJLabel inchesLabel = new JLabel("Inches:");\r\n\t\tinchesLabel.setLabelFor(inchesEntry);\r\n\t\tJLabel cmLabel = new JLabel("Centimetres:");\r\n\t\tcmLabel.setLabelFor(centimetresEntry);\r\n\t\tcentimetresEntry.setEditable(false);\r\n\t\t\r\n\t\tform.add(inchesLabel);\r\n\t\tform.add(inchesEntry);\r\n\t\tform.add(cmLabel);\r\n\t\tform.add(centimetresEntry);\r\n\t\t\r\n\t\t\/\/ Use StringLayout to layout the form\r\n\t\t\r\n\t\tspringLayoutForm(form, 2, 2);\r\n\t\t\r\n\t\tadd(BorderLayout.CENTER, form);\r\n\t\t\r\n\t\t\/\/ Add the buttons\r\n\t\t\r\n\t\tJPanel controls = new JPanel();\r\n\t\tJButton convert = new JButton("Convert");\r\n\t\tJButton clear = new JButton("Clear");\r\n\t\tJButton quit = new JButton("Quit");\r\n\t\tcontrols.add(convert);\r\n\t\tcontrols.add(clear);\r\n\t\tcontrols.add(quit);\r\n\t\tadd(BorderLayout.SOUTH, controls);\r\n\t\t\r\n\t\t\/\/ finally wire up the buttons\r\n\t\t\/\/ We do this by adding an ActionListener to each button\r\n\t\t\/\/ We use an inner class to call the method we want invoked\r\n\t\t\/\/ when the button is pressed\r\n\r\n\t\tconvert.addActionListener(new ActionListener() {\r\n\t\t\t@Override\r\n\t\t\tpublic void actionPerformed(ActionEvent e) {\r\n\t\t\t\tconvert();\r\n\t\t\t}\r\n\t\t});\r\n\r\n\t\tclear.addActionListener(new ActionListener() {\r\n\t\t\t@Override\r\n\t\t\tpublic void actionPerformed(ActionEvent e) {\r\n\t\t\t\tclear();\r\n\t\t\t}\r\n\t\t});\r\n\r\n\t\tquit.addActionListener(new ActionListener() {\r\n\t\t\t@Override\r\n\t\t\tpublic void actionPerformed(ActionEvent e) {\r\n\t\t\t\tSystem.exit(0);\r\n\t\t\t}\r\n\t\t});\r\n\t}\r\n\t\r\n\t\/**\r\n\t * Performs the actual conversion\r\n\t *\/\r\n\t\r\n\tprivate void convert() {\r\n\t\ttry {\r\n\t\t\t\r\n\t\t\t\/\/ Get the inches valued entered and convert it to a double\r\n\t\t\t\r\n\t\t\tdouble inches = Double.parseDouble(inchesEntry.getText());\r\n\t\t\t\r\n\t\t\t\/\/ Heres where we do the actual conversion from inches to cm's\r\n\t\t\t\r\n\t\t\tdouble centimetres = inches * 2.54;\r\n\t\t\t\r\n\t\t\t\/\/ Finally display the centimetre value\r\n\t\t\t\/\/ We use the NumberFormat class to format the double value\r\n\t\t\t\r\n\t\t\tcentimetresEntry.setText(\r\n\t\t\t\tNumberFormat.getInstance().format(centimetres));\r\n\t\t\r\n\t\t} catch (Exception ex) {\r\n\t\t\t\r\n\t\t\t\/\/ If the value entered by the user cannot be parsed\r\n\t\t\t\/\/ then an Exception is thrown by parseDouble()\r\n\t\t\t\/\/ And execution will end up here\r\n\t\t\t\r\n\t\t\tJOptionPane.showMessageDialog(this,\r\n\t\t\t\t"Please enter a valid number");\r\n\t\t}\r\n\t\t\t\r\n\t}\r\n\r\n\t\/**\r\n\t * Clears the gui\r\n\t *\/\r\n\t\r\n\tprivate void clear() {\r\n\t\t\r\n\t\t\/\/ Clear both text fields\r\n\t\t\r\n\t\tinchesEntry.setText("");\r\n\t\tcentimetresEntry.setText("");\r\n\t}\r\n\r\n\t\/**\r\n\t * Create and setup the main window\r\n\t *\/\r\n\t\r\n\tprivate static void createAndShowGUI() {\r\n\t\tJFrame frame = new JFrame("Distance Converter");\r\n\t\t\r\n\t\t\/\/ We want the application to exit when the window is closed\r\n\t\t\r\n\t\tframe.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);\r\n\r\n\t\t\/\/ Add the converter panel to window\r\n\t\t\r\n\t\tframe.getContentPane().add(new DistanceConverter());\r\n\t\t\r\n\t\t\/\/ Display the window.\r\n\t\t\r\n\t\tframe.pack();\r\n\t\tframe.setVisible(true);\r\n\t}\r\n\r\n\tpublic static void main(String[] args) {\r\n\t\tSwingUtilities.invokeLater(new Runnable() {\r\n\t\t\tpublic void run() {\r\n\t\t\t\tcreateAndShowGUI();\r\n\t\t\t}\r\n\t\t});\r\n\t}\r\n\r\n\t\/**\r\n\t* Aligns the rows and columns of a form\r\n\t* using a SpringLayout\r\n\t* \r\n\t* NB. We'll covers this in more detail in a future discussion on layouts\r\n\t* One of our tutors will be happy to discuss it with you if need be\r\n\t*\/\r\n\t\r\n\tprivate static void springLayoutForm(Container form, int rows, int cols) {\r\n\t\t\r\n\t\tSpringLayout layout = new SpringLayout();\r\n\t\tform.setLayout(layout);\r\n\t\r\n\t\t\/\/ Align labels and text fields in each column\r\n\t\t\r\n\t\tSpring x = Spring.constant(10);\r\n\t\tfor (int c = 0; c < cols; c++) {\r\n\t\t\tSpring width = Spring.constant(0);\r\n\t\t\tfor (int r = 0; r < rows; r++) {\r\n\t\t\t\twidth = Spring.max(width, \r\n\t\t\t\t\tgetConstraints(r, c, form, cols).getWidth());\r\n\t\t\t}\r\n\t\t\tfor (int r = 0; r < rows; r++) {\r\n\t\t\t\tSpringLayout.Constraints constraints =\r\n\t\t\t\t\tgetConstraints(r, c, form, cols);\r\n\t\t\t\tconstraints.setX(x);\r\n\t\t\t\tconstraints.setWidth(width);\r\n\t\t\t}\r\n\t\t\tx = Spring.sum(x, Spring.sum(width, Spring.constant(5)));\r\n\t\t}\r\n\t\r\n\t\t\/\/ Align all labels and text fields in each row\r\n\t\t\/\/ and make them the same height.\r\n\t\t\r\n\t\tSpring y = Spring.constant(10);\r\n\t\tfor (int r = 0; r < rows; r++) {\r\n\t\t\tSpring height = Spring.constant(0);\r\n\t\t\tfor (int c = 0; c < cols; c++) {\r\n\t\t\t\theight = Spring.max(height,\r\n\t\t\t\t\tgetConstraints(r, c, form, cols).getHeight());\r\n\t\t\t}\r\n\t\t\tfor (int c = 0; c < cols; c++) {\r\n\t\t\t\tSpringLayout.Constraints constraints =\r\n\t\t\t\t\tgetConstraints(r, c, form, cols);\r\n\t\t\t\tconstraints.setY(y);\r\n\t\t\t\tconstraints.setHeight(height);\r\n\t\t\t}\r\n\t\t\ty = Spring.sum(y, \r\n\t\t\t\t\tSpring.sum(height, Spring.constant(5)));\r\n\t\t}\r\n\t\r\n\t\t\/\/Set the form's size.\r\n\t\r\n\t\tSpringLayout.Constraints formConstraints = \r\n\t\t\tlayout.getConstraints(form);\r\n\t\tformConstraints.setConstraint(SpringLayout.SOUTH, y);\r\n\t\tformConstraints.setConstraint(SpringLayout.EAST, x);\r\n\t}\r\n\r\n\tprivate static SpringLayout.Constraints getConstraints(\r\n            int row, int col, Container parent, int cols) {\r\n\t\tSpringLayout layout = (SpringLayout) parent.getLayout();\r\n\t\tComponent c = parent.getComponent(row * cols + col);\r\n\t\treturn layout.getConstraints(c);\r\n\t}\r\n}\r\n<\/pre>\n","protected":false},"excerpt":{"rendered":"

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.<\/p>\n","protected":false},"author":1,"featured_media":217,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"jetpack_post_was_ever_published":false,"jetpack_publicize_message":"","jetpack_is_tweetstorm":false,"jetpack_publicize_feature_enabled":true,"jetpack_social_options":[]},"categories":[4,15],"tags":[19,59,61,16,17,60,12,58],"jetpack_publicize_connections":[],"jetpack_featured_media_url":"https:\/\/learn-java-by-example.com\/wp-content\/uploads\/2011\/11\/ruler.jpg","jetpack_sharing_enabled":true,"jetpack_shortlink":"https:\/\/wp.me\/p6Yyl2-3s","jetpack-related-posts":[{"id":251,"url":"https:\/\/learn-java-by-example.com\/java\/add-checkbox-items-jlist\/","url_meta":{"origin":214,"position":0},"title":"How do add a checkbox to items in a JList?","date":"June 30, 2015","format":false,"excerpt":"We often get asked about how to implement a list of checkboxes using Swing. Using a JList filled with JCheckbox's seems the obvious solution, however JList does not support cell editors so this does not work. One possible solutions is to use a single column JTable and store boolean's as\u2026","rel":"","context":"In "Java"","img":{"alt_text":"","src":"","width":0,"height":0},"classes":[]},{"id":98,"url":"https:\/\/learn-java-by-example.com\/java\/calculator-keypad\/","url_meta":{"origin":214,"position":1},"title":"Calculator Keypad","date":"August 14, 2010","format":false,"excerpt":"This problem involves understanding some of the basics of building a Swing application including how individual components are laid out inside a window, and how your application can react to the user interacting with the application. In this case we need to update a text field whenever a button is\u2026","rel":"","context":"In "Java"","img":{"alt_text":"","src":"","width":0,"height":0},"classes":[]},{"id":300,"url":"https:\/\/learn-java-by-example.com\/java\/control-decimal-places-displayed-jtable-column\/","url_meta":{"origin":214,"position":2},"title":"How to control decimal places displayed in JTable column?","date":"September 10, 2015","format":false,"excerpt":"Rendering of table cells is handled by instances of TableCellRenderer. By default JTable uses a DefaultTableCellRenderer to render all of its cells. To control the number of decimal places used we just need to subclass DefaultTableCellRenderer and format the cell double value before passing the (formatted) value to to the\u2026","rel":"","context":"In "Java"","img":{"alt_text":"","src":"","width":0,"height":0},"classes":[]},{"id":370,"url":"https:\/\/learn-java-by-example.com\/java\/iterate-dates-range\/","url_meta":{"origin":214,"position":3},"title":"How can I iterate through all dates in a range?","date":"November 23, 2013","format":false,"excerpt":"Ever wanted to iterate through a range of Date's? We can use Iterator's for looping through the elements of a Collection, but for Date's we need to implement the Date arithmetic required. The following class shows how we can create our own Iterator implementation to easily iterate over a range\u2026","rel":"","context":"In "Java"","img":{"alt_text":"","src":"","width":0,"height":0},"classes":[]},{"id":205,"url":"https:\/\/learn-java-by-example.com\/java\/counting-numbers\/","url_meta":{"origin":214,"position":4},"title":"Counting numbers","date":"September 12, 2011","format":false,"excerpt":"The assignment here is to read a text file containing a list of numbers. We need to report how many numbers were in the file, the sum of all the numbers, the average of all numbers, and the minimum and maximum number. First step is to read the file and\u2026","rel":"","context":"In "Featured"","img":{"alt_text":"","src":"","width":0,"height":0},"classes":[]},{"id":222,"url":"https:\/\/learn-java-by-example.com\/java\/list-array\/","url_meta":{"origin":214,"position":5},"title":"Using a List instead of an array","date":"March 8, 2012","format":false,"excerpt":"Lists and arrays can both be used to store ordered collections of data. Both have their strengths and weakness which we shall discuss in a later post. Previously we showed you how to generate Pascals Triangle and in that Java example we used arrays to represent each row of the\u2026","rel":"","context":"In "Java"","img":{"alt_text":"","src":"","width":0,"height":0},"classes":[]}],"_links":{"self":[{"href":"https:\/\/learn-java-by-example.com\/wp-json\/wp\/v2\/posts\/214"}],"collection":[{"href":"https:\/\/learn-java-by-example.com\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/learn-java-by-example.com\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/learn-java-by-example.com\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/learn-java-by-example.com\/wp-json\/wp\/v2\/comments?post=214"}],"version-history":[{"count":6,"href":"https:\/\/learn-java-by-example.com\/wp-json\/wp\/v2\/posts\/214\/revisions"}],"predecessor-version":[{"id":221,"href":"https:\/\/learn-java-by-example.com\/wp-json\/wp\/v2\/posts\/214\/revisions\/221"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/learn-java-by-example.com\/wp-json\/wp\/v2\/media\/217"}],"wp:attachment":[{"href":"https:\/\/learn-java-by-example.com\/wp-json\/wp\/v2\/media?parent=214"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/learn-java-by-example.com\/wp-json\/wp\/v2\/categories?post=214"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/learn-java-by-example.com\/wp-json\/wp\/v2\/tags?post=214"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}