0

I'm trying to create a ComboBox based on a resource file. I have no issue converting the resource file into an ArrayList. I was hoping to use that ArrayList to populate the ComboBox, I've create using a for loop and this exception is thrown Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException I've tried to create the combobox like this as well jComboBox1.setModel(new DefaultComboBoxModel(cc.getCodes().toArray()));the same exception is thrown. Now i'm using jComboBox1 = new JComboBox(cc.getCodes().toArray()); and no exception is thrown, however the combo box remains empty. I need a combobox that has the capacity to have items remove from it or added to it on the fly. Can anyone help? The source code is below, The method i'm concerned with is the popluteComboBox() method at the very end of the source. I'm calling the method in the Form's constructor.

import java.io.BufferedWriter;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.awt.Font;
import java.awt.Toolkit;
import java.awt.datatransfer.*;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JComboBox;
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 *
 * @author marcsantiago
 */
public class MainForm extends javax.swing.JFrame {

    /**
     * Creates new form MainForm
     * @throws java.io.FileNotFoundException
     */
    public MainForm() throws FileNotFoundException, IOException {

        this.rndn = new RandomNumber();
        popluteComboBox();
        setIcon();
        initComponents();

    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">                          
    private void initComponents() {

        jButton1 = new javax.swing.JButton();
        jTextField1 = new javax.swing.JTextField();
        jComboBox1 = new javax.swing.JComboBox();
        jButton2 = new javax.swing.JButton();
        jButton3 = new javax.swing.JButton();
        jScrollPane1 = new javax.swing.JScrollPane();
        jTextArea1 = new javax.swing.JTextArea();
        jLabel1 = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("Style Code");
        setAlwaysOnTop(true);
        setLocationByPlatform(true);
        setMinimumSize(new java.awt.Dimension(200, 260));
        setResizable(false);
        getContentPane().setLayout(null);

        jButton1.setText("Generate Number");
        jButton1.setToolTipText("");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });
        getContentPane().add(jButton1);
        jButton1.setBounds(0, 30, 160, 29);

        jTextField1.setToolTipText("");
        getContentPane().add(jTextField1);
        jTextField1.setBounds(0, 60, 160, 28);

        jComboBox1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jComboBox1ActionPerformed(evt);
            }
        });
        getContentPane().add(jComboBox1);
        jComboBox1.setBounds(0, 0, 71, 27);

        jButton2.setText("Save Number");
        jButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton2ActionPerformed(evt);
            }
        });
        getContentPane().add(jButton2);
        jButton2.setBounds(0, 90, 160, 29);

        jButton3.setText("View Saved Numbers");
        jButton3.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton3ActionPerformed(evt);
            }
        });
        getContentPane().add(jButton3);
        jButton3.setBounds(0, 120, 160, 29);

        jScrollPane1.setHorizontalScrollBar(null);

        jTextArea1.setEditable(false);
        jTextArea1.setColumns(20);
        jTextArea1.setRows(5);
        jScrollPane1.setViewportView(jTextArea1);

        getContentPane().add(jScrollPane1);
        jScrollPane1.setBounds(10, 160, 160, 106);

        jLabel1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/resources/background.jpg"))); // NOI18N
        getContentPane().add(jLabel1);
        jLabel1.setBounds(0, 0, 430, 330);

        pack();
    }// </editor-fold>                        

    RandomNumber rndn;
    ClassificationCodes cc = new ClassificationCodes();
    //Writer writer;
    private final Font font1 = new Font("SansSerif", Font.BOLD, 20);

    //View Randomly Generated Number buttom
    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {                                         
        // TODO add your handling code here:
        jTextField1.setFont(font1);
        jTextField1.setText(rndn.getNumber());
        StringSelection stringSelection = new StringSelection (rndn.getCurrentNumber());
        Clipboard clpbrd = Toolkit.getDefaultToolkit ().getSystemClipboard();
        clpbrd.setContents (stringSelection, null);
        jTextArea1.setText(rndn.getCurrentNumber() + " added to clipboard");

    }                                        

    //save number button
    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {                                         
        // TODO add your handling code here:
        rndn.removeNumber();
        StringBuilder sb = new StringBuilder();
        for (String s : rndn.getUsedNumbers()) {
            sb.append(s).append(",");      
        } 
        try (Writer writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream("used_number_data.txt"), "utf-8"))) {
            writer.write(sb.toString());
        } catch (IOException ex) {
            Logger.getLogger(MainForm.class.getName()).log(Level.SEVERE, null, ex);
        }

        StringSelection stringSelection = new StringSelection (rndn.getCurrentNumber());
        Clipboard clpbrd = Toolkit.getDefaultToolkit ().getSystemClipboard();
        clpbrd.setContents (stringSelection, null);
        jTextArea1.setText(rndn.getCurrentNumber() + " added to clipboard");

    }                                        

    //view notes
    private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {                                         
        // TODO add your handling code here:
        jTextField1.setFont(font1);
        StringBuilder sb = new StringBuilder();
        for (String s : rndn.getUsedNumbers()) {
            sb.append(s).append("\n");      
        } 
        jTextArea1.setText(sb.toString());
    }                                        

    private void jComboBox1ActionPerformed(java.awt.event.ActionEvent evt) {                                           
        // TODO add your handling code here:
        repaint();
    }                                          

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        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 | InstantiationException | IllegalAccessException | javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(MainForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    new MainForm().setVisible(true);
                } catch (FileNotFoundException ex) {
                    Logger.getLogger(MainForm.class.getName()).log(Level.SEVERE, null, ex);
                } catch (IOException ex) {
                    Logger.getLogger(MainForm.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        });
    }

    // Variables declaration - do not modify                     
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private javax.swing.JButton jButton3;
    private javax.swing.JComboBox jComboBox1;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTextArea jTextArea1;
    private javax.swing.JTextField jTextField1;
    // End of variables declaration                   

    private void setIcon() {
        setIconImage(Toolkit.getDefaultToolkit().getImage(getClass().getResource("/resources/icon.png")));
    }

    private void popluteComboBox(){
//        for(Object s: cc.getCodes()){
//            jComboBox1.addItem(s);
//        }
         //jComboBox1.setModel(new DefaultComboBoxModel(cc.getCodes().toArray()));
        jComboBox1 = new JComboBox(cc.getCodes().toArray());

    }
}

TraceBack Error

Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
    at MainForm.popluteComboBox(MainForm.java:235)
    at MainForm.<init>(MainForm.java:35)
    at MainForm$5.run(MainForm.java:206)
    at java.awt.event.InvocationEvent.dispatch(InvocationEvent.java:311)
    at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:744)
    at java.awt.EventQueue.access$400(EventQueue.java:97)
    at java.awt.EventQueue$3.run(EventQueue.java:697)
    at java.awt.EventQueue$3.run(EventQueue.java:691)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:75)
    at java.awt.EventQueue.dispatchEvent(EventQueue.java:714)
    at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:201)
    at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:116)
    at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:105)
    at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:101)
    at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:93)
    at java.awt.EventDispatchThread.run(EventDispatchThread.java:82)

ClassificationCodes (my cc object)

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Arrays;
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 *
 * @author marcsantiago
 */
public class ClassificationCodes {
    private BufferedReader txtReader;
    private ArrayList<String> codes;

    ClassificationCodes() throws FileNotFoundException, IOException{
        this.txtReader = new BufferedReader(new InputStreamReader(ClassificationCodes.class.getResourceAsStream("/resources/stylecodes.txt"))); 
        try{
            codes = new ArrayList(Arrays.asList(txtReader.readLine().split(",")));
        }catch(IOException e){

        }
    }

    public ArrayList getCodes(){
        return codes;
    }
}

To be clear it is not the data I am passing in the exception is thrown even when I do things like this

for (int i = 0; i < 10; i++) {
            jComboBox1.addItem(i);
        }
Unihedron
  • 10,902
  • 13
  • 62
  • 72
reticentroot
  • 3,612
  • 2
  • 22
  • 39
  • 1
    1) See [What is a stack trace, and how can I use it to debug my application errors?](http://stackoverflow.com/q/3988788/418556) & [What is a Null Pointer Exception, and how do I fix it?](http://stackoverflow.com/q/218384/418556) 2) Always copy/paste error and exception output! – Andrew Thompson Jul 30 '15 at 01:37
  • 1
    As an aside, besides providing good functionality to *debug* exceptions in code, your IDE is not really realted to the immediate problem and should be left out of the tags. The [tag:netbeans] tag is for problems with the NetBeans IDE itself. – Andrew Thompson Jul 30 '15 at 01:39
  • My "guess" is `cc.getCodes()` is `null`, but you've not provided the code for that so it's just a guess – MadProgrammer Jul 30 '15 at 01:43
  • Added the traceback. I don't know why it's throwing a null exception when I use the for loop or jComboBox1.setModel(new DefaultComboBoxModel(cc.getCodes().toArray())); There is data there. When I use jComboBox1 = new JComboBox(cc.getCodes().toArray()); i can print out the data using getItemAt(). So i'm not passing in null – reticentroot Jul 30 '15 at 01:45
  • That stack trace does not seem to correspond to the code. For example `at MainForm.popluteComboBox(MainForm.java:235)` is a blank line (directly after the line you mentioned. While `at MainForm.(MainForm.java:35)` implies the called method must be `initComponents()` as opposed to `popluteComboBox()` which happens two code lines before it.. Please ensure the code and stack trace are from the exact same code. – Andrew Thompson Jul 30 '15 at 01:47
  • You're ignoring the potential exception which is been thrown by `codes = new ArrayList(Arrays.asList(txtReader.readLine().split(",")));`...I would suggest making sure that there is nothing going wrong here... – MadProgrammer Jul 30 '15 at 01:48
  • I have check it over and over. The data populates just fine. You can call cc.getCodes() and an arraylist is always returned. It is only in the context of the ComboBox that the exception is raised. This is not a duplicate, so please remove it so that other suggestions can be made. – reticentroot Jul 30 '15 at 01:52
  • @AndrewThompson Whenever I hit the run button, that's the only traceback I get. That's the only traceback there is. It only appears when I try and run the popluteComboBox() method. – reticentroot Jul 30 '15 at 01:58
  • Post the contents of the file and the `RandomNumber` class might help. Add a breakpoint in your code and start stepping through and inspecting what the variables actually are. Put some debug statements and inspect the state of the actual variables – MadProgrammer Jul 30 '15 at 02:00
  • The RandomNumber code works just fine, This software works except when the combox is implemented. If i remove the combobox all together, the code works just fine and the application runs. If i add a combobox and don't change it's data it works just fine. If i manually add the data into the model using the GUI it works just fine. Its whenever I try and programmatically add the data that it crashes. – reticentroot Jul 30 '15 at 02:03
  • 1
    @msanti Yes, but WE can't run your code, so it's impossible for use to determine what might be causing your problems, everything else is just guess work – MadProgrammer Jul 30 '15 at 02:04
  • 4
    You combobox is `null`, as you are calling `popluteComboBox` before `initComponents` ... – MadProgrammer Jul 30 '15 at 02:07
  • -_- alright let me change that and i'll get back to you guys – reticentroot Jul 30 '15 at 02:07
  • @MadProgrammer I was so frustrated I would have never looked there. Thanks! That was it. If you want to answer the question formally i'll accept it. – reticentroot Jul 30 '15 at 02:09

0 Answers0