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);
}