Working with JFC/Swing Controls using NetBeans IDE
This article focuses on programming with the text boxes, buttons and labels of JFC in Java using the NetBeans IDE. It also introduces you to exception handling in Java.
Working with JFC/Swing Controls using NetBeans IDE - Introducing error handling or exception handling in Java using NetBeans IDE (Page 5 of 6 )
The above example that I presented works well if you provide the values correctly. The application may crash if you try to provide some incorrect values (or even no values). To handle such situations, we can use the exception handling built within Java.
In this section, I shall only introduce exception handling (with respect to the previous example). In my upcoming articles, we shall go in an in-depth discussion of exceptions. Now let us go through the modified code as follows:
private void btnSumActionPerformed(java.awt.event.ActionEvent evt) { // TODO add your handling code here: int a=0,b=0;
//check for the validity of first number try { a = Integer.parseInt(this.txtFirst.getText()); } catch(Exception e) { this.txtFirst.setBackground(java.awt.Color.RED); this.txtFirst.requestFocus(); return; }
//check for the validity of second number try { b = Integer.parseInt(this.txtSecond.getText()); } catch(Exception e) { this.txtSecond.setBackground(java.awt.Color.RED); this.txtSecond.requestFocus(); return; }
//set back the colors and give the result this.txtFirst.setBackground(java.awt.Color.WHITE); this.txtSecond.setBackground(java.awt.Color.WHITE); this.lblResult.setText(String.valueOf(a+b)); }
The next section will explain the above code in detail.