Working with JFC/Swing Controls using NetBeans IDE - Working with text boxes, buttons, labels: understanding the code
(Page 2 of 6 )
Let us go through the code created behind the controls. I shall explain step by step. Let us first consider the following:
private javax.swing.JButton btnSum;
private javax.swing.JLabel lblEnterFirst;
private javax.swing.JLabel lblEnterSecond;
private javax.swing.JLabel lblResult;
private javax.swing.JTextField txtFirst;
private javax.swing.JTextField txtSecond;
Every control we dropped from the toolbox onto the form (or JFrame) would be coded as above. In fact, every control we placed on the form would be treated as an object of the respective class. In the above case, they are simply references to non existing objects. The next code fragment would create the real objects and assign those objects to above references. The name of the object/reference (in this case) would be the same, as we rename it during the design.
Further proceeding we have the following:
private void initComponents() {
The line above contains the name (initComponents) of the method which is executed from within the constructor (please refer to the code fragment in the previous section). The constructor is a special type of method, which has the same name as the class name and is executed automatically by itself (when the instance of that class has been created).
Further proceeding we have the following:
txtFirst = new javax.swing.JTextField();
btnSum = new javax.swing.JButton();
lblEnterFirst = new javax.swing.JLabel();
lblEnterSecond = new javax.swing.JLabel();
txtSecond = new javax.swing.JTextField();
lblResult = new javax.swing.JLabel();
All the above statements simply create objects of the controls we placed on the form. Those objects will be assigned to the references previously created.
getContentPane().setLayout(null);
The above statement assigns "no layout" to our frame (or to the content pane). Every JFrame would be generally equipped with a special panel called "contentPane." We will generally add controls to this "contentpane". Which means, we need to specify the top, left, width, and height of every control ourselves (and nothing would be automated).
Next: Working with text boxes, buttons, labels: understanding the code continued >>
More Java Articles
More By Jagadish Chaterjee