coder005
coder005

Reputation: 79

JTextField not working properly

I just want to run a swing application t display a textfield. Following is the code when run the exceptions generated are :

Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
at textf.<init>(textf.java:10)
at textf$1.run(textf.java:35)
at java.awt.event.InvocationEvent.dispatch(Unknown Source)
at java.awt.EventQueue.dispatchEvent(Unknown Source)
at java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.run(Unknown Source)

Please help what to do.

import java.awt.FlowLayout;
import javax.swing.*;

class textf{
JTextField tf;
JFrame j;
textf(){
    new JFrame("TextField Demo");
    j.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    j.setSize(400,200);
    j.setLayout(new FlowLayout());
    tf=new JTextField("press<Enter>",20);

    j.add(tf);
    j.setVisible(true);
}

public static void main(String s[]) {
    SwingUtilities.invokeLater(new Runnable() {
        public void run() {
            new textf();
        }
    });
}
}

Upvotes: 1

Views: 341

Answers (1)

Jon Skeet
Jon Skeet

Reputation: 1502126

You're never assigning a value to j, so it has the default value of null. When you try to dereference it in the second line of your constructor (j.setDefaultCloseOperation(...)) that therefore throws a NullPointerException. Note that this is before you even get to a JTextField...

Just change the first line of your constructor to:

j = new JFrame("TextField Demo");

After that, sort out both the indentation of your code and the naming of your class and variables, so you end up with more maintainable code :)

Upvotes: 3

Related Questions