JComboBox不能正常工作(我没有传入空数据)

时间:2015-07-30 01:30:44

标签: java swing arraylist nullpointerexception jcombobox

我正在尝试基于资源文件创建一个ComboBox。我没有问题将资源文件转换为ArrayList。我希望使用ArrayList来填充ComboBox,我使用for循环创建并抛出此异常Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException我试图像这样创建组合框jComboBox1.setModel(new DefaultComboBoxModel(cc.getCodes().toArray()));同样的异常被扔了。现在我使用jComboBox1 = new JComboBox(cc.getCodes().toArray());并且没有抛出任何异常,但组合框仍为空。我需要一个能够将物品从中取出或随时添加到其中的组合框。有人可以帮忙吗?源代码如下, 我关心的方法是源的最末端的 popluteComboBox()方法。我在Form的构造函数中调用该方法。

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错误

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 (我的cc对象)

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

要清楚的是,即使我做这样的事情,也不会抛出我在异常中传递的数据

for (int i = 0; i < 10; i++) {
            jComboBox1.addItem(i);
        }

0 个答案:

没有答案