Search code examples
javanullpointerexceptionjtextfield

button action listener for text field doesnt work


I tried to make this GUI program which take input from the user by text field and should return it with uppercase convertion:

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

public class gui {
 JTextField textField;
 JFrame frame;
 JButton button;

public static void main(String args[]) {
    gui tr = new gui();
    tr.go();
}

public void go() {  
    JFrame frame = new JFrame();
    JTextField textField = new JTextField("Type here);
    JButton button = new JButton("Send");
    button.addActionListener(new buttonListener());
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.getContentPane().add(BorderLayout.CENTER, textField);
    frame.getContentPane().add(BorderLayout.SOUTH, button);
    frame.setSize(300, 300);
    frame.setVisible(true);

}

class buttonListener implements ActionListener {
    public void actionPerformed(ActionEvent event) {
        String txt;
        txt = textField.getText();
        txt = txt.toUpperCase();
        textField.setText(txt);
    }
}
}

The file respond by null pointer exception. Ive tried to add exception handler, and to change the program based on instances Ive seen online. please explain to me my mistake. Thank you.


Solution

  • The problem is that your class member JTextField textField is never initialized, yet you are trying to use it within your actionPerformed

    Inside your go() method you create a new JTextField textField that has nothing do to with the original textField.

    In fact inside go() you basically create new objects

    JFrame frame = new JFrame();
    JTextField textField = new JTextField("Type here);
    JButton button = new JButton("Send");
    

    Instead of initializing those already defined for your class.