Working with JFC/Swing Controls using NetBeans IDE - How about the JButton and its events?
(Page 4 of 6 )
In the previous section, I didn't really specify anything about "btnSum." I shall give you a detailed explanation in this section. Let us go through the code generated automatically by IDE for the button:
btnSum.setText("Sum");
btnSum.addActionListener(new
java.awt.event.ActionListener() {
public void actionPerformed(
java.awt.event.ActionEvent evt) {
btnSumActionPerformed(evt);
}
});
getContentPane().add(btnSum);
btnSum.setBounds(180, 80, 80, 23);
Now you can see that working with "btnSum" is a bit different from working with the others (because it has something to do when the user clicks). In general, every control/component may expose several events. Our application needs to "listen" to those events when necessary.
For example, "JButton" exposes the "actionPerformed" event, helping you to execute your own code when the button is clicked. To work with that event, we need to "listen" (or add a listener based on "actionPerformed") to that event. The following code fragment adds a listener with respect to "btnSum."
btnSum.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(
java.awt.event.ActionEvent evt) {
btnSumActionPerformed(evt);
}
});
In short, it executes the method "btnSumActionPerformed" when the button is hit. Let us see how "btnSumActionPerformed" is framed:
private void btnSumActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
int a = Integer.parseInt(this.txtFirst.getText());
int b = Integer.parseInt(this.txtSecond.getText());
this.lblResult.setText(String.valueOf(a+b));
}
The method gets executed whenever the "btnSum" is clicked. The first statement within the method gets the text available in "txtFirst," converts it to an integer and finally assigns to it the variable "a." The second statement within the method gets the text available in "txtSecond," converts it to an integer and finally assigns to it the variable "b." Finally, in the third statement, I am adding the two values (present in "a" and "b"), converting to string and finally placing it into "lblResult."
Next: Introducing error handling or exception handling in Java using NetBeans IDE >>
More Java Articles
More By Jagadish Chaterjee