The Artima Developer Community
Sponsored Link

Java Answers Forum
NullPointerException ??

2 replies on 1 page. Most recent reply: Feb 4, 2004 10:51 AM by twc

Welcome Guest
  Sign In

Go back to the topic listing  Back to Topic List Click to reply to this topic  Reply to this Topic Click to search messages in this forum  Search Forum Click for a threaded view of the topic  Threaded View   
Previous Topic   Next Topic
Flat View: This topic has 2 replies on 1 page
aj3423 aj

Posts: 16
Nickname: aj3423
Registered: Aug, 2003

NullPointerException ?? Posted: Jan 23, 2004 4:58 AM
Reply to this message Reply
Advertisement
it can compile, but NullPointerException occured when i run it. what's the matter ?

// code :
import javax.swing.*;
import java.awt.*;

class Temp extends JFrame {

JLabel[] lbl;

public Temp() {
lbl = new JLabel[1];
Icon image = new ImageIcon("1.jpg");
lbl[0].setIcon(image);
getContentPane().add(lbl[0]);
}

public static void main(String args[]) {
Temp t = new Temp();
t.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
t.show();
t.pack();
}
}


Joe Parks

Posts: 107
Nickname: joeparks
Registered: Aug, 2003

Re: NullPointerException ?? Posted: Jan 23, 2004 9:27 PM
Reply to this message Reply
// this will declare an array (the element in the array is null)
JLabel [] lbl = new JLabel[1];
 
// you have to initialize the element
lbl[0] = new JLabel();
 
// now you can invoke methods on the element
lbl[0].setIcon(image);

twc

Posts: 129
Nickname: twc
Registered: Feb, 2004

Re: NullPointerException ?? Posted: Feb 4, 2004 10:51 AM
Reply to this message Reply
NullPointerException means that you have tried to use an object that doesn't really exist yet. In your code, you are creating an array of JLabel objects, but not any JLabel objects. See my comments below.

> it can compile, but NullPointerException occured when i
> run it. what's the matter ?
>
> // code :
> import javax.swing.*;
> import java.awt.*;
>
> class Temp extends JFrame {
>
> JLabel[] lbl;
>
> public Temp() {
> lbl = new JLabel[1]; //creates an array

//add the line below to actually create
lbl[0] = new JLabel(); //the JLabel

> Icon image = new ImageIcon("1.jpg");
//without the line that I added, the lbl[0]
//object does not exist yet.
> lbl[0].setIcon(image);
> getContentPane().add(lbl[0]);
> }
>
> public static void main(String args[]) {
> Temp t = new Temp();
> t.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
> t.show();
> t.pack();
> }
> }

Flat View: This topic has 2 replies on 1 page
Topic: Eclipse runtime workbench Previous Topic   Next Topic Topic: run a java application based server on the web server

Sponsored Links



Google
  Web Artima.com   

Copyright © 1996-2019 Artima, Inc. All Rights Reserved. - Privacy Policy - Terms of Use