{"id":241,"date":"2017-12-05T06:27:00","date_gmt":"2017-12-05T06:27:00","guid":{"rendered":"https:\/\/kindsonthegenius.com\/blog\/2017\/12\/05\/part-2-how-to-build-a-simple-calculator-in-java-using-netbeans-step-by-step-with-screenshots\/"},"modified":"2026-07-05T02:11:42","modified_gmt":"2026-07-05T00:11:42","slug":"part-2-how-to-build-a-simple-calculator-in-java-using-netbeans-step-by-step-with-screenshots","status":"publish","type":"post","link":"https:\/\/kindsonthegenius.com\/blog\/part-2-how-to-build-a-simple-calculator-in-java-using-netbeans-step-by-step-with-screenshots\/","title":{"rendered":"Part 2: Java Calculator in NetBeans \u2014 Multi-digit, Layout &#038; Error Handling (2026)"},"content":{"rendered":"<p><!-- ktg-updated-banner --><\/p>\n<div class=\"ktg-updated-banner\" style=\"margin:1em 0;padding:0.75em 1em;background:#eff6ff;border-left:4px solid #3b82f6;border-radius:4px;\">\n<p><strong>Updated July 5, 2026:<\/strong> Restructured with table of contents, +\/- button code, division fix, and error handling. Completes the two-part Java calculator series \u2014 <a href=\"https:\/\/kindsonthegenius.com\/blog\/how-to-build-a-simple-calculator-in-java-using-netbeans-step-by-step-with-screenshots\/\">start with Part 1<\/a> if you have not built the base project yet.<\/p>\n<\/div>\n<p>This is <strong>Part 2<\/strong> of the <strong>Java calculator NetBeans tutorial<\/strong>. You will improve the calculator from <a href=\"https:\/\/kindsonthegenius.com\/blog\/how-to-build-a-simple-calculator-in-java-using-netbeans-step-by-step-with-screenshots\/\">Part 1<\/a> by fixing button layout, supporting <strong>multi-digit numbers<\/strong>, adding the <strong>+\/- toggle<\/strong>, and handling common input errors.<\/p>\n<p><strong>Prerequisites:<\/strong> Complete <a href=\"https:\/\/kindsonthegenius.com\/blog\/how-to-build-a-simple-calculator-in-java-using-netbeans-step-by-step-with-screenshots\/\">Part 1 \u2014 Build a Simple Calculator in Java Using NetBeans<\/a> with a working <code>CalculatorProgram<\/code> project and <code>pnlCalculator<\/code> form. <strong>Estimated time:<\/strong> 45\u201360 minutes.<\/p>\n<p><!-- ktg-article-toc --><\/p>\n<nav class=\"ktg-article-toc\" aria-label=\"Java calculator Part 2 table of contents\" style=\"margin:1.5em 0;padding:1em 1.25em;background:#f8fafc;border:1px solid #e2e8f0;border-radius:8px;\">\n<h2>Table of Contents<\/h2>\n<ol>\n<li><a href=\"#questions-from-part-1\">Questions answered in Part 2<\/a><\/li>\n<li><a href=\"#button-layout\">Arrange buttons with Absolute Layout<\/a><\/li>\n<li><a href=\"#multi-digit\">Handle multi-digit numbers (0\u20139)<\/a><\/li>\n<li><a href=\"#operator-buttons\">Update operator button code<\/a><\/li>\n<li><a href=\"#plus-minus-toggle\">+\/- (plus-minus) button<\/a><\/li>\n<li><a href=\"#equals-button\">Update the equals button<\/a><\/li>\n<li><a href=\"#error-handling\">Basic error handling<\/a><\/li>\n<li><a href=\"#test\">Test your improved calculator<\/a><\/li>\n<li><a href=\"#faq\">Frequently asked questions<\/a><\/li>\n<\/ol>\n<\/nav>\n<figure style=\"margin:1.5em 0;text-align:center;\"><img decoding=\"async\" src=\"https:\/\/3.bp.blogspot.com\/-avPVpJC7VGg\/WiY78s2KuDI\/AAAAAAAAAWQ\/-zDxBS5qpVAHTW-AS5L4ceeyvK89b2P1wCLcBGAs\/s320\/How-To-Build-a-Simple-Calculator-In-Java-Using-Netbeans-Part-2.jpg\" alt=\"Part 2 Java calculator tutorial in NetBeans \u2014 multi-digit and layout improvements\" width=\"640\" height=\"480\" loading=\"lazy\" style=\"max-width:100%;height:auto;border-radius:8px;border:1px solid #dee2e6;\" \/><\/figure>\n<h2 id=\"questions-from-part-1\">Questions Answered in Part 2<\/h2>\n<p>Readers of Part 1 asked:<\/p>\n<ul>\n<li>How do I arrange the buttons neatly on the form?<\/li>\n<li>How do I handle numbers greater than 9 (multi-digit input)?<\/li>\n<li>What is the code for the <strong>+\/-<\/strong> button?<\/li>\n<li>How do I handle wrong or invalid input?<\/li>\n<\/ul>\n<p>This tutorial addresses all four. (An earlier draft mentioned a Part 3; those topics are covered here instead.)<\/p>\n<h2 id=\"button-layout\">Step 1\u20133: Arrange Buttons with Absolute Layout<\/h2>\n<h3>Step 1: Switch to Absolute Layout<\/h3>\n<p>Right-click inside the panel that holds the buttons \u2192 <strong>Set Layout \u2192 Absolute Layout<\/strong>. Buttons will no longer snap to a grid, so you can position them precisely.<\/p>\n<figure style=\"margin:1.5em 0;text-align:center;\"><img decoding=\"async\" src=\"https:\/\/3.bp.blogspot.com\/-32Ns5glLE6o\/WiYSSnlK5rI\/AAAAAAAAAVs\/J9CzTDUB_uIpvRnjrlyXy_HyEAZz1oEZwCLcBGAs\/s320\/Setting%2BLayout.jpg\" alt=\"Setting Absolute Layout on the calculator button panel in NetBeans\" width=\"640\" height=\"480\" loading=\"lazy\" style=\"max-width:100%;height:auto;border-radius:8px;border:1px solid #dee2e6;\" \/><\/figure>\n<h3>Step 2: Resize and align buttons<\/h3>\n<p>Drag each button into a clean grid. Aim for even spacing between rows and columns.<\/p>\n<h3>Step 3 (optional): Uniform dimensions via Properties<\/h3>\n<p>Select a button and open the <strong>Properties<\/strong> window \u2192 <strong>Layout<\/strong> section:<\/p>\n<ul>\n<li>Give every button the same <strong>width<\/strong> and <strong>height<\/strong> (except = if you want it taller)<\/li>\n<li>Buttons in the same <strong>row<\/strong> share the same <strong>Y<\/strong> coordinate<\/li>\n<li>Buttons in the same <strong>column<\/strong> share the same <strong>X<\/strong> coordinate<\/li>\n<\/ul>\n<figure style=\"margin:1.5em 0;text-align:center;\"><img decoding=\"async\" src=\"https:\/\/2.bp.blogspot.com\/-rdp6q04SHgc\/WiYTsDu1mnI\/AAAAAAAAAV8\/vLqJP5SQibAaagMmYNF2Rik1uswtPpSHgCLcBGAs\/s320\/Button%2BLayout.JPG\" alt=\"Uniform calculator button layout with aligned rows and columns in NetBeans\" width=\"640\" height=\"480\" loading=\"lazy\" style=\"max-width:100%;height:auto;border-radius:8px;border:1px solid #dee2e6;\" \/><\/figure>\n<h2 id=\"multi-digit\">Step 4\u20135: Handle Multi-digit Numbers<\/h2>\n<p>Replace the Part 1 click handlers for digits <strong>0\u20139<\/strong> with the pattern below. It appends digits before an operator is chosen, and builds <code>value2<\/code> digit-by-digit after an operator appears in the display.<\/p>\n<h3>Example: Button 1 (<code>btn1<\/code>)<\/h3>\n<pre><code class=\"language-java\">String res = txtResult.getText();\nif (res.isEmpty()) {\n    txtResult.setText(\"1\");\n} else if (res.contains(\"+\") || res.contains(\"-\") || res.contains(\"*\") || res.contains(\"\/\")) {\n    txtResult.setText(res + \"1\");\n    value2 = Integer.parseInt(value2 + \"1\");\n} else {\n    txtResult.setText(res + \"1\");\n}\n<\/code><\/pre>\n<h3>Repeat for buttons 2\u20139 and 0<\/h3>\n<p>Copy the pattern, changing <code>\"1\"<\/code> and <code>value2 + \"1\"<\/code> to the matching digit. For example, button 7:<\/p>\n<pre><code class=\"language-java\">String res = txtResult.getText();\nif (res.isEmpty()) {\n    txtResult.setText(\"7\");\n} else if (res.contains(\"+\") || res.contains(\"-\") || res.contains(\"*\") || res.contains(\"\/\")) {\n    txtResult.setText(res + \"7\");\n    value2 = Integer.parseInt(value2 + \"7\");\n} else {\n    txtResult.setText(res + \"7\");\n}\n<\/code><\/pre>\n<p><strong>How it works:<\/strong> Before an operator, digits concatenate in the display (e.g. <code>1<\/code> then <code>2<\/code> \u2192 <code>12<\/code>). After an operator, <code>value2<\/code> is built by string concatenation on the integer (<code>value2 + \"7\"<\/code> converts to string, then <code>parseInt<\/code>).<\/p>\n<h2 id=\"operator-buttons\">Step 6: Update Operator Buttons (+, \u2212, \u00d7, \u00f7)<\/h2>\n<p>Replace the Part 1 operator handlers so <code>value1<\/code> is parsed from the full display text (multi-digit) before the operator symbol is appended.<\/p>\n<p><strong>Important:<\/strong> Use <code>btnDivision<\/code> (the name from Part 1), not <code>btnDivide<\/code>.<\/p>\n<pre><code class=\"language-java\">\/\/ btnPlus\nif (txtResult.getText().isEmpty()) return;\nvalue1 = Integer.parseInt(txtResult.getText().trim());\ntxtResult.setText(txtResult.getText() + \" \" + btnPlus.getText());\noperator = \"plus\";\n\n\/\/ btnMinus\nif (txtResult.getText().isEmpty()) return;\nvalue1 = Integer.parseInt(txtResult.getText().trim());\ntxtResult.setText(txtResult.getText() + \" \" + btnMinus.getText());\noperator = \"minus\";\n\n\/\/ btnDivision\nif (txtResult.getText().isEmpty()) return;\nvalue1 = Integer.parseInt(txtResult.getText().trim());\ntxtResult.setText(txtResult.getText() + \" \" + btnDivision.getText());\noperator = \"division\";\n\n\/\/ btnMultiplication\nif (txtResult.getText().isEmpty()) return;\nvalue1 = Integer.parseInt(txtResult.getText().trim());\ntxtResult.setText(txtResult.getText() + \" \" + btnMultiplication.getText());\noperator = \"multiplication\";\n<\/code><\/pre>\n<p><strong>Division fix:<\/strong> If division returned wrong results in Part 1, confirm the button variable is <code>btnDivision<\/code> and that <code>operator<\/code> is set to <code>\"division\"<\/code> (compared with <code>.equals()<\/code> in the equals handler).<\/p>\n<h2 id=\"plus-minus-toggle\">Step 7: +\/- (Plus-Minus) Button<\/h2>\n<p>Add a <code>mouseClicked<\/code> handler for <code>btnPlusMinus<\/code> that toggles the sign of the number currently displayed:<\/p>\n<pre><code class=\"language-java\">String text = txtResult.getText().trim();\nif (text.isEmpty()) return;\ntry {\n    double num = Double.parseDouble(text);\n    num = -num;\n    txtResult.setText(String.valueOf((int) num));\n} catch (NumberFormatException ex) {\n    txtResult.setText(\"Invalid input\");\n}\n<\/code><\/pre>\n<p>This flips positive \u2194 negative on the current value (e.g. <code>42<\/code> \u2192 <code>-42<\/code>). For decimal support, remove the <code>(int)<\/code> cast and keep <code>Double.toString(num)<\/code>.<\/p>\n<h2 id=\"equals-button\">Step 8: Update the Equals Button<\/h2>\n<p>Replace the Part 1 equals handler with a version that handles division-by-zero and uses <code>.equals()<\/code> for string comparison:<\/p>\n<pre><code class=\"language-java\">double answer = 0;\nif (\"plus\".equals(operator))\n    answer = value1 + value2;\nelse if (\"minus\".equals(operator))\n    answer = value1 - value2;\nelse if (\"multiplication\".equals(operator))\n    answer = value1 * value2;\nelse if (\"division\".equals(operator)) {\n    if (value2 == 0) {\n        txtResult.setText(\"Cannot divide by zero\");\n        return;\n    }\n    answer = (double) value1 \/ value2;\n}\nelse {\n    txtResult.setText(\"No operator selected\");\n    return;\n}\ntxtResult.setText(Double.toString(answer));\n<\/code><\/pre>\n<h2 id=\"error-handling\">Step 9: Basic Error Handling<\/h2>\n<p>Add validation for common mistakes:<\/p>\n<table>\n<thead>\n<tr>\n<th>Error<\/th>\n<th>Handler<\/th>\n<\/tr>\n<\/thead>\n<tbody>\n<tr>\n<td>Divide by zero<\/td>\n<td>Show <code>Cannot divide by zero<\/code> (equals handler above)<\/td>\n<\/tr>\n<tr>\n<td>No operator before =<\/td>\n<td>Show <code>No operator selected<\/code><\/td>\n<\/tr>\n<tr>\n<td>Invalid number on +\/-<\/td>\n<td><code>catch NumberFormatException<\/code> \u2192 <code>Invalid input<\/code><\/td>\n<\/tr>\n<tr>\n<td>Wrong operator entered<\/td>\n<td>Wrap <code>parseInt<\/code> in try\/catch on operator buttons:<\/td>\n<\/tr>\n<\/tbody>\n<\/table>\n<pre><code class=\"language-java\">\/\/ Example on btnPlus \u2014 wrap parseInt\ntry {\n    if (txtResult.getText().isEmpty()) return;\n    value1 = Integer.parseInt(txtResult.getText().trim());\n    txtResult.setText(txtResult.getText() + \" \" + btnPlus.getText());\n    operator = \"plus\";\n} catch (NumberFormatException ex) {\n    txtResult.setText(\"You have entered a wrong operator.\");\n}\n<\/code><\/pre>\n<h2 id=\"test\">Step 10: Test Your Improved Calculator<\/h2>\n<p>Run the form and verify:<\/p>\n<ol>\n<li><strong>Multi-digit:<\/strong> <code>12 + 34 =<\/code> \u2192 <code>46.0<\/code><\/li>\n<li><strong>+\/- toggle:<\/strong> Enter <code>5<\/code>, click +\/- \u2192 <code>-5<\/code><\/li>\n<li><strong>Division:<\/strong> <code>20 \/ 4 =<\/code> \u2192 <code>5.0<\/code><\/li>\n<li><strong>Divide by zero:<\/strong> <code>8 \/ 0 =<\/code> \u2192 error message<\/li>\n<li><strong>Clear:<\/strong> CE resets the display<\/li>\n<\/ol>\n<h2 id=\"faq\">Frequently Asked Questions<\/h2>\n<p><strong>What is the code for the +\/- button?<\/strong><br \/>\nSee <a href=\"#plus-minus-toggle\">Step 7<\/a> above. It parses the display value, multiplies by \u22121, and writes it back to <code>txtResult<\/code>.<\/p>\n<p><strong>Why is division not working properly?<\/strong><br \/>\nCheck three things: (1) button variable is <code>btnDivision<\/code>, not <code>btnDivide<\/code>; (2) <code>operator<\/code> is <code>\"division\"<\/code>; (3) equals handler uses <code>\"division\".equals(operator)<\/code> and casts to <code>double<\/code> for non-integer results.<\/p>\n<p><strong>Is there a Part 3?<\/strong><br \/>\nDecimal points and advanced validation were originally planned as Part 3. This updated Part 2 covers multi-digit input, +\/-, and basic errors. For decimal support, change operand types from <code>int<\/code> to <code>double<\/code> and use <code>Double.parseDouble()<\/code> throughout.<\/p>\n<p><strong>When was Part 2 published?<\/strong><br \/>\nThe original Part 2 dates to 2017. This July 2026 revision adds missing +\/- code, fixes the division button name, and documents error handling readers requested in comments.<\/p>\n<h2 id=\"series-links\">Calculator Tutorial Series<\/h2>\n<ul>\n<li><a href=\"https:\/\/kindsonthegenius.com\/blog\/how-to-build-a-simple-calculator-in-java-using-netbeans-step-by-step-with-screenshots\/\"><strong>Part 1<\/strong> \u2014 GUI design, buttons, and basic arithmetic<\/a><\/li>\n<li><strong>Part 2<\/strong> (this page) \u2014 layout, multi-digit, +\/-, errors<\/li>\n<li><a href=\"https:\/\/kindsonthegenius.com\/blog\/java-for-beginners-lesson-3-structure-of-a-java-program\/\">Lesson 3 \u2014 Structure of a Java Program<\/a><\/li>\n<li><a href=\"https:\/\/kindsonthegenius.com\/blog\/15-easy-free-java-tutorials-with-step-by-step-examples-and-quiz\/\">15 Easy Free Java Tutorials<\/a><\/li>\n<\/ul>\n<p><!-- ktg-series-nav --><\/p>\n<nav class=\"ktg-series-nav\" aria-label=\"Java calculator tutorial series\">\n<p><strong>Previous:<\/strong> <a href=\"https:\/\/kindsonthegenius.com\/blog\/how-to-build-a-simple-calculator-in-java-using-netbeans-step-by-step-with-screenshots\/\">Part 1 \u2014 Build a Simple Calculator in Java Using NetBeans<\/a><\/p>\n<\/nav>\n<p><!-- ktg-alkademy-cta --><\/p>\n<div class=\"ktg-alkademy-cta\" style=\"margin:2em 0;padding:1.25em;border-left:4px solid #2563eb;background:#f8fafc;\">\n<p><strong>Ready for structured Java training?<\/strong> Join <a href=\"https:\/\/www.alkademy.com\/courses\" target=\"_blank\" rel=\"noopener noreferrer\">Alkademy<\/a> for instructor-led Java courses with hands-on GUI and OOP projects.<\/p>\n<\/div>\n<p><!-- ktg-faq-schema --><br \/>\n<script type=\"application\/ld+json\">{\"@context\":\"https:\/\/schema.org\",\"@type\":\"FAQPage\",\"mainEntity\":[{\"@type\":\"Question\",\"name\":\"What is the code for the +\/- button on the Java NetBeans calculator?\",\"acceptedAnswer\":{\"@type\":\"Answer\",\"text\":\"Parse the display with Double.parseDouble, multiply by -1, and set txtResult. See Part 2 Step 7 of the Kindson The Genius Java calculator tutorial.\"}},{\"@type\":\"Question\",\"name\":\"Why is division not working in my Java NetBeans calculator?\",\"acceptedAnswer\":{\"@type\":\"Answer\",\"text\":\"Use btnDivision not btnDivide, set operator to division, and compare with equals() in the equals handler. Cast to double for correct division results.\"}},{\"@type\":\"Question\",\"name\":\"Is there a Part 3 of the Java calculator tutorial?\",\"acceptedAnswer\":{\"@type\":\"Answer\",\"text\":\"Decimal and advanced validation were planned as Part 3. The July 2026 Part 2 update covers multi-digit input, +\/- toggle, and basic error handling instead.\"}},{\"@type\":\"Question\",\"name\":\"How do I handle multi-digit numbers in the Java calculator?\",\"acceptedAnswer\":{\"@type\":\"Answer\",\"text\":\"Replace digit button handlers to append digits to the display and build value2 with Integer.parseInt(value2 + digit) after an operator appears in the display text.\"}}]}<\/script><\/p>\n<p><!-- ktg-howto-schema --><br \/>\n<script type=\"application\/ld+json\">{\"@context\":\"https:\/\/schema.org\",\"@type\":\"HowTo\",\"name\":\"Java Calculator in NetBeans \u2014 Part 2: Multi-digit and Error Handling\",\"description\":\"Improve a Java Swing calculator in NetBeans with absolute layout, multi-digit input, +\/- toggle, and input validation.\",\"totalTime\":\"PT60M\",\"step\":[{\"@type\":\"HowToStep\",\"name\":\"Set Absolute Layout\",\"text\":\"Right-click the button panel and choose Set Layout, Absolute Layout.\"},{\"@type\":\"HowToStep\",\"name\":\"Align buttons\",\"text\":\"Resize and position buttons with uniform width, height, X, and Y coordinates.\"},{\"@type\":\"HowToStep\",\"name\":\"Update digit handlers\",\"text\":\"Replace 0-9 button code to support multi-digit display and value2 building.\"},{\"@type\":\"HowToStep\",\"name\":\"Update operator handlers\",\"text\":\"Parse value1 from full display text before appending operator symbols.\"},{\"@type\":\"HowToStep\",\"name\":\"Add +\/- toggle\",\"text\":\"Implement btnPlusMinus to flip the sign of the displayed number.\"},{\"@type\":\"HowToStep\",\"name\":\"Add error handling\",\"text\":\"Handle divide by zero, missing operator, and NumberFormatException.\"}]}<\/script><\/p>\n","protected":false},"excerpt":{"rendered":"<p>Updated July 5, 2026: Restructured with table of contents, +\/- button code, division fix, and error handling. Completes the two-part Java calculator series \u2014 start &hellip; <\/p>\n","protected":false},"author":2,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"pagelayer_contact_templates":[],"_pagelayer_content":"","footnotes":""},"categories":[85],"tags":[],"class_list":["post-241","post","type-post","status-publish","format-standard","hentry","category-java"],"_links":{"self":[{"href":"https:\/\/kindsonthegenius.com\/blog\/wp-json\/wp\/v2\/posts\/241","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/kindsonthegenius.com\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/kindsonthegenius.com\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/kindsonthegenius.com\/blog\/wp-json\/wp\/v2\/users\/2"}],"replies":[{"embeddable":true,"href":"https:\/\/kindsonthegenius.com\/blog\/wp-json\/wp\/v2\/comments?post=241"}],"version-history":[{"count":2,"href":"https:\/\/kindsonthegenius.com\/blog\/wp-json\/wp\/v2\/posts\/241\/revisions"}],"predecessor-version":[{"id":1869,"href":"https:\/\/kindsonthegenius.com\/blog\/wp-json\/wp\/v2\/posts\/241\/revisions\/1869"}],"wp:attachment":[{"href":"https:\/\/kindsonthegenius.com\/blog\/wp-json\/wp\/v2\/media?parent=241"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/kindsonthegenius.com\/blog\/wp-json\/wp\/v2\/categories?post=241"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/kindsonthegenius.com\/blog\/wp-json\/wp\/v2\/tags?post=241"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}