Categories: MSDN / DotNet / Java / Scripts / Linux / PHP Ask - La ask - La Answer

How to create objects (JButton) array?

Hello. I'm creating a Calculator class. This is just the code where i wan't to creare an array of objects - JButtons:

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Calculator extends JFrame{
public static void main(String[]args){
JFrame window=new JFrame("Calculator");
JButton button[]=new JButton[10];
for(int i=0;i<button.length;i++){
button[i].setText(Integer.toString(i+1));
}
window.setSize(500,500);
window.setVisible(true);
}}

Application properly compiles. Error occures when i run it - NulPointerException somewhere in the for statement. :o
[662 byte] By [barbato] at [2007-11-11 8:25:45]
# 1 Re: How to create objects (JButton) array?
Don't you want your buttons to be 1 to 0. not 1 to 10?

I don't know that I can figure out the source of your NullPointerException. Put parentheses around your ((i+1)%button.length) calculation in the setText() method - it is acting as if you are moving the value of i outside of the range of the array.
nspils at 2007-11-11 22:35:32 >
# 2 Re: How to create objects (JButton) array?
found it:
JButton button[]=new JButton[10];
for(int i=0;i<button.length;i++){
button[i].setText(Integer.toString(i+1));
}

you call button[i].setText(.. without having actualy constructed that object.
with JButton button[]=new JButton[10]; you create the array, not the objects!
use:
JButton button[]=new JButton[10];
for(int i=0;i<button.length;i++){
button[i] = new JButton();
button[i].setText(Integer.toString(i+1));
}
graviton at 2007-11-11 22:36:26 >
# 3 Re: How to create objects (JButton) array?
Good catch, graviton.
nspils at 2007-11-11 22:37:30 >
# 4 Re: How to create objects (JButton) array?
thanx graviton!
barbato at 2007-11-11 22:39:36 >
# 5 Re: How to create objects (JButton) array?
Use this way

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class forum1 extends JFrame

{
public forum1()
{
JButton button[]=new JButton[10];
JPanel p1=new JPanel();
p1.setLayout(new GridLayout(4,2,5,5));
for(int i=0;i<button.length;i++){
button[i]= new JButton(Integer.toString(i+1));
p1.add(button[i]);
}
Container c=getContentPane();
c.add(p1);

setTitle("Testing button");
setSize(500,500);
setVisible(true);

}


public static void main(String[]args){
new forum1();

}
}
vanduc at 2007-11-11 22:40:29 >