0

我对这个优越的网站感到非常惊讶!

我的目标是获取一个 .txt 文件,将其读入,根据选择的“窗口大小”(多少个字符,由 jcombobox 选择)将其切割成单个字符串,然后按频率列出。通过调试,它会在注释被标记的地方停止。我无法消除那些抛出的异常:

Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
    at xxxx.Babbles_GUI.windowSize(Babbles_GUI.java:247)    at
xxxx.Babbles_GUI.actionPerformed(Babbles_GUI.java:203)  at
javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:2028)
    at
javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.java:2351)
    at
javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:387)
    at
javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:242)
    at
javax.swing.plaf.basic.BasicButtonListener.mouseReleased(BasicButtonListener.java:236)
    at java.awt.Component.processMouseEvent(Component.java:6375)    at
javax.swing.JComponent.processMouseEvent(JComponent.java:3267)  at
java.awt.Component.processEvent(Component.java:6140)    at
java.awt.Container.processEvent(Container.java:2083)    at
java.awt.Component.dispatchEventImpl(Component.java:4737)   at
java.awt.Container.dispatchEventImpl(Container.java:2141)   at
java.awt.Component.dispatchEvent(Component.java:4565)   at
java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4619)
    at
java.awt.LightweightDispatcher.processMouseEvent(Container.java:4280)
    at java.awt.LightweightDispatcher.dispatchEvent(Container.java:4210)
    at java.awt.Container.dispatchEventImpl(Container.java:2127)    at
java.awt.Window.dispatchEventImpl(Window.java:2482)     at
java.awt.Component.dispatchEvent(Component.java:4565)   at
java.awt.EventQueue.dispatchEventImpl(EventQueue.java:684)  at
java.awt.EventQueue.access$000(EventQueue.java:85)  at
java.awt.EventQueue$1.run(EventQueue.java:643)  at
java.awt.EventQueue$1.run(EventQueue.java:641)  at
java.security.AccessController.doPrivileged(Native Method)  at
java.security.AccessControlContext$1.doIntersectionPrivilege(AccessControlContext.java:87)
    at
java.security.AccessControlContext$1.doIntersectionPrivilege(AccessControlContext.java:98)
    at java.awt.EventQueue$2.run(EventQueue.java:657)   at
java.awt.EventQueue$2.run(EventQueue.java:655)  at
java.security.AccessController.doPrivileged(Native Method)  at
java.security.AccessControlContext$1.doIntersectionPrivilege(AccessControlContext.java:87)
    at java.awt.EventQueue.dispatchEvent(EventQueue.java:654)   at
java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:296)
    at
java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:211)
    at
java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:201)
    at
java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:196)
    at
java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:188)
    at java.awt.EventDispatchThread.run(EventDispatchThread.java:122)

代码

public class Analysis {

    /**
     * @param file
     */
    public static void analyze(File file, int windowSize) {
        ArrayList<String> splittedText = new ArrayList<String>();
        System.out.println(windowSize);

        StringBuffer buf = new StringBuffer();
        if (file.exists()) {
            try {
                FileInputStream fis = new FileInputStream(file);
                InputStreamReader isr = new InputStreamReader(fis,
                        Charset.forName("UTF-8"));
                BufferedReader reader = new BufferedReader(isr);
                String line = "";
                while ((line = reader.readLine()) != null) {
                    buf.append(line);
                    splittedText.add(line);
                }
                reader.close();
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        String wholeString = buf.toString();

        // for (int i = 0; i < wholeString.length(); i += (Babbles_GUI
        // .WindowSize())) {
        // splittedText.add(wholeString.substring(
        // i,
        // Math.min(i + (Babbles_GUI.WindowSize()),
        // wholeString.length())));
        // }

//      for (int i = 0; (i < wholeString.length()-(Babbles_GUI.WindowSize())); i += Babbles_GUI.WindowSize()) {
//          splittedText.add(wholeString.substring(i, Math.min(Babbles_GUI.WindowSize()+i, wholeString.length())));
//      }

        for(int i = 0; i<wholeString.length()-(windowSize); i++){
            splittedText.add(wholeString.substring(i, i+windowSize));
        }
        System.out.println("error");

        Set<String> unique = new HashSet<String>(splittedText);
        for (String key : unique) {
            Babbles_GUI.txtAnalysis.append(Collections.frequency(splittedText,
                    key) + "x  " + key + "\t" + "\t");

        }
        Babbles_GUI.txtLog.append("Text analyzed with WindowSize "
                + windowSize + "\n");

    }
}

Babbles_GUI

public class Babbles_GUI extends JFrame implements ActionListener {

    private static final long serialVersionUID = 1L;
    JFileChooser fc1;
    JButton btnFileCh;
    JButton btnOutput;
    JLabel lblBtnLabel;
    static JTextArea txtLog;
    static JTextArea txtOrig;
    static JTextArea txtAnalysis;
    JTextArea txtGenerated;
    static JComboBox cbxWindowSize;
    BorderLayout borderlayout;
    JScrollPane ScrLog;
    private JPanel pnWest;
    private JPanel pnEast;
    private JPanel pnNorth;
    private JPanel pnCenter;
    private JPanel pnSouth;

    static int numberofchars;

    public Babbles_GUI(String title) {

        this.setTitle(title);
        this.setSize(1200, 2400);
        this.createUI();
        this.setVisible(true);
        this.setResizable(false);
        this.pack();
        this.setLocation(
                (Toolkit.getDefaultToolkit().getScreenSize().width - this
                        .getSize().width) / 2, (Toolkit.getDefaultToolkit()
                        .getScreenSize().height - this.getSize().height) / 2);

        addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent e) {
                System.exit(0);
            }
        });

    }

    /**
     * 
     */
    private void createUI() {

        btnFileCh = new JButton("Open...");
        // btnFileCh.setForeground(Color.BLACK);
        btnFileCh.setFont(new Font("Monospaced", Font.PLAIN, 14));
        btnFileCh.setPreferredSize(new Dimension(100, 20));
        btnFileCh.addActionListener(this);

        lblBtnLabel = new JLabel("Number of letters to shuffle: ");
        lblBtnLabel.setFont(new Font("Monospaced", Font.BOLD, 14));
        lblBtnLabel.setForeground(Color.WHITE);

        txtLog = new JTextArea();
        txtLog.setBackground(getBackground());
        txtLog.setBackground(Color.BLACK);
        txtLog.setForeground(Color.WHITE);
        txtLog.setWrapStyleWord(true);
        txtLog.setLineWrap(true);
        txtLog.setFont(new Font("Monospaced", Font.PLAIN, 13));
        JScrollPane spTxtlog = new JScrollPane(txtLog);
        spTxtlog.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_NEVER);
        spTxtlog.setBorder(BorderFactory.createMatteBorder(5, 0, 0, 0,
                Color.RED));

        txtOrig = new JTextArea();
        txtOrig.setEditable(false);
        txtOrig.setWrapStyleWord(true);
        txtOrig.setLineWrap(true);
        txtOrig.setBackground(Color.BLACK);
        txtOrig.setForeground(Color.WHITE);
        txtOrig.setFont(new Font("Monospaced", Font.PLAIN, 15));
        txtOrig.setBorder(BorderFactory.createMatteBorder(10, 0, 0, 0,
                Color.BLUE));

        txtAnalysis = new JTextArea();
        txtAnalysis.setEditable(false);
        txtAnalysis.setWrapStyleWord(true);
        txtAnalysis.setLineWrap(true);
        txtAnalysis.setBackground(Color.BLACK);
        txtAnalysis.setForeground(Color.WHITE);
        txtAnalysis.setFont(new Font("Monospaced", Font.PLAIN, 15));
        txtAnalysis.setBorder(new EmptyBorder(20, 0, 0, 20));
        JScrollPane spTxtAn = new JScrollPane(txtAnalysis);
        spTxtAn.setBorder(BorderFactory.createMatteBorder(10, 0, 0, 0,
                Color.GREEN));

        btnOutput = new JButton("Generate");
        btnOutput.addActionListener(this);
        btnOutput.setForeground(Color.BLACK);
        btnOutput.setFont(new Font("Monospaced", Font.PLAIN, 14));
        btnOutput.setPreferredSize(new Dimension(100, 20));

        String[] item = { "WindowSize 1", "WindowSize 2", "WindowSize 3",
                "WindowSize 4", "WindowSize 5", "WindowSize 6", "WindowSize 7" };
        JComboBox cbxWindowSize = new JComboBox(item);
        cbxWindowSize.setFont(new Font("Monospaced", Font.PLAIN, 14));
        cbxWindowSize.setPreferredSize(new Dimension(200, 20));
        Box bxLeft = Box.createHorizontalBox();
        bxLeft.add(lblBtnLabel);
        bxLeft.add(cbxWindowSize);

        Box bxCenter = Box.createHorizontalBox();
        bxCenter.add(btnFileCh);

        Box bxRight = Box.createHorizontalBox();
        bxRight.add(btnOutput);

        txtGenerated = new JTextArea();
        txtGenerated.setEditable(false);
        txtGenerated.setBackground(Color.BLACK);
        txtGenerated.setForeground(Color.WHITE);
        txtGenerated.setBorder(BorderFactory.createMatteBorder(10, 0, 0, 0,
                Color.YELLOW));

        pnWest = new JPanel();
        pnEast = new JPanel();
        pnNorth = new JPanel();
        pnCenter = new JPanel();
        pnSouth = new JPanel();

        pnWest.setLayout(new BorderLayout());
        pnWest.setBorder(new EmptyBorder(0, 0, 0, 10));
        pnWest.setBackground(Color.BLACK);
        pnEast.setLayout(new BorderLayout());
        pnEast.setBorder(new EmptyBorder(0, 10, 0, 0));
        pnEast.setBackground(Color.BLACK);
        pnNorth.setLayout(new FlowLayout(FlowLayout.LEFT));
        pnNorth.setBackground(Color.BLACK);
        pnCenter.setLayout(new BorderLayout());
        pnCenter.setBackground(Color.BLACK);
        pnSouth.setLayout(new BorderLayout());

        try {
            this.fc1 = new JFileChooser();
            fc1.setFileFilter(new FileNameExtensionFilter(null, "txt"));

        } catch (IllegalArgumentException e) {
            txtOrig.append("");
            txtLog.append("File format must be .txt" + "\n");

        }
        pnNorth.add(bxLeft);
        pnNorth.add(bxCenter);
        pnNorth.add(bxRight);

        pnSouth.add(spTxtlog, BorderLayout.SOUTH);

        pnWest.add(txtOrig, BorderLayout.CENTER);
        pnWest.setPreferredSize(new Dimension(400, 700));

        pnCenter.add(spTxtAn, BorderLayout.CENTER);
        pnCenter.setPreferredSize(new Dimension(400, 700));

        pnEast.add(txtGenerated, BorderLayout.CENTER);
        pnEast.setPreferredSize(new Dimension(400, 700));

        borderlayout = new BorderLayout();
        borderlayout.setHgap(30);
        borderlayout.setVgap(3);
        setBackground(Color.BLACK);

        getContentPane().setLayout(borderlayout);
        getContentPane().add(pnEast, BorderLayout.EAST);
        getContentPane().add(pnWest, BorderLayout.WEST);
        getContentPane().add(pnNorth, BorderLayout.NORTH);
        getContentPane().add(pnCenter, BorderLayout.CENTER);
        getContentPane().add(pnSouth, BorderLayout.SOUTH);

    }

    @Override
    public void actionPerformed(ActionEvent e) {

        if (e.getSource() == btnFileCh) {
            int returnVal = fc1.showOpenDialog(Babbles_GUI.this);
            if (returnVal == JFileChooser.APPROVE_OPTION) {
                File file = fc1.getSelectedFile();
                txtLog.append(file.getName() + " opened" + "\n");
                printOrigFile(file);
                //DEBUG-STOP**********************************
                Analysis.analyze(file, windowSize());
            } else {
                txtLog.append("Open command cancelled by user" + "\n");
            }
            txtLog.setCaretPosition(txtLog.getDocument().getLength());
        }

    }

    public static void main(String[] args) {
        new Babbles_GUI("Babbles Exercise David Huser");

    }

    /**
     * @param file
     * @return
     */
    public String printOrigFile(File file) {

        StringBuffer buf = new StringBuffer();
        if (file.exists()) {
            try {
                FileInputStream fis = new FileInputStream(file);
                InputStreamReader isr = new InputStreamReader(fis,
                        Charset.forName("UTF-8"));
                BufferedReader reader = new BufferedReader(isr);
                String line = "";
                while ((line = reader.readLine()) != null) {
                    buf.append(line + "\n");
                }
                reader.close();
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        txtOrig.setText(buf.toString());
        return (buf.toString());
    }

    public int windowSize() {
        if (cbxWindowSize.getSelectedItem().equals("WindowSize 1")) {
            numberofchars = 1;
        } else if (cbxWindowSize.getSelectedItem().equals("WindowSize 2")) {
            numberofchars = 2;
        } else if (cbxWindowSize.getSelectedItem().equals("WindowSize 3")) {
            numberofchars = 3;
        } else if (cbxWindowSize.getSelectedItem().equals("WindowSize 4")) {
            numberofchars = 4;
        } else if (cbxWindowSize.getSelectedItem().equals("WindowSize 5")) {
            numberofchars = 5;
        } else if (cbxWindowSize.getSelectedItem().equals("WindowSize 6")) {
            numberofchars = 6;
        } else if (cbxWindowSize.getSelectedItem().equals("WindowSize 7")) {
            numberofchars = 7;
        }
        return numberofchars;
    }

}
4

1 回答 1

2

您有一个在 中为 null 的对象windowSize()。你确定cbxWindowSize是初始化?

另一种可能性是没有选定的项目。getSelectedItem()在这种情况下将返回 null。您需要检查这一点,而不是立即调用equals()结果。

编辑:

String[] item = { "WindowSize 1", "WindowSize 2", "WindowSize 3",
            "WindowSize 4", "WindowSize 5", "WindowSize 6", "WindowSize 7" };
JComboBox cbxWindowSize = new JComboBox(item);

这定义了一个新的局部变量并对其进行初始化。局部变量隐藏了同名的类变量。从行首删除JComboBox

于 2012-04-23T15:28:53.353 回答