JUNGE
JUNGE

Reputation: 73

nullpointerException on a JTextfield with Text in it

So you guys said you don't have enough information to help me. I'm sorry it's the first time I asked a question in such a forum and I didn't work a long time with Java.

So here's my whole code, there could be a lots of faults but I'm glad if you help me to solve them and say me how to do better Java Programming in all.

Main Class:

public class Main {
  public static void main(String[] args) {
    new Main().top();
  }

  void top() {

    GUI g = new GUI();


  }  
}

Class GUI:

import java.awt.event.ActionListener;
import java.text.SimpleDateFormat;
import javax.swing.*;

public class GUI {

JFrame frame;
JPanel panel;
static JLabel label;
static JLabel username_bezeichnung;
static JLabel vorname_bezeichnung;
static JLabel nachname_bezeichnung;
static JLabel geburtstag_bezeichnung;
static JLabel email_bezeichnung;
static JLabel passwort_bezeichnung;
static JButton registrieren;
static JButton login;
static JButton registrierenBestätigen;
static JTextField username;
static JTextField vorname;
static JTextField nachname;
static JTextField email;
static JFormattedTextField geburtstag;
static JPasswordField passwort;


void gui() {

  ListenerHome h = new ListenerHome();
  ListenerRegistrieren r = new ListenerRegistrieren();

    /**
     * Frames
     */
    // Frame Main
    frame = new JFrame("Main");
    frame.setSize(800, 600);
    frame.setLocation(600, 200);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setVisible(true);

    /**
     * Panels
     */
    // Panel Main
    panel = new JPanel();
    panel.setSize(780, 475);
    panel.setLayout(null);
    frame.add(panel);

    /**
     * Labels
     */
    // Label Main
    label = new JLabel();
    label.setSize(200, 300);
    label.setLocation(230, 30);
    label.setVisible(true);
    label.setText("Guten Tag, was möchten Sie tun?");
    panel.add(label);

    // Label Username
    username_bezeichnung = new JLabel();
    username_bezeichnung.setBounds(65, 50, 120, 30);
    username_bezeichnung.setVisible(false);
    username_bezeichnung.setText("Username");
    panel.add(username_bezeichnung);

    // Label Vorname
    vorname_bezeichnung = new JLabel();
    vorname_bezeichnung.setBounds(65, 90, 120, 30);
    vorname_bezeichnung.setVisible(false);
    vorname_bezeichnung.setText("Vorname");
    panel.add(vorname_bezeichnung);

    // Label Nachname
    nachname_bezeichnung = new JLabel();
    nachname_bezeichnung.setBounds(65, 130, 120, 30);
    nachname_bezeichnung.setVisible(false);
    nachname_bezeichnung.setText("Nachname");
    panel.add(nachname_bezeichnung);

    // Label Geburtstag
    geburtstag_bezeichnung = new JLabel();
    geburtstag_bezeichnung.setBounds(390, 50, 120, 30);
    geburtstag_bezeichnung.setVisible(false);
    geburtstag_bezeichnung.setText("Geburtstag");
    panel.add(geburtstag_bezeichnung);

    // Label E-Mail
    email_bezeichnung = new JLabel();
    email_bezeichnung.setBounds(390, 90, 120, 30);
    email_bezeichnung.setVisible(false);
    email_bezeichnung.setText("E-Mail");
    panel.add(email_bezeichnung);

    // Label Passwort
    passwort_bezeichnung = new JLabel();
    passwort_bezeichnung.setBounds(390, 130, 120, 30);
    passwort_bezeichnung.setVisible(false);
    passwort_bezeichnung.setText("Passwort");
    panel.add(passwort_bezeichnung);

    /**
     * Buttons
     */
    // Button registrieren
    registrieren = new JButton("Registrieren");
    registrieren.setLocation(200, 320);
    registrieren.setSize(120, 50);
    registrieren.setVisible(true);
    registrieren.addActionListener(h);
    panel.add(registrieren);

    // Button login
    login = new JButton("Login");
    login.setLocation(350, 320);
    login.setSize(120, 50);
    login.setVisible(true);
    login.addActionListener(h);
    panel.add(login);

    // Button registrieren bestätigen
    registrierenBestätigen = new JButton("Registrieren");
    registrierenBestätigen.setLocation(390, 350);
    registrierenBestätigen.setSize(120, 50);
    registrierenBestätigen.setVisible(false);
    registrierenBestätigen.addActionListener(r);
    panel.add(registrierenBestätigen);

    /**
     * Textfields
     */
    // Textfield Username
    username = new JTextField("", 20);
    username.setBounds(150, 50, 120, 30);
    username.setVisible(false);
    panel.add(username);

    // Textfield Vorname
    vorname = new JTextField("", 20);
    vorname.setBounds(150, 90, 120, 30);
    vorname.setVisible(false);
    panel.add(vorname);

    // Textfield Nachname
    nachname = new JTextField("", 20);
    nachname.setBounds(150, 130, 120, 30);
    nachname.setVisible(false);
    panel.add(nachname);

    // Textfield Geburtstag
    geburtstag = new JFormattedTextField(new SimpleDateFormat("dd.MM.yyyy")); 
    geburtstag.setValue(new java.util.Date());
    geburtstag.setBounds(475, 90, 120, 30);
    geburtstag.setVisible(false);
    panel.add(geburtstag);

    // Textfield E-Mail
    email = new JTextField("", 25);
    email.setBounds(475, 50, 120, 30);
    email.setVisible(false);
    panel.add(email);

    // Passwortfield Passwort
    passwort = new JPasswordField("", 20);
    passwort.setBounds(475, 130, 120, 30);
    passwort.setVisible(false);
    panel.add(passwort);

}
}

Class ListenerHome

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class ListenerHome implements ActionListener {



@Override
public void actionPerformed(ActionEvent e) {
    if (e.getSource() == GUI.registrieren) {
        GUI.label.setVisible(false);
        GUI.username_bezeichnung.setVisible(true);
        GUI.vorname_bezeichnung.setVisible(true);
        GUI.nachname_bezeichnung.setVisible(true);
        GUI.geburtstag_bezeichnung.setVisible(true);
        GUI.email_bezeichnung.setVisible(true);
        GUI.passwort_bezeichnung.setVisible(true);
        GUI.registrieren.setVisible(false);
        GUI.login.setVisible(false);
        GUI.registrierenBestätigen.setVisible(true);
        GUI.username.setVisible(true);
        GUI.vorname.setVisible(true);
        GUI.nachname.setVisible(true);
        GUI.email.setVisible(true);
        GUI.geburtstag.setVisible(true);
        GUI.passwort.setVisible(true);


    }
}
}

Class ListenerRegistrieren

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;

public class ListenerRegistrieren implements ActionListener {


    public void actionPerformed(ActionEvent e) {        
        if(e.getSource() == GUI.registrierenBestätigen) {
                addBenutzer();
        }
    }



private static void addBenutzer() {

    try {

    Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
    Connection conn = DriverManager.getConnection("jdbc:odbc:MSAccess");
    PreparedStatement pstm;
    String sql = "Insert Into Benutzer ('Benutername', 'Vorname', 'Nachname', 'E-Mail') values ('?','?','?','?')";
    pstm = conn.prepareStatement(sql);

    // SQL Statements
    pstm.setString(1, GUI.username.getText());
    pstm.setString(2, GUI.vorname.getText());
    pstm.setString(3, GUI.nachname.getText());
    pstm.setString(4, GUI.email.getText());
    pstm.executeUpdate();

    } catch (Exception e) {
        e.printStackTrace();
    }
}
}

Stack Trace

java.lang.NullPointerException
at sun.jdbc.odbc.JdbcOdbcPreparedStatement.clearParameter(Unknown Source)
at sun.jdbc.odbc.JdbcOdbcPreparedStatement.setChar(Unknown Source)
at sun.jdbc.odbc.JdbcOdbcPreparedStatement.setString(Unknown Source)
at verwaltung.ListenerRegistrieren.addBenutzer(ListenerRegistrieren.java:37)
at verwaltung.ListenerRegistrieren.actionPerformed(ListenerRegistrieren.java:20)
at javax.swing.AbstractButton.fireActionPerformed(Unknown Source)
at javax.swing.AbstractButton$Handler.actionPerformed(Unknown Source)
at javax.swing.DefaultButtonModel.fireActionPerformed(Unknown Source)
at javax.swing.DefaultButtonModel.setPressed(Unknown Source)
at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(Unknown Source)
at java.awt.Component.processMouseEvent(Unknown Source)
at javax.swing.JComponent.processMouseEvent(Unknown Source)
at java.awt.Component.processEvent(Unknown Source)
at java.awt.Container.processEvent(Unknown Source)
at java.awt.Component.dispatchEventImpl(Unknown Source)
at java.awt.Container.dispatchEventImpl(Unknown Source)
at java.awt.Component.dispatchEvent(Unknown Source)
at java.awt.LightweightDispatcher.retargetMouseEvent(Unknown Source)
at java.awt.LightweightDispatcher.processMouseEvent(Unknown Source)
at java.awt.LightweightDispatcher.dispatchEvent(Unknown Source)
at java.awt.Container.dispatchEventImpl(Unknown Source)
at java.awt.Window.dispatchEventImpl(Unknown Source)
at java.awt.Component.dispatchEvent(Unknown Source)
at java.awt.EventQueue.dispatchEventImpl(Unknown Source)
at java.awt.EventQueue.access$200(Unknown Source)
at java.awt.EventQueue$3.run(Unknown Source)
at java.awt.EventQueue$3.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
at java.awt.EventQueue$4.run(Unknown Source)
at java.awt.EventQueue$4.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(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)

I hope you can help me better now. Thanks for your help guys!

Upvotes: 0

Views: 662

Answers (3)

Dennis Kriechel
Dennis Kriechel

Reputation: 3749

I guess its not the JTextfield that throws the NullPointer but the GUI. This might not have a reference to the object on top.

Like i see from your Code, you dont have a Constructor for the GUI class. You need to change

void gui() {

into

public GUI() {

After changing this, and removing the Databaseconnection, i could acces the Field on the GUI, the way with static variables is ugly but works:

    private static void addBenutzer() {

    try {

        System.out.println(GUI.username.getText());

    } catch (Exception e) {
        e.printStackTrace();
    }
}

If the exception still happening now, there is something wrong with the database connection which i cant test any further, because i dont have the db and the drives. but to me the db connections looks allright.

Here are all classes how it should be done:

import java.text.SimpleDateFormat;

import javax.swing.JButton;
import javax.swing.JFormattedTextField;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JPasswordField;
import javax.swing.JTextField;

public class GUI {

    JFrame frame;
    JPanel panel;
    JLabel label;
    JLabel username_bezeichnung;
    JLabel vorname_bezeichnung;
    JLabel nachname_bezeichnung;
    JLabel geburtstag_bezeichnung;
    JLabel email_bezeichnung;
    JLabel passwort_bezeichnung;
    JButton registrieren;
    JButton login;
    JButton registrierenBestätigen;
    JTextField username;
    JTextField vorname;
    JTextField nachname;
    JTextField email;
    JFormattedTextField geburtstag;
    JPasswordField passwort;

    public GUI() {

        ListenerHome h = new ListenerHome(this);
        ListenerRegistrieren r = new ListenerRegistrieren(this);

        /**
         * Frames
         */
        // Frame Main
        frame = new JFrame("Main");
        frame.setSize(800, 600);
        frame.setLocation(600, 200);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setVisible(true);

        /**
         * Panels
         */
        // Panel Main
        panel = new JPanel();
        panel.setSize(780, 475);
        panel.setLayout(null);
        frame.add(panel);

        /**
         * Labels
         */
        // Label Main
        label = new JLabel();
        label.setSize(200, 300);
        label.setLocation(230, 30);
        label.setVisible(true);
        label.setText("Guten Tag, was m�chten Sie tun?");
        panel.add(label);

        // Label Username
        username_bezeichnung = new JLabel();
        username_bezeichnung.setBounds(65, 50, 120, 30);
        username_bezeichnung.setVisible(false);
        username_bezeichnung.setText("Username");
        panel.add(username_bezeichnung);

        // Label Vorname
        vorname_bezeichnung = new JLabel();
        vorname_bezeichnung.setBounds(65, 90, 120, 30);
        vorname_bezeichnung.setVisible(false);
        vorname_bezeichnung.setText("Vorname");
        panel.add(vorname_bezeichnung);

        // Label Nachname
        nachname_bezeichnung = new JLabel();
        nachname_bezeichnung.setBounds(65, 130, 120, 30);
        nachname_bezeichnung.setVisible(false);
        nachname_bezeichnung.setText("Nachname");
        panel.add(nachname_bezeichnung);

        // Label Geburtstag
        geburtstag_bezeichnung = new JLabel();
        geburtstag_bezeichnung.setBounds(390, 50, 120, 30);
        geburtstag_bezeichnung.setVisible(false);
        geburtstag_bezeichnung.setText("Geburtstag");
        panel.add(geburtstag_bezeichnung);

        // Label E-Mail
        email_bezeichnung = new JLabel();
        email_bezeichnung.setBounds(390, 90, 120, 30);
        email_bezeichnung.setVisible(false);
        email_bezeichnung.setText("E-Mail");
        panel.add(email_bezeichnung);

        // Label Passwort
        passwort_bezeichnung = new JLabel();
        passwort_bezeichnung.setBounds(390, 130, 120, 30);
        passwort_bezeichnung.setVisible(false);
        passwort_bezeichnung.setText("Passwort");
        panel.add(passwort_bezeichnung);

        /**
         * Buttons
         */
        // Button registrieren
        registrieren = new JButton("Registrieren");
        registrieren.setLocation(200, 320);
        registrieren.setSize(120, 50);
        registrieren.setVisible(true);
        registrieren.addActionListener(h);
        panel.add(registrieren);

        // Button login
        login = new JButton("Login");
        login.setLocation(350, 320);
        login.setSize(120, 50);
        login.setVisible(true);
        login.addActionListener(h);
        panel.add(login);

        // Button registrieren best�tigen
        registrierenBestätigen = new JButton("Registrieren");
        registrierenBestätigen.setLocation(390, 350);
        registrierenBestätigen.setSize(120, 50);
        registrierenBestätigen.setVisible(false);
        registrierenBestätigen.addActionListener(r);
        panel.add(registrierenBestätigen);

        /**
         * Textfields
         */
        // Textfield Username
        username = new JTextField("", 20);
        username.setBounds(150, 50, 120, 30);
        username.setVisible(false);
        panel.add(username);

        // Textfield Vorname
        vorname = new JTextField("", 20);
        vorname.setBounds(150, 90, 120, 30);
        vorname.setVisible(false);
        panel.add(vorname);

        // Textfield Nachname
        nachname = new JTextField("", 20);
        nachname.setBounds(150, 130, 120, 30);
        nachname.setVisible(false);
        panel.add(nachname);

        // Textfield Geburtstag
        geburtstag = new JFormattedTextField(new SimpleDateFormat("dd.MM.yyyy"));
        geburtstag.setValue(new java.util.Date());
        geburtstag.setBounds(475, 90, 120, 30);
        geburtstag.setVisible(false);
        panel.add(geburtstag);

        // Textfield E-Mail
        email = new JTextField("", 25);
        email.setBounds(475, 50, 120, 30);
        email.setVisible(false);
        panel.add(email);

        // Passwortfield Passwort
        passwort = new JPasswordField("", 20);
        passwort.setBounds(475, 130, 120, 30);
        passwort.setVisible(false);
        panel.add(passwort);

    }
}

-

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class ListenerHome implements ActionListener {

    private GUI gui;

    public ListenerHome(GUI gui) {
        this.gui = gui;
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        if (e.getSource() == gui.registrieren) {
            gui.label.setVisible(false);
            gui.username_bezeichnung.setVisible(true);
            gui.vorname_bezeichnung.setVisible(true);
            gui.nachname_bezeichnung.setVisible(true);
            gui.geburtstag_bezeichnung.setVisible(true);
            gui.email_bezeichnung.setVisible(true);
            gui.passwort_bezeichnung.setVisible(true);
            gui.registrieren.setVisible(false);
            gui.login.setVisible(false);
            gui.registrierenBestätigen.setVisible(true);
            gui.username.setVisible(true);
            gui.vorname.setVisible(true);
            gui.nachname.setVisible(true);
            gui.email.setVisible(true);
            gui.geburtstag.setVisible(true);
            gui.passwort.setVisible(true);

        }
    }
}

-

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;

public class ListenerRegistrieren implements ActionListener {

    private GUI gui;

    public ListenerRegistrieren(GUI gui) {
        this.gui = gui;
    }

    public void actionPerformed(ActionEvent e) {
        if (e.getSource() == gui.registrierenBestätigen) {
            addBenutzer();
        }
    }

    private void addBenutzer() {

        try {

            Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
            Connection conn = DriverManager.getConnection("jdbc:odbc:MSAccess");
            PreparedStatement pstm;
            String sql = "Insert Into Benutzer ('Benutername', 'Vorname', 'Nachname', 'E-Mail') values ('?','?','?','?')";
            pstm = conn.prepareStatement(sql);

            // SQL Statements
            pstm.setString(1, gui.username.getText());
            pstm.setString(2, gui.vorname.getText());
            pstm.setString(3, gui.nachname.getText());
            pstm.setString(4, gui.email.getText());
            pstm.executeUpdate();

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

-

public class Main {
    public static void main(String[] args) {
        new GUI();

    }

}

Upvotes: 2

Mike Thomsen
Mike Thomsen

Reputation: 37526

If this is where it's happening, it's most likely not the JTextfield:

GUI.username.getText()

You didn't give us much to go on here, but based on your code above, I'm guessing that you have a variable named GUI with a public property named username that you forgot to do something like this with:

GUI.username = username;

If GUI.username is not set to a JTextfield, any method call on it will throw a NullPointerException.

Also, you don't need to put quotes around ? in your prepared statement. In fact, it's better if you don't since prepareStatement is supposed to be handled by the vendor-specific driver. This is fine:

Insert Into Benutzer ('Benutername', 'Vorname', 'Nachname', 'E-Mail') values (?, ?, ?, ?)

That'll push all responsibility for getting it right onto the MS Access JDBC driver.

Upvotes: 0

atk
atk

Reputation: 9324

A null pointer exception means that you are trying to operate on a variable that is currently set to null instead pointing to an instance of an object. The most common form of this exception is of the form

Object myObject = ...;
// for whatever reason, myObject = null
myObject.someMethod();

In the third line, when the someMethod() method of myObject is called, the runtime must first locate the object referenced by the myObject variable. If myObject does not reference a valid instance, then the runtime will not be able to locate and execute someMethod(). This is an error condition, where the defined resolution is to throw a NullPointerException.

In your code, it is very difficult to tell what caused the NullPointerException to be thrown. You can make this very easy on yourself by printing or otherwise displaying the stack trace of the exception. The stack trace will point to a specific file and line of code where the null pointer dereference occurs.

It is important to review the entire stack trace. You may discover that the null pointer dereference occurs within a method you call, rather than in your own code. This means that you probably passed a null object. Or you passed an object one of whose methods or accessible slots contains a null value, and the called method depends upon this value. Reading through the stack trace, you will be able to discover the last line of your code that was called. You can then decide whether to investigate the variables you pass (such as checking their values in a debugger or by printing out their values to System.out) or if you want to try and find the source of the code you are calling, and if available manually backtrace to determine where the error occurred.

You may also discover that the line where the exception is thrown is ambiguous - just reading it, there may be several potential causes for the exception, as in the following code...

myObject.method1().method2().method3();

... where any of the following might cause the exception: * myObject may be null * the return value from myObject.method1() may be null * the return value from myObject.method1().method2() may be null

In this case, there are two easy ways to investigate. First, you may run the code in a debugger and use the debugger to identify what variable fails to dereference. Second, you may restructure your code so that debugging is easier...

result1 = myObject.method1();
result2 = myObject.method2();
myObject.method3();

The correct approach depends upon your team, your coding standards, the readability of the code being restructured, and a host of other considerations that are out of scope of this answer.

Upvotes: 0

Related Questions