0

I have tried to develop a simple swing application with actionlisteners. I used JComboBox. It has an actionlistener. When I perform some action on it and click save button I am getting an exception. When I checked with the value obtained in combo box, the value was correct.But still I am getting null pointer exception.

Code:

    package swings;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;

import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;

class Survey extends JFrame {
    JFrame jframe = null;
    JTextField name;
    JTextArea address, hobbies, describe;
    JButton save, cancel;
    JLabel nameLabel, cityLabel, countryLabel, addressLabel, hobbiesLabel, describeLabel;
    JComboBox city=null, country=null;

    String[] citiesIndia = { "Hyderabad", "Kadapa", "Ranchi", "Vizag", "Delhi", "Pune", "Bangalore"};
    String[] citiesPakistan = {"Lahore", "Rawalpindi"};
    String[] citiesUS = {"LA", "New York", "Cancass City", "LaPito"};

    String[] countryList = {"India", "Pakistan", "USA"};

    private void clearAllOPtions() {
        name.setText("");
        country.setSelectedItem(null);
        city.setSelectedItem(null);
        System.out.println(country.getSelectedItem());

        city.setEnabled(false);
        address.setText("");
        hobbies.setText("");
        describe.setText("");       
    }

    public Survey() {
        this.jframe = new JFrame("Survey");
        this.nameLabel = new JLabel("Name : ");
        this.name = new JTextField();
        this.cityLabel = new JLabel("City : ");
        this.city = new JComboBox<String>();
        this.city.setSelectedItem(null);
        this.city.setEnabled(false);
        this.countryLabel = new JLabel("Country : ");
        this.country = new JComboBox<String>(countryList);
        this.country.setSelectedItem(null);
        this.addressLabel = new JLabel("Address : ");
        this.address = new JTextArea();
        this.hobbiesLabel = new JLabel("Hobbies : ");
        this.hobbies = new JTextArea();
        this.describeLabel = new JLabel("Describe : ");
        this.describe = new JTextArea();
        this.save = new JButton(new ImageIcon("save.png"));
        this.cancel = new JButton(new ImageIcon("cancel.png"));
        jframe.add(nameLabel);
        nameLabel.setBounds(50, 100, 70, 30);
        jframe.add(name);
        name.setBounds(150, 100, 150, 30);
        jframe.add(cityLabel);
        countryLabel.setBounds(50, 140, 70, 30);
        jframe.add(city);
        country.setBounds(150, 140, 150, 30);
        jframe.add(countryLabel);
        cityLabel.setBounds(50, 180, 70, 30);
        jframe.add(country);
        city.setBounds(150, 180, 150, 30);
        jframe.add(addressLabel);
        addressLabel.setBounds(50, 220, 70, 30);
        jframe.add(address);
        address.setBounds(150, 220, 150, 30);
        jframe.add(hobbiesLabel);
        hobbiesLabel.setBounds(50, 260, 70, 30);
        jframe.add(hobbies);
        hobbies.setBounds(150, 260, 150, 30);
        jframe.add(describeLabel);
        describeLabel.setBounds(50, 300, 70, 30);
        jframe.add(describe);
        describe.setBounds(150, 300, 150, 30);
        jframe.add(save);
        save.setBounds(130, 350, 50, 50);
        jframe.add(cancel);
        cancel.setBounds(220, 350, 50, 50);
        jframe.setLayout(null);
        jframe.setVisible(true);
        jframe.setSize(500, 500);

        country.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                city.removeAllItems();
                if(country.getSelectedItem().equals("India")){
                    for(String s : citiesIndia){
                        city.addItem(s);
                    }
                }
                if(country.getSelectedItem().equals("Pakistan")){
                    for(String s : citiesPakistan){
                        city.addItem(s);
                    }
                }
                if(country.getSelectedItem().equals("USA")){
                    for(String s : citiesUS){
                        city.addItem(s);
                    }
                }
                city.setEnabled(true);
            }
        });

        save.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                int input = JOptionPane.showConfirmDialog(null, "Details Saved");
                if (input == 0) {
                    FileWriter fw = null;
                    File file = new File("survey.txt");
                    try {
                        if (file.exists()) {
                            fw = new FileWriter(file, true);
                        } else {
                            fw = new FileWriter(file);
                        }
                        fw.write("\nName : " + name.getText());
                        fw.write("\nCity : " + city.getSelectedItem());
                        fw.write("\nCountry : " + country.getSelectedItem());
                        fw.write("\nAddress : " + address.getText());
                        fw.write("\nHobbies : " + hobbies.getText());
                        fw.write("\nDescription : " + describe.getText());
                    } catch (IOException e1) {
                        e1.printStackTrace();
                    } finally {
                        try {
                            fw.close();
                            clearAllOPtions();
                        } catch (IOException e1) {
                            // TODO Auto-generated catch block
                            e1.printStackTrace();
                        }
                    }

                }
            }
        });
        cancel.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                clearAllOPtions();
            }
        });
        jframe.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }

}

public class SwingSurvey {

    public static void main(String[] args) {
        Survey s = new Survey();

    }

}

When I run this and click on save button, I am getting null pointer exception as below:

Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
at swings.Survey$1.actionPerformed(SwingSurvey.java:100)
at javax.swing.JComboBox.fireActionEvent(Unknown Source)
at javax.swing.JComboBox.setSelectedItem(Unknown Source)
at swings.Survey.clearAllOPtions(SwingSurvey.java:34)
at swings.Survey.access$0(SwingSurvey.java:32)
at swings.Survey$2.actionPerformed(SwingSurvey.java:144)
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)

.....

I am getting the exception like above. How to rectify it?

Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
Thedeadman619
  • 881
  • 1
  • 7
  • 14
  • 1) See also [What is a stack trace, and how can I use it to debug my application errors?](http://stackoverflow.com/q/3988788/418556) 2) Java GUIs have to work on different OS', screen size, screen resolution etc. using different PLAFs in different locales. As such, they are not conducive to pixel perfect layout. Instead use layout managers, or [combinations of them](http://stackoverflow.com/a/5630271/418556) along with layout padding and borders for [white space](http://stackoverflow.com/a/17874718/418556). – Andrew Thompson Jul 03 '18 at 11:58
  • Look up your clearAllOPtions() Methode. After this Methode, you want to call country.getSelectedItem() – Wulf Jul 03 '18 at 11:59
  • I am calling clearAllOptions() at the end of the actionPerformed(). Only After getting the value in country. – Thedeadman619 Jul 03 '18 at 12:28
  • 1
    *"I am calling clearAllOptions().."* Tip: Add @Wufo (or whoever, the `@` is important) to *notify* the person of a new comment. – Andrew Thompson Jul 03 '18 at 12:35
  • @Thedeadman619 Look up Java Doc's. [Country.setSelectedItem() actived your Actionslistener](https://docs.oracle.com/javase/7/docs/api/javax/swing/JComboBox.html#setSelectedItem(java.lang.Object)) – Wulf Jul 03 '18 at 12:57
  • 1
    @AndrewThompson Thank you for your suggestion. – Thedeadman619 Jul 03 '18 at 14:36
  • 1
    @Wufo Problem is solved by using the way mentioned in the 1st answer. Thanks for suggestions. – Thedeadman619 Jul 03 '18 at 14:37

1 Answers1

2

This is probably because you set null,

country.setSelectedItem( null );

and then call

country.getSelectedItem().equals("India")

This gives NPE.

To rectify this use string comparison like,

if ( "India".equals( country.getSelectedItem() ))
Dushmantha
  • 2,911
  • 1
  • 14
  • 21
  • he could use **country.getSelectedItem().toString().equals("India")** because he wants to compare strings, but upvoted because this is the most logical answer – Kebab Programmer Jul 03 '18 at 14:37