Forum     

Go Back   Digit Technology Discussion Forum > Software > Programming
Register FAQ Calendar Mark Forums Read

Programming The destination for developers - C, C++, Java, Python and the lot


Closed Thread
 
LinkBack Thread Tools Display Modes
Old 13-07-2008, 11:11 PM   #1 (permalink)
Beware of the innocent
 
ilugd's Avatar
 
Join Date: Dec 2005
Posts: 1,024
Default Java-Swing buttons - adding as array in loop problem


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?
__________________
Life is too short. Have fun.

Last edited by ilugd; 14-07-2008 at 12:24 AM.
ilugd is offline  
Advertisements. Register and be a member of the community to get rid of them.
Advertisement

Old 14-07-2008, 12:08 AM   #2 (permalink)
Rubik's Uncle!!
 
Charan's Avatar
 
Join Date: Sep 2004
Location: ಬೆಂಗಳೂರು (Bengaluru)
Posts: 3,785
Default Re: Java-Swing buttons - adding as array in loop problem

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:
Dim arrButtons(0) As Button '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 
        Dim btnTemp As Button 
        Dim iCount As Integer 
        For iCount = 1 To 5 
            ReDim Preserve arrButtons(iCount) 'Expand array to receive next buton 
            btnTemp = New Button 'Create instance of new button 
            btnTemp.Name = "txtBox" & iCount.ToString 'Name button with sequential numbering 
            btnTemp.Width = 100 
            btnTemp.Text = "button" & iCount 
            btnTemp.Location = New Point(20, iCount * 25) 
            Me.Controls.Add(btnTemp) 'Add new button to form 
            arrButtons(iCount) = btnTemp '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?
Check attachment
Attached Images
File Type: jpg beforepost.JPG (37.1 KB, 8 views)
File Type: jpg afterpost.JPG (28.2 KB, 5 views)
__________________
i5 2400 | DH67BL | G.Skill Ripjaw 4 GB | FSP SAGA II 500W | CM 430 Black Elite | MSI R6850 Cyclone PE/OC | XBox 360 Controller | 21.5" Samsung Sync Master 2233 | 4 Mbps @75GB FUP :)
Battlefield 3 Multiplayer Discussion | Battlefield 3 Low Latency Servers List

Last edited by Charan; 14-07-2008 at 12:24 AM. Reason: fixed code.
Charan is offline  
Old 14-07-2008, 12:15 AM   #3 (permalink)
CAFEBABE
 
chandru.in's Avatar
 
Join Date: Mar 2008
Location: Bangalore
Posts: 474
Default Re: Java-Swing buttons - adding as array in loop problem

^^ Seems like .Net is too damn same as Java.

@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.
__________________
Chandru

http://tuxychandru.blogspot.com
chandru.in is offline  
Old 14-07-2008, 12:20 AM   #4 (permalink)
Beware of the innocent
 
ilugd's Avatar
 
Join Date: Dec 2005
Posts: 1,024
Default 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
__________________
Life is too short. Have fun.

Last edited by ilugd; 14-07-2008 at 12:23 AM. Reason: Automerged Doublepost
ilugd is offline  
Old 14-07-2008, 12:25 AM   #5 (permalink)
Rubik's Uncle!!
 
Charan's Avatar
 
Join Date: Sep 2004
Location: ಬೆಂಗಳೂರು (Bengaluru)
Posts: 3,785
Default Re: Java-Swing buttons - adding as array in loop problem

^^ I didnt use [ /code ] , now i fixed it.
__________________
i5 2400 | DH67BL | G.Skill Ripjaw 4 GB | FSP SAGA II 500W | CM 430 Black Elite | MSI R6850 Cyclone PE/OC | XBox 360 Controller | 21.5" Samsung Sync Master 2233 | 4 Mbps @75GB FUP :)
Battlefield 3 Multiplayer Discussion | Battlefield 3 Low Latency Servers List
Charan is offline  
Old 14-07-2008, 01:19 AM   #6 (permalink)
18 Till I Die............
 
Join Date: Jul 2004
Location: India, Mumbai, Marine Lines
Posts: 5,792
Default Re: SOLVED: Java-Swing buttons - adding as array in loop problem

Quote:
Originally Posted by ilugd View Post
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?
__________________
http://www.bash.org/?258908
mehulved is offline  
Old 14-07-2008, 10:06 AM   #7 (permalink)
Beware of the innocent
 
ilugd's Avatar
 
Join Date: Dec 2005
Posts: 1,024
Default Re: Java-Swing buttons - adding as array in loop problem

and who would that be?
__________________
Life is too short. Have fun.
ilugd is offline  
Closed Thread

Bookmarks

Thread Tools
Display Modes

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are On


Similar Threads
Thread Thread Starter Forum Replies Last Post
The Loop Kingdom abhi.eternal Chit-Chat 1 22-12-2007 07:13 PM
java code at start up and adding playlist.. Pragadheesh QnA (read only) 2 16-09-2007 09:48 AM
array of JPanel in java.... tweety_bird_bunny QnA (read only) 3 27-09-2006 08:52 PM
Learn :: USING JDBC(with ACCESS), AWT, & SWING in JAVA(JDK 1.5) imdbest Tutorials 1 11-07-2006 11:47 AM
HowTo convert C struct with array of another struct in java kb QnA (read only) 1 08-04-2005 12:59 PM

 
Latest Threads
- by Sujeet
- by clmlbx
- by Sujeet
- by icebags

Advertisement




All times are GMT +5.5. The time now is 11:06 AM.


Powered by vBulletin® Version 3.8.7
Copyright ©2000 - 2012, vBulletin Solutions, Inc.

Search Engine Optimization by vBSEO 3.3.2