Skip to main content

Random Color

2 replies [Last post]
Chillout88
Offline
Joined: 2011-09-24
Points: 0

Hi i am a bit new to Java so pls forgive me for bad questions.

I wanna have about 16 panels and i wanna give them random colours. i've got an error messeage when i try to set the colour to a panel.

Exception in thread "main" java.lang.NullPointerException
at probák.GF.<init>(GF.java:36)
at probák.GF.main(GF.java:46)
Java Result: 1

the code looks like this:

package probák;
import javax.swing.*;
import java.awt.*;
import java.util.Random;

public class GF extends JFrame {

JPanel panel = new JPanel();
JPanel[] panelek = new JPanel[16];
JButton[] gombok = new JButton[16];
Random rand = new Random();
float r = rand.nextFloat();
float g = rand.nextFloat();
float b = rand.nextFloat();
Color randomColor = new Color(r, g, b);

public GF(){
super("game");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(500,500);
FlowLayout layout1 = new FlowLayout(FlowLayout.CENTER);
setLayout(layout1);
GridLayout layout2 = new GridLayout(4,4);
panel.setLayout(layout2);
for (int i = 0; i < panelek.length; i++) {
panelek[i].setBackground(randomColor);
panel.add(panelek[i]);

}

add(panel);
setVisible(true);

}
public static void main(String[] args) {
GF asd = new GF();
}
}

Thanks for your help:)

Reply viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.
_Yogi_
Offline
Joined: 2011-09-26
Points: 0

This is because you have created an array of references and no objects are made to attach to that reference ...

Replace your for loop with this..

for (int i = 0; i < panelek.length; i++) {
panelek[i] = new JPanel();
panelek[i].setBackground(randomColor);
panel.add(panelek[i]);

}

And also Color(r , g , b) r, g, b should be between 0 and 1..

tobimichigan
Offline
Joined: 2011-09-03
Points: 0

I looked through your code Chillman, @

{

for (int i = 0; i < panelek.length; i++)

}

Is "panelek.length" supposed to be a var? or a meth? from where?