Problem in assigning randomed buttons
Hello There!!
I'm just a beginner so i would need your help with the Code:
JButton x []= new JButton [12];
int [] arr=new int[15];
public Bahay_Kubling() {
setLayout(new GridLayout(3,4));
int randomNumbers = 12;
Container con=getContentPane();
ArrayList<Integer> numbers = new ArrayList<Integer>();
int number = (int)(Math.random() * randomNumbers);
numbers.add(number);
for(int i = 0; i < randomNumbers-1; i++){
do{
number = (int)(Math.random() * 12);
}while(numbers.indexOf(number)!=-1);
numbers.add(number);
}
for(Integer i: numbers){
System.out.println(i);
con.add(x[i]);
x[i].addActionListener(this);
}
setTitle("Bahay Kubling Matching Game");
setSize(300,400);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null);
setVisible(true);
I think I'm done with randoming unique numbers but the problem is assigning it to the buttons. I'm having error during runtime supposedly.. These is the error:
Code:
11
Exception in thread "main" java.lang.NullPointerException
at java.awt.Container.addImpl(Container.java:1086)
at java.awt.Container.add(Container.java:410)
at Bahay_Kubling.<init>(Bahay_Kubling.java:35)
at Bahay_Kubling.main(Bahay_Kubling.java:54)
Thanks in advance.. Hope you can help me. :(happy):
Re: Problem in assigning randomed buttons
I did not see where you initialize JButtons.
Re: Problem in assigning randomed buttons
Quote:
11
Exception in thread "main" java.lang.NullPointerException
at java.awt.Container.addImpl(Container.java:1086)
at java.awt.Container.add(Container.java:410)
at Bahay_Kubling.<init>(Bahay_Kubling.java:35)
At line 35 you call the add method with a null value. Check that line in your code to see what the problem is.
Re: Problem in assigning randomed buttons
Quote:
Originally Posted by
mine0926
I did not see where you initialize JButtons.
Sorry for late reply..
It's here:
Code:
public class Bahay_Kubling extends JFrame implements ActionListener{
JButton x []= new JButton [12];
int [] arr=new int[15];
:(nod):
Re: Problem in assigning randomed buttons
Code:
JButton x []= new JButton [12];
That creates an array with 12 empty slots. It does not put any objects in the slots.
You need to assign them all with valid objects.
Re: Problem in assigning randomed buttons
Quote:
Originally Posted by
Norm
At line 35 you call the add method with a null value. Check that line in your code to see what the problem is.
Thanks for the reply..
Line 35 is :I don't know whats wrong.. please help.
Re: Problem in assigning randomed buttons
What is the value of x[i]? Is it null?
See post#5
Re: Problem in assigning randomed buttons
Quote:
Originally Posted by
Norm
What is the value of x[i]? Is it null?
See post#5
Ok. I got it.! Thanks Mod..
I just added Code:
x[i] = new JButton("1", new ImageIcon ("stan.jpg"));
before adding it to container..
Thanks a lot.
Re: Problem in assigning randomed buttons