{"id":98,"date":"2010-08-14T15:43:02","date_gmt":"2010-08-14T05:43:02","guid":{"rendered":"https:\/\/learn-java-by-example.com\/?p=98"},"modified":"2011-06-03T16:18:43","modified_gmt":"2011-06-03T06:18:43","slug":"calculator-keypad","status":"publish","type":"post","link":"https:\/\/learn-java-by-example.com\/java\/calculator-keypad\/","title":{"rendered":"Calculator Keypad"},"content":{"rendered":"

\"\"<\/p>\n

Here we will cover creating a simple Swing application that provides a keypad similar to what you would find on a calculator. It should include a button for each digit (0-9) and the field to display the numbers entered.\n<\/p>\n

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

The key points to implementing a solution to this problem are outlined below.<\/p>\n

Laying out the buttons<\/h4>\n

Swing uses layout managers to handle the positioning of components. In our case we’ll use a GridLayout to handle laying out our buttons in a 3 x 4 grid.<\/p>\n

Once we have our parent JPanel managed by a GridLayout all we then need is to create the buttons and add them to the panel. A simple for loop can be used to achieve this task.<\/p>\n

\r\n\/\/ Create a panel for the buttons\r\n\/\/ We'll use a GridLayout to display the buttons in a grid\r\n\t\t\r\nJPanel buttons = new JPanel(new GridLayout(3, 4));\r\nfor (int i=0; i<10; i++) {\r\n\tJButton button = new JButton(Integer.toString(i));\r\n\tbuttons.add(button);\r\n}\r\n<\/pre>\n

Making our buttons work<\/h4>\n

When a button is pressed we need our application to get called so that we can update the text field. We can use a ActionListener to achieve this. <\/p>\n

\r\n\/\/ By adding an ActionListener to our button we\r\n\/\/ can get notified when the button has been pressed \r\n\t\t\t\r\nbutton.addActionListener(this);\r\n<\/pre>\n

By adding an ActionListener to our button we are telling the button to call the ActionListener’s actionPerformed() method everytime it is pressed. So then in our actionPerformed() method we can update text field with the digit from the button that was pressed.<\/p>\n

\r\n\/**\r\n * Called when a button is pressed\r\n *\/\r\n\t\r\n@Override\r\npublic void actionPerformed(ActionEvent event) {\r\n\t\t\r\n\t\/\/ Determine which key was pressed\r\n\t\t\r\n\tString key = event.getActionCommand();\r\n\t\t\r\n\t\/\/ Insert the pressed key into our text fields Document\r\n\t\t\r\n\ttry {\r\n\t\tdisplay.insertString(display.getLength(), key, null);\r\n\t} catch (BadLocationException e) {\r\n\t\te.printStackTrace();\r\n\t}\r\n}\r\n\r\n<\/pre>\n

Here’s the final code.<\/p>\n

\r\npackage com.learnjava.swing;\r\n\r\nimport java.awt.BorderLayout;\r\nimport java.awt.GridLayout;\r\nimport java.awt.event.ActionEvent;\r\nimport java.awt.event.ActionListener;\r\n\r\nimport javax.swing.JButton;\r\nimport javax.swing.JFrame;\r\nimport javax.swing.JPanel;\r\nimport javax.swing.JTextField;\r\nimport javax.swing.SwingUtilities;\r\nimport javax.swing.text.BadLocationException;\r\nimport javax.swing.text.Document;\r\n\r\npublic class Keypad extends JPanel implements ActionListener {\r\n\r\n\t\/\/ Document display by the text field\r\n\t\r\n\tprivate Document display = null;\r\n\t\r\n\t\/**\r\n\t * Creates a key pad panel containing a button for each digit (0 - 9)\r\n\t * And a text field for displaying what's pressed\r\n\t *\/\r\n\t\r\n\tpublic Keypad() {\r\n\t\tsuper(new BorderLayout());\r\n\t\t\r\n\t\t\/\/ Create a panel for the buttons\r\n\t\t\/\/ We'll use a GridLayout to display the buttons in a grid\r\n\t\t\r\n\t\tJPanel buttons = new JPanel(new GridLayout(3, 4));\r\n\t\tfor (int i=0; i<10; i++) {\r\n\t\t\tJButton button = new JButton(Integer.toString(i));\r\n\t\t\t\r\n\t\t\t\/\/ By adding an ActionListener to our button we\r\n\t\t\t\/\/ can get notified when the button has been pressed \r\n\t\t\t\r\n\t\t\tbutton.addActionListener(this);\r\n\t\t\tbuttons.add(button);\r\n\t\t}\r\n\t\t\r\n\t\t\/\/ Create a text field to display the numbers entered\r\n\t\t\r\n\t\tJTextField displayField = new JTextField();\r\n\t\tdisplay = displayField.getDocument();\r\n\t\tadd(BorderLayout.CENTER, buttons);\r\n\t\tadd(BorderLayout.SOUTH, displayField);\r\n\t}\r\n\t\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("Keypad");\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 key pad to window\r\n\t\t\r\n\t\tframe.getContentPane().add(new Keypad());\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\t\r\n\t\/**\r\n\t * Called when a button is pressed\r\n\t *\/\r\n\t\r\n\t@Override\r\n\tpublic void actionPerformed(ActionEvent event) {\r\n\t\t\r\n\t\t\/\/ Determine which key was pressed\r\n\t\t\r\n\t\tString key = event.getActionCommand();\r\n\t\t\r\n\t\t\/\/ Insert the pressed key into our text fields Document\r\n\t\t\r\n\t\ttry {\r\n\t\t\tdisplay.insertString(display.getLength(), key, null);\r\n\t\t} catch (BadLocationException e) {\r\n\t\t\te.printStackTrace();\r\n\t\t}\r\n\t}\r\n\t\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\r\n<\/pre>\n

Once you understand the basic concepts involved we will build on this example in a future post to include more features such as a delete key and some arithmetic operator buttons.<\/p>\n","protected":false},"excerpt":{"rendered":"

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 pressed. The key points to…<\/p>\n","protected":false},"author":1,"featured_media":0,"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,18,20,16,17],"jetpack_publicize_connections":[],"jetpack_featured_media_url":"","jetpack_sharing_enabled":true,"jetpack_shortlink":"https:\/\/wp.me\/p6Yyl2-1A","jetpack-related-posts":[{"id":56,"url":"https:\/\/learn-java-by-example.com\/java\/monthly-payment-calculator\/","url_meta":{"origin":98,"position":0},"title":"Monthly Payment Calculator","date":"June 2, 2010","format":false,"excerpt":"This is the simplest form of one of the classic problems given to first year Java students. It aims to get you comfortable with the structure of a simple Java application and how to get input from the user. User input in this example is taken from the console (standard\u2026","rel":"","context":"In "Java"","img":{"alt_text":"","src":"","width":0,"height":0},"classes":[]},{"id":214,"url":"https:\/\/learn-java-by-example.com\/java\/convert-inches-centimetres\/","url_meta":{"origin":98,"position":1},"title":"Convert Inches to Centimetres","date":"October 14, 2011","format":false,"excerpt":"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\u2026","rel":"","context":"In "Java"","img":{"alt_text":"","src":"","width":0,"height":0},"classes":[]},{"id":308,"url":"https:\/\/learn-java-by-example.com\/java\/jscrollpane-display-scroll-bars\/","url_meta":{"origin":98,"position":2},"title":"How do I get a JScrollPane to always display scroll bars?","date":"November 6, 2015","format":false,"excerpt":"You can achieve this by setting the scroll bar policy on both the verical and horizontal scroll bars.","rel":"","context":"In "Java"","img":{"alt_text":"","src":"","width":0,"height":0},"classes":[]},{"id":251,"url":"https:\/\/learn-java-by-example.com\/java\/add-checkbox-items-jlist\/","url_meta":{"origin":98,"position":3},"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":96,"url":"https:\/\/learn-java-by-example.com\/java\/simple-mortgage-calculator\/","url_meta":{"origin":98,"position":4},"title":"Simple Mortgage Calculator","date":"June 5, 2010","format":false,"excerpt":"This example expands on the Monthly Payment Calculator example we posted earlier. As well as calculating the monthly payment for a loan, it then goes on to use that to calculate the balance of the loan after each payment. This is often referred to as an amortisation schedule. The displayMonthlyBalance()\u2026","rel":"","context":"In "Featured"","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":98,"position":5},"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":[]}],"_links":{"self":[{"href":"https:\/\/learn-java-by-example.com\/wp-json\/wp\/v2\/posts\/98"}],"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=98"}],"version-history":[{"count":11,"href":"https:\/\/learn-java-by-example.com\/wp-json\/wp\/v2\/posts\/98\/revisions"}],"predecessor-version":[{"id":109,"href":"https:\/\/learn-java-by-example.com\/wp-json\/wp\/v2\/posts\/98\/revisions\/109"}],"wp:attachment":[{"href":"https:\/\/learn-java-by-example.com\/wp-json\/wp\/v2\/media?parent=98"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/learn-java-by-example.com\/wp-json\/wp\/v2\/categories?post=98"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/learn-java-by-example.com\/wp-json\/wp\/v2\/tags?post=98"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}