Home > Software design >  NullPointerException: Cannot invoke "JComboBox.getSelectedIndex()" because "this.this
NullPointerException: Cannot invoke "JComboBox.getSelectedIndex()" because "this.this

Time:05-15

My Combo Box Always Returns Null Value.

In my Project "Attendance Management System" ,I need to validate the selected Item in the Combo box. But it returns null. How can I get it to return the item selected from the Combo Box. I use Eclipse IDE to run my project. Here is My Code:

import java.awt.*;
import javax.swing.*;
import javax.swing.border.BevelBorder;
public class admin extends javax.swing.JFrame {
private static final long serialVersionUID=1L;
@SuppressWarnings({ "unchecked", "rawtypes" })
admin(){
//setResizable(false);  
JFrame newFrame=new JFrame("Admin");
newFrame.getContentPane().setForeground(new Color(0, 0, 0));
newFrame.getContentPane().setFont(new Font("Arial Black", Font.BOLD, 15));
newFrame.getContentPane().setBackground(new Color(0, 191, 255));
newFrame.setSize(1000,600);
newFrame.setVisible(true);
newFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

JLabel lblNewLabel = new JLabel("Welcome Admin");
lblNewLabel.setBounds(416, 75, 185, 28);
lblNewLabel.setFont(new Font("Arial Black", Font.BOLD, 18));
newFrame.getContentPane().setLayout(null);
newFrame.getContentPane().add(lblNewLabel);
JButton btnNewButton = new JButton("Go");
btnNewButton.setBorder(new BevelBorder(BevelBorder.RAISED, new Color(0, 0, 255), null, 
Color.BLUE, null));
btnNewButton.setFont(new Font("Tahoma", Font.BOLD, 13));
btnNewButton.setBounds(471, 343, 85, 35);
btnNewButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
    if(comboBox_1.getSelectedItem().toString().equals("Student"))
    {

   JOptionPane.showMessageDialog(null, "You can  Login !","", JOptionPane.ERROR_MESSAGE);
   //new Register_Student().setVisible(true); 
   }
}
});
newFrame.getContentPane().add(btnNewButton);
JComboBox comboBox_1 = new JComboBox();
comboBox_1.setBorder(new BevelBorder(BevelBorder.LOWERED, new Color(0, 0, 255), null, new 
 Color(0, 0, 255), null));
 comboBox_1.setFont(new Font("Arial Black", Font.BOLD, 14));
 comboBox_1.setModel(new DefaultComboBoxModel(new String[] {"Student", "Teacher", "Parent"}));

 comboBox_1.setBounds(359, 179, 291, 80);
 newFrame.getContentPane().add(comboBox_1);
  pack();
  }
public static void main(String args[]) {

try {
    for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
        if ("Nimbus".equals(info.getName())) {
            javax.swing.UIManager.setLookAndFeel(info.getClassName());
            break;
        }
    }
} catch (ClassNotFoundException ex) {
    java.util.logging.Logger.getLogger(admin.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
    java.util.logging.Logger.getLogger(admin.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
    java.util.logging.Logger.getLogger(admin.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
    java.util.logging.Logger.getLogger(admin.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}

java.awt.EventQueue.invokeLater(new Runnable() {
    public void run() {
        new admin().setVisible(true);
        
    }
});
}
 private javax.swing.JComboBox<String> comboBox_1;
 }

Immediate help will be appreciated. Thank you in advance:)

CodePudding user response:

You have created two combo box objects. Please remove the ComboBox declaration on the top or JComboBox comboBox_1 = to comboBox_1 = in the constructor.

import java.awt.*;
import javax.swing.*;
import javax.swing.border.BevelBorder;
public class admin extends javax.swing.JFrame {
    private static final long serialVersionUID=1L;
    @SuppressWarnings({ "unchecked", "rawtypes" })
    admin(){
//setResizable(false);
        JFrame newFrame=new JFrame("Admin");
        newFrame.getContentPane().setForeground(new Color(0, 0, 0));
        newFrame.getContentPane().setFont(new Font("Arial Black", Font.BOLD, 15));
        newFrame.getContentPane().setBackground(new Color(0, 191, 255));
        newFrame.setSize(1000,600);
        newFrame.setVisible(true);
        newFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        JLabel lblNewLabel = new JLabel("Welcome Admin");
        lblNewLabel.setBounds(416, 75, 185, 28);
        lblNewLabel.setFont(new Font("Arial Black", Font.BOLD, 18));
        newFrame.getContentPane().setLayout(null);
        newFrame.getContentPane().add(lblNewLabel);
        JComboBox comboBox_1 = new JComboBox();
        comboBox_1.setBorder(new BevelBorder(BevelBorder.LOWERED, new Color(0, 0, 255), null, new
                Color(0, 0, 255), null));
        comboBox_1.setFont(new Font("Arial Black", Font.BOLD, 14));
        comboBox_1.setModel(new DefaultComboBoxModel(new String[] {"Student", "Teacher", "Parent"}));

        comboBox_1.setBounds(359, 179, 291, 80);
        JButton btnNewButton = new JButton("Go");
        btnNewButton.setBorder(new BevelBorder(BevelBorder.RAISED, new Color(0, 0, 255), null,
                Color.BLUE, null));
        btnNewButton.setFont(new Font("Tahoma", Font.BOLD, 13));
        btnNewButton.setBounds(471, 343, 85, 35);
        btnNewButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                if(comboBox_1.getSelectedItem().toString().equals("Student"))
                {

                    JOptionPane.showMessageDialog(null, "You can  Login !","", JOptionPane.ERROR_MESSAGE);
                    //new Register_Student().setVisible(true);
                }
            }
        });
        newFrame.getContentPane().add(btnNewButton);

        newFrame.getContentPane().add(comboBox_1);
        pack();
    }
    public static void main(String args[]) {

        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(admin.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(admin.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(admin.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(admin.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }

        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new admin().setVisible(true);

            }
        });
    }
    private javax.swing.JComboBox<String> comboBox_1;
}

CodePudding user response:

You're shadowing your variables. That is, you've declared comboBox_1 twice, once as an instance field and once as a local variable...

public class admin extends javax.swing.JFrame {
    admin() {
        //...
        JComboBox comboBox_1 = new JComboBox();
        //...
    }
    //...
    private javax.swing.JComboBox<String> comboBox_1;
}

Get rid of the local decleration

public class admin extends javax.swing.JFrame {
    admin() {
        //...
        comboBox_1 = new JComboBox();
        //...
    }

Now, having said that, you have another issue. admin extends from JFrame...

public class admin extends javax.swing.JFrame {

But then you create a second JFrame in the constructor...

public class admin extends javax.swing.JFrame {
    private static final long serialVersionUID = 1L;

    @SuppressWarnings({"unchecked", "rawtypes"})
    admin() {
        JFrame newFrame = new JFrame("Admin");

So, when I do new admin().setVisble(true) which frame is getting displayed?

As a general recommendation, you should avoid extending directly from top level containers like JFrame, you're not adding any new functionality to the class and you're restricting yourself to a single use case.

And, you really, really, really want to learn how to use layout managers, see Laying Out Components Within a Container for more details

import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import javax.swing.JFrame;
import java.awt.Font;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.border.BevelBorder;

public class Main {

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

    public Main() {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                JFrame frame = new JFrame();
                frame.add(new Admin());
                frame.pack();
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
            }
        });
    }

    public class Admin extends JPanel {
        private static final long serialVersionUID = 1L;

        @SuppressWarnings({"unchecked", "rawtypes"})
        Admin() {
            setForeground(new Color(0, 0, 0));
            setBackground(new Color(0, 191, 255));

            setLayout(new GridBagLayout());
            GridBagConstraints gbc = new GridBagConstraints();
            gbc.gridwidth = GridBagConstraints.REMAINDER;
            gbc.insets = new Insets(50, 0, 50, 0);

            JLabel lblNewLabel = new JLabel("Welcome Admin");
            lblNewLabel.setFont(new Font("Arial Black", Font.BOLD, 18));
            add(lblNewLabel, gbc);

            comboBox_1 = new JComboBox();
            comboBox_1.setBorder(new BevelBorder(BevelBorder.LOWERED, new Color(0, 0, 255), null, new Color(0, 0, 255), null));
            comboBox_1.setFont(new Font("Arial Black", Font.BOLD, 14));
            comboBox_1.setModel(new DefaultComboBoxModel(new String[]{"Student", "Teacher", "Parent"}));
            gbc.ipady = 100;
            gbc.insets = new Insets(0, 0, 0, 0);
            add(comboBox_1, gbc);

            JButton btnNewButton = new JButton("Go");
            btnNewButton.setBorder(new BevelBorder(BevelBorder.RAISED, new Color(0, 0, 255), null, Color.BLUE, null));
            btnNewButton.setFont(new Font("Tahoma", Font.BOLD, 13));
            btnNewButton.addActionListener(new java.awt.event.ActionListener() {
                public void actionPerformed(java.awt.event.ActionEvent evt) {
                    if (comboBox_1.getSelectedItem().toString().equals("Student")) {

                        JOptionPane.showMessageDialog(null, "You can  Login !", "", JOptionPane.ERROR_MESSAGE);
                        //new Register_Student().setVisible(true); 
                    }
                }
            });
            gbc.insets = new Insets(50, 0, 50, 0);
            gbc.ipady = 0;
            add(btnNewButton, gbc);
        }

        @Override
        public Dimension getPreferredSize() {
            return new Dimension(1000, 600);
        }

        private javax.swing.JComboBox<String> comboBox_1;
    }
}
  • Related