JPanel Array -- NullPointerException

T

tomzhi

I am new to Java, learning GUI. I am trying to create a TabbedPane
with 10 tabs, by using array of JPanel. However, JPanel arrays are
always null. I do not understand why they are null when they are
arrays but not otherwise. I would appreciate explanation and help on
this code. Thanks

public static void main(String[] args) {
JTabbedPane tab = new JTabbedPane();

int i;
JTextField[] text = new JTextField[10]; //
textfield to add to each panel
JPanel [] panel = new JPanel[10]; //array
of panel

//name of each tab
String [] name = {"One",
"Two","Three","Four","Five","Six","Seven","Eight","Nine","Ten"};

for (i=1;i<10;i++) {
panel.add(text); //
NullPointerException here
tab.addTab(name,panel);
}

System.out.println(tab);
JFrame frame = new JFrame("Testing");
frame.add(tab);
frame.setSize(500,500);
frame.setVisible(true);
}
 
C

Chris Dollin

tomzhi said:
I am new to Java, learning GUI. I am trying to create a TabbedPane
with 10 tabs, by using array of JPanel. However, JPanel arrays are
always null. I do not understand why they are null when they are
arrays but not otherwise.

When you create an array of references using `new ClassName[N]`,
each element of that array is null. If you want to put something
interesting into the elements, you have to do so yourself.

[It's null because there's no [general] way of knowing how to construct
an element to go into that slot.]
 
T

tomzhi

tomzhi said:
I am new to Java, learning GUI. I am trying to create a TabbedPane
with 10 tabs, by using array of JPanel. However, JPanel arrays are
always null. I do not understand why they are null when they are
arrays but not otherwise.

When you create an array of references using `new ClassName[N]`,
each element of that array is null. If you want to put something
interesting into the elements, you have to do so yourself.

[It's null because there's no [general] way of knowing how to construct
an element to go into that slot.]

--
Chris "loopy" Dollin

Hewlett-Packard Limited Cain Road, Bracknell, registered no:
registered office: Berks RG12 1HN 690597 England



Chris, but how do I go about doing it?
panel =?

the right said need to be a JPanel too.
 
T

tomzhi

Thanks. I figured out that I just needed to add panel=new JPanel()
and box=new JComboBox();
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,582
Members
45,067
Latest member
HunterTere

Latest Threads

Top