....
But i want to test when it is null without having to catch the null pointer
exception.
I think we both went wrong on this one, I
whipped up an example to check some things,..
(ahem..) ignore the earlier one.
<sscce>
import javax.swing.*;
public class TestTextArea {
public static void main(String args[]) {
JFrame f = new JFrame();
String s = null;
JTextArea ta = new JTextArea(s);
f.getContentPane().add(ta);
f.validate();
f.setSize(f.getPreferredSize());
f.setVisible(true);
if ( ta.getText()==null ) {
System.out.println("TextArea is null!");
} else {
System.out.println("TextArea is '" + ta.getText() + "'" );
}
ta.setText(null);
if ( ta.getText()==null ) {
System.out.println("TextArea is null!");
} else {
System.out.println("TextArea is '" + ta.getText() + "'" );
}
}
}
</sscce>
Even when instantiated with a null string, then
set to a bull string, the values returned were ..
TextArea is ''
TextArea is ''
both times, using Java 1.5.
So *I* delved back into the JDocs...
<
http://java.sun.com/j2se/1.5.0/docs/api/javax/swing/JTextArea.html#JTextArea()>
"Constructs a new TextArea. A default model is set,
the initial string is null, and rows/columns are set to 0. "
<
http://java.sun.com/j2se/1.5.0/docs/api/javax/swing/text/JTextComponent.html#getText()>
"If the underlying document is null, will give a NullPointerException."
Note that it says if the underlying *document* is 'null',
that corresponds to the *model*, not the text itself..
Apparently, Sun has decided that even if the String
contained in the JTextArea is null, it will return
a 0 length String.
That is as far as I understand it at the moment.
BTW. To demonstrate teting for null..
<sscce>
public class TestNull {
public static void main(String args[]) {
String s = null;
if ( s==null ) {
System.out.println("String is null!");
} else {
System.out.println("String is '" + s + "'" );
}
}
}
</sscce>
No exception needs to be thrown, and nobody
needs to get nailed to anything.
HTH