Java-Swing buttons - adding as array in loop problem

Status
Not open for further replies.

ilugd

Beware of the innocent
SOLVED
I am having trouble with the following code.
Code:
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package calcapp;

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
import javax.swing.border.*;
import java.lang.String;

/**
 *
 * @author jsemmanuel
 */
public class calculator extends JFrame {

    calculator() {
        super("This is a frame");
        setSize(200, 200);
        JPanel valuePanel = new JPanel();
        JPanel buttonPanel = new JPanel();
        JLabel valueLabel = new JLabel("0");
        //valueLabel.setSize(40, 1800); ; //this one doesn't seems to work
        valueLabel.setBorder(new EtchedBorder());
        valuePanel.add(valueLabel);
        String buttonText[] = {"+", "-", "*", "/", "7", "8", "9", "4", "5", "6", "1", "2", "3", "0", ".", "="};
        JButton[] b=new JButton[16];
        for (int i = 0; i < 16; i++) {
           b[i].setText(buttonText[i]);
            buttonPanel.add(b[i]);
        }
        Container container;
        container = getContentPane();
        container.setLayout(new GridLayout(2, 1));
        add("North", valuePanel);
        add("South", buttonPanel);
        addWindowListener(new WindowHandler());

        show();
    }
}

class WindowHandler extends WindowAdapter implements ActionListener {

    @Override
    public void windowClosing(WindowEvent e) {
        System.exit(0);

    }

    public void actionPerformed(ActionEvent arg0) {
        throw new UnsupportedOperationException("Not supported yet.");
    }
}

I get this error from the compiler
Code:
compile:
run:
Exception in thread "main" java.lang.NullPointerException
        at calcapp.calculator.<init>(calculator.java:32)
        at calcapp.Main.main(Main.java:13)
Java Result: 1
BUILD SUCCESSFUL (total time: 1 second)
The part of the code that is the problem is this.
Code:
        JButton[] b=new JButton[16];
        for (int i = 0; i < 16; i++) {
           b[i].setText(buttonText[i]);
            buttonPanel.add(b[i]);
        }
what i am trying is to create an array of 16 buttons and then go into a loop and assign strings as button labels to each of the individual buttons. I am just learning Java, so not sure what is wrong here. can someone please help?
 
Last edited:

RCuber

The Mighty Unkel!!!
Staff member
Interesting coincidence.. I had the exact same task almost a year back .. but it was in vb.net .. here is the code vb.net

Code:
[B]Dim arrButtons(0) As Button[/B] 'Prepare array to receive buttons. Give this the necesary scope 

Private Sub MyBase_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load 
       [B] Dim btnTemp As Button [/B]
        Dim iCount As Integer 
        For iCount = 1 To 5 
            ReDim Preserve arrButtons(iCount) 'Expand array to receive next buton 
           [B] btnTemp = New Button[/B] 'Create instance of new button 
           [B] btnTemp.Name = "txtBox" & iCount.ToString[/B] 'Name button with sequential numbering 
            [B]btnTemp.Width = 100 
            btnTemp.Text = "button" & iCount 
            btnTemp.Location = New Point(20, iCount * 25) 
            Me.Controls.Add(btnTemp)[/B] 'Add new button to form 
            [B]arrButtons(iCount) = btnTemp [/B]'Place reference to new button in appropriate element of array 

            'The next line adds the handle of the new button to the appropriate event 

            AddHandler btnTemp.Click, AddressOf ButtonClickEvent 
        Next 
End Sub 

Private Sub ButtonClickEvent(ByVal sender As System.Object, ByVal e As System.EventArgs) 
    MessageBox.Show(CType(sender, Button).Name & " was clicked") 
End Sub

Now in this case I had to create a temperory button object and then assign the properties to this object.. after this just add to the array created. Also add this temp variable to the form/frame.

@ilugd: try the same approach by creating a tempbutton and then adding it to the array/frame. it may work.. BTW im not a java programmer, but doesnt java require a entery point (main()) I guess its in another file in the project :).

offtopic: What!!! how did your photo grow a mustache and beard in less than 5 mins? :D
Check attachment :D
 
Last edited:

chandru.in

In the zone
^^ Seems like .Net is too damn same as Java. :p

@ilugd

When you initialize an array using JButton[] b=new JButton[16], you are just saying that it is an array of 16 JButton instances. You are not actually creating the 16 JButton objects. Hence all elements of array take their default value of null.

To avoid it you must separately initialize each element of the array with a new JButton();

The simple rule to remember in Java is all array elements take their default value upon initialization. The default value for object references if null. Hence you get the most dreaded exception in any Java programmer's life. :D
 
OP
ilugd

ilugd

Beware of the innocent
SOLVED: Java-Swing buttons - adding as array in loop problem

Thanks a lot charan. You code made me think.
The line
JButton[] b=new JButton[16];
was creating a new JButton array but not the objects at each position of the array. I guess I didn't understand it properly.
In side the loop i just created a new button and assigned it to each array position. The program compiles and works now. Thanks a lot buddy.
Code:
        for (int i = 0; i < 16; i++) {
            b[i]=new JButton(buttonText[i]);
            buttonPanel.add(b[i]);
        }

By the way I am just wondering. Not sure about the syntax of VB.Net, but wouldn't this have been cleaner?
Code:
Private Sub MyBase_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Dim arrButtons(5) As Button
Dim iCount As Integer
For iCount = 1 To 5
set arrButtons(iCount)= New Button 'Create instance of new button 
arrButtons(iCount).Name = "txtBox" & iCount.ToString 'Name button with sequential numbering
arrButtons(iCount).Width = 100
arrButtons(iCount).Text = "button" & iCount
arrButtons(iCount).Location = New Point(20, iCount * 25)
Me.Controls.Add(arrButtons(iCount)) 'Add new button to form
AddHandler arrButtons(iCount).Click, AddressOf ButtonClickEvent

offtopic: Oh, I have been like this since january. just didn't update my avatar. A guy at irc mentioned and I changed it now. :)

ah, chandru.in, I gained insight just as you were posting. Thanks a lot for confirming my idea.

SOLVED
 
Last edited:

mehulved

18 Till I Die............
Re: SOLVED: Java-Swing buttons - adding as array in loop problem

offtopic: Oh, I have been like this since january. just didn't update my avatar. A guy at irc mentioned and I changed it now. :)
And would that be your best friend there?
 
Status
Not open for further replies.
Top Bottom