线程“AWT-EventQueue-0”中的异常java.lang.NullPointerException

时间:2015-01-10 12:53:04

标签: java exception

错误在于控制台:

Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
at Main.formLoad(Main.java:265)
at Main.access$0(Main.java:256)
at Main$1.windowActivated(Main.java:54)
at java.awt.AWTEventMulticaster.windowActivated(Unknown Source)
at java.awt.Window.processWindowEvent(Unknown Source)
at javax.swing.JFrame.processWindowEvent(Unknown Source)
at java.awt.Window.processEvent(Unknown Source)
at java.awt.Component.dispatchEventImpl(Unknown Source)
at java.awt.Container.dispatchEventImpl(Unknown Source)
at java.awt.Window.dispatchEventImpl(Unknown Source)
at java.awt.Component.dispatchEvent(Unknown Source)
at java.awt.KeyboardFocusManager.redispatchEvent(Unknown Source)
at java.awt.DefaultKeyboardFocusManager.typeAheadAssertions(Unknown Source)
at java.awt.DefaultKeyboardFocusManager.dispatchEvent(Unknown Source)
at java.awt.Component.dispatchEventImpl(Unknown Source)
at java.awt.Container.dispatchEventImpl(Unknown Source)
at java.awt.Window.dispatchEventImpl(Unknown Source)
at java.awt.Component.dispatchEvent(Unknown Source)
at java.awt.EventQueue.dispatchEventImpl(Unknown Source)
at java.awt.EventQueue.access$200(Unknown Source)
at java.awt.EventQueue$3.run(Unknown Source)
at java.awt.EventQueue$3.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
at java.awt.EventQueue$4.run(Unknown Source)
at java.awt.EventQueue$4.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
at java.awt.EventQueue.dispatchEvent(Unknown Source)
at java.awt.SentEvent.dispatch(Unknown Source)
at java.awt.DefaultKeyboardFocusManager$DefaultKeyboardFocusManagerSentEvent.dispatch(Unknown Source)
at java.awt.DefaultKeyboardFocusManager.sendMessage(Unknown Source)
at java.awt.DefaultKeyboardFocusManager.dispatchEvent(Unknown Source)
at java.awt.Component.dispatchEventImpl(Unknown Source)
at java.awt.Container.dispatchEventImpl(Unknown Source)
at java.awt.Window.dispatchEventImpl(Unknown Source)
at java.awt.Component.dispatchEvent(Unknown Source)
at java.awt.EventQueue.dispatchEventImpl(Unknown Source)
at java.awt.EventQueue.access$200(Unknown Source)
at java.awt.EventQueue$3.run(Unknown Source)
at java.awt.EventQueue$3.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
at java.awt.EventQueue$4.run(Unknown Source)
at java.awt.EventQueue$4.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
at java.awt.EventQueue.dispatchEvent(Unknown Source)
at java.awt.SequencedEvent.dispatch(Unknown Source)
at java.awt.EventQueue.dispatchEventImpl(Unknown Source)
at java.awt.EventQueue.access$200(Unknown Source)
at java.awt.EventQueue$3.run(Unknown Source)
at java.awt.EventQueue$3.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
at java.awt.EventQueue$4.run(Unknown Source)
at java.awt.EventQueue$4.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
at java.awt.EventQueue.dispatchEvent(Unknown Source)
at java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.run(Unknown Source)

我的主要课程是:

import java.io.*;
import java.util.ArrayList;
import javax.swing.JFileChooser;
import javax.swing.filechooser.FileNameExtensionFilter;

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * Main.java
 *
 * 
 */
/**
 *
 * @author ouzov
 */
@SuppressWarnings("serial")
public class Main extends javax.swing.JFrame implements Runnable {
    ArrayList<LBP> train;
    /** Creates new form Main */
    public Main() {
        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">//GEN-BEGIN:initComponents
    private void initComponents() {

        jButton1 = new javax.swing.JButton();
        jTextField1 = new javax.swing.JTextField();
        orjinal = new javax.swing.JLabel();
        sonuc1 = new javax.swing.JLabel();
        sonuc2 = new javax.swing.JLabel();
        sonuc3 = new javax.swing.JLabel();
        durum = new javax.swing.JLabel();
        dbCreator = new javax.swing.JButton();
        ongosterim = new javax.swing.JLabel();
        prNo = new javax.swing.JSpinner();
        prView = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setResizable(false);
        addWindowListener(new java.awt.event.WindowAdapter() {
            public void windowActivated(java.awt.event.WindowEvent evt) {
                formLoad(evt);
            }
        });

        jButton1.setText("Gozat");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        jTextField1.setEditable(false);

        sonuc1.setText("Sonuc1");

        sonuc2.setText("Sonuc2");

        sonuc3.setText("Sonuc3");

        durum.setText("jLabel1");

        dbCreator.setText("Veritabani Olustur");
        dbCreator.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                dbCreatorActionPerformed(evt);
            }
        });

        ongosterim.setText("jLabel1");

        prView.setText("Goster");
        prView.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                prViewActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(42, 42, 42)
                .addComponent(orjinal, javax.swing.GroupLayout.DEFAULT_SIZE, 86, Short.MAX_VALUE)
                .addGap(307, 307, 307))
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(sonuc3, javax.swing.GroupLayout.PREFERRED_SIZE, 350, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(316, Short.MAX_VALUE))
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(sonuc2, javax.swing.GroupLayout.DEFAULT_SIZE, 350, Short.MAX_VALUE)
                .addGap(202, 202, 202))
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(sonuc1, javax.swing.GroupLayout.DEFAULT_SIZE, 350, Short.MAX_VALUE)
                .addGap(79, 79, 79))
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(ongosterim)
                .addContainerGap(391, Short.MAX_VALUE))
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(dbCreator)
                        .addGap(165, 165, 165)
                        .addComponent(prNo, javax.swing.GroupLayout.DEFAULT_SIZE, 50, Short.MAX_VALUE))
                    .addComponent(jTextField1, javax.swing.GroupLayout.DEFAULT_SIZE, 336, Short.MAX_VALUE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                    .addComponent(jButton1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(prView, javax.swing.GroupLayout.DEFAULT_SIZE, 73, Short.MAX_VALUE))
                .addContainerGap())
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(durum)
                .addContainerGap(391, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jButton1))
                .addGap(12, 12, 12)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(orjinal)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(prView)
                        .addComponent(prNo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addComponent(dbCreator)))
                .addGap(15, 15, 15)
                .addComponent(ongosterim)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(sonuc1, javax.swing.GroupLayout.PREFERRED_SIZE, 35, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(sonuc2, javax.swing.GroupLayout.PREFERRED_SIZE, 31, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(sonuc3, javax.swing.GroupLayout.PREFERRED_SIZE, 32, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(32, 32, 32)
                .addComponent(durum)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
// TODO add your handling code here:
    int min;
    String[] sonuc={"","",""};
    JFileChooser file=new JFileChooser(".");
    FileNameExtensionFilter  filter=new FileNameExtensionFilter("Image files", "jpg","bmp","jpeg","png");
    file.setFileFilter(filter);
    int choice=file.showOpenDialog(this);
    if(choice==JFileChooser.APPROVE_OPTION)
    {
        File x=file.getSelectedFile();
        jTextField1.setText(x.getAbsolutePath());
        LBP f=new LBP(x);
        if(!train.isEmpty())
        {
            for(int i=0;i<3;i++)
            {
                Boolean var=false;
                min=train.get(0).distance(f);
                sonuc[i]=train.get(0).getFile();
                for(int j=1;j<train.size();j++)
                {
                    if(min>=train.get(j).distance(f))
                    {
                        for(int k=0;k<i;k++)
                        {
                            if(sonuc[k]==train.get(j).getFile())
                                var=true;
                        }

                        if(!var)
                        {
                            min=train.get(j).distance(f);
                            sonuc[i]=train.get(j).getFile();
                        }
                    }
                }
            }

          sonuc1.setText(sonuc[0]);  
          sonuc2.setText(sonuc[1]); 
          sonuc3.setText(sonuc[2]); 
        }
    }
}//GEN-LAST:event_jButton1ActionPerformed

    @Override
public void run()
{
    FileFilter filter=new FileFilter() {

            @Override
            public boolean accept(File pathname) {
            if(pathname.isFile())
            {
                String[] suffix={"jpg","jpeg","bmp","png"};
                String f=pathname.getAbsolutePath().toLowerCase();
                for(int i=0;i<suffix.length;i++)
                    if(f.endsWith("."+suffix[i]))
                    {
                        return true;
                    }
            }
            return false;
            }
        };

    File[] x=new File("Train\\").listFiles(filter);

    if(x!=null)
    {
    train=new ArrayList<LBP>();
    for(int i=0;i<x.length;i++)
    {
        durum.setText("Islenen dosya: "+x[i].getName());
        train.add(new LBP(x[i]));
    }
    durum.setText("Dosya Sayisi: "+x.length);   
    }

    try{
            File file=new File("Database.dat");
            file.delete();
            FileOutputStream f=new FileOutputStream("Database.dat");
            ObjectOutputStream obj=new ObjectOutputStream(f);
            obj.writeObject(train);
            obj.close();
        }catch(FileNotFoundException e)
        {}
        catch(IOException e)
        {}
}

private void formLoad(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formLoad
// TODO add your handling code here:

        try{
            InputStream f=new FileInputStream("Database.dat");
            InputStream buf=new BufferedInputStream(f);
            ObjectInput obj=new ObjectInputStream(buf);
            train=(ArrayList<LBP>)obj.readObject();
            obj.close();
            durum.setText("Veritabaninda "+train.size()+" adet resim kayitli...");
        }catch(FileNotFoundException e)
        {
            durum.setText("Veritabani bulunamadi...");
        }
        catch(ClassNotFoundException e)
        {

        }
        catch(IOException e)
        {
            e.printStackTrace();
            durum.setText("Veritabani okunurken hata olustu...");
        }

}//GEN-LAST:event_formLoad

private void dbCreatorActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_dbCreatorActionPerformed
// TODO add your handling code here:
    Thread thCreator=new Thread(this);
    thCreator.start();
}//GEN-LAST:event_dbCreatorActionPerformed

private void prViewActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_prViewActionPerformed
// TODO add your handling code here:
   Integer x=(Integer)prNo.getValue();
   if(train!=null && x>=0 && train.size()>=x)
       ongosterim.setText(train.get(x).getFile());
}//GEN-LAST:event_prViewActionPerformed

    /**
     * @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 ex) {
            java.util.logging.Logger.getLogger(Main.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(Main.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(Main.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(Main.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                new Main().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton dbCreator;
    private javax.swing.JLabel durum;
    private javax.swing.JButton jButton1;
    private javax.swing.JTextField jTextField1;
    private javax.swing.JLabel ongosterim;
    private javax.swing.JLabel orjinal;
    private javax.swing.JSpinner prNo;
    private javax.swing.JButton prView;
    private javax.swing.JLabel sonuc1;
    private javax.swing.JLabel sonuc2;
    private javax.swing.JLabel sonuc3;
    // End of variables declaration//GEN-END:variables
}

我的另一课是:

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.io.Serializable;
import javax.imageio.ImageIO;
/**
 *
 * @author ouzov
 */

@SuppressWarnings("serial")
public class LBP implements Serializable{
    private int[] histogram;
    private String file;

    public LBP(File file)
    {
        histogram=new int[0x100];
        try{
        BufferedImage image=ImageIO.read(file);
        this.file=file.getAbsolutePath();
        calcHist(image);
        }catch(IOException e)
        {}

    }

    public String getFile()
    {
        return file;
    }

    private void calcHist(BufferedImage image)
    {
        int[][] moves={{-1,-1},{0,-1},{1,-1},{1,0},{1,1},{0,1},{-1,1},{-1,0}};

        for(int i=1;i<image.getHeight()-1;i++)
            for(int j=1;j<image.getWidth()-1;j++)
            {
                String bin="";
                for(int k=0;k<8;k++)
                {
                    if(image.getRGB(j, i)>image.getRGB(j+moves[k][1],i+moves[k][0]))
                    {
                        bin+="1";
                    }else{
                        bin+="0";
                    }
                }

               if(chgBin(bin)<=2)
               {
                   histogram[bin2dec(bin)]++;
               }else{
                   histogram[0xAA]++;
               }

            }


    }

    private int bin2dec(String bin)
    {
    int numBits = bin.length();
    int power = numBits - 1;
    int sum = 0;

    for( int i=0; i<numBits; i++ )
    {
    int bit = Integer.parseInt( bin.substring( i, i+1 ) );
    int term = (int)(bit * Math.pow( 2, power ));
    sum += term;
    power--;
    }
    return sum;
    }

    private int chgBin(String str)
    {
        int x=0;
        char tmp=str.charAt(0);
        for(int i=1;i<str.length();i++)
            if(tmp!=str.charAt(i))
            {
                x++;
                tmp=str.charAt(i);
            }

        return x;
    }

    public int[] getHistogram()
    {
        return this.histogram;
    }

    public int distance(LBP hist)
    {
        int[] histogram2=hist.getHistogram();
        int tmp=0;
        for(int i=0;i<histogram.length;i++)
        {
            tmp+=Math.abs(histogram[i]-histogram2[i]);
        }
        return tmp;
    }

}

错误

at Main.formLoad(Main.java:265) 

在代码中显示此行:

 durum.setText("Veritabaninda "+train.size()+" adet resim kayitli...");

另一个是

at Main.access$0(Main.java:256)

private void formLoad(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formLoad

另一个是

at Main$1.windowActivated(Main.java:54)

几个小时,我想弄明白但是我失败了。我希望我能在这里得到帮助。

  formLoad(evt);

1 个答案:

答案 0 :(得分:0)

这是因为durum中访问的Main.java:256变量未在Main.java:331行(或附近)中初始化

private javax.swing.JLabel durum;

应该是

private javax.swing.JLabel durum = new javax.swing.JLabel();

或类似的东西