为什么我在这一行得到NullPointerException?

时间:2018-06-14 11:40:10

标签: java swing nullpointerexception jtable

虽然我正在给出值,但我得到NullPointerException。我有DefaultTableModel名为model1。我想将第4列和第5列的值相乘并将其添加到第6列。我制作了三行。前两行中4,5的值相乘并添加到第6列,但第三行的值不会显示在列上并生成异常。

这是错误块 -

for(int i = 0; i <= model1.getRowCount();i++){
    Double d = Double.parseDouble((String) model1.getValueAt(i, 4));
    Double d2 = Double.parseDouble((String) model1.getValueAt(i, 5)); //exception
    Double d3 = d * d2;
    model1.setValueAt(d3, i, 6);
}

这是例外 -

Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
    at sun.misc.FloatingDecimal.readJavaFormatString(FloatingDecimal.java:1838)
    at sun.misc.FloatingDecimal.parseDouble(FloatingDecimal.java:110)
    at java.lang.Double.parseDouble(Double.java:538)
    at Busy.saver(Busy.java:246)
    at Busy.lambda$inventory$12(Busy.java:233)
    at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:2022)
    at javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.java:2348)
    at javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:402)
    at javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:259)
    at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(BasicButtonListener.java:252)
    at java.awt.Component.processMouseEvent(Component.java:6533)
    at javax.swing.JComponent.processMouseEvent(JComponent.java:3324)
    at java.awt.Component.processEvent(Component.java:6298)
    at java.awt.Container.processEvent(Container.java:2237)
    at java.awt.Component.dispatchEventImpl(Component.java:4889)
    at java.awt.Container.dispatchEventImpl(Container.java:2295)
    at java.awt.Component.dispatchEvent(Component.java:4711)
    at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4889)
    at java.awt.LightweightDispatcher.processMouseEvent(Container.java:4526)
    at java.awt.LightweightDispatcher.dispatchEvent(Container.java:4467)
    at java.awt.Container.dispatchEventImpl(Container.java:2281)
    at java.awt.Window.dispatchEventImpl(Window.java:2746)
    at java.awt.Component.dispatchEvent(Component.java:4711)
    at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:758)
    at java.awt.EventQueue.access$500(EventQueue.java:97)
    at java.awt.EventQueue$3.run(EventQueue.java:709)
    at java.awt.EventQueue$3.run(EventQueue.java:703)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:80)
    at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:90)
    at java.awt.EventQueue$4.run(EventQueue.java:731)
    at java.awt.EventQueue$4.run(EventQueue.java:729)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:80)
    at java.awt.EventQueue.dispatchEvent(EventQueue.java:728)
    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)
    BUILD SUCCESSFUL (total time: 48 seconds)

为什么我会收到此异常?

这是MCVE -

import java.awt.*;
import java.io.Serializable;
import javax.swing.*;
import javax.swing.table.*;
public class Mcve extends JPanel{
    String data[][] ={{""}};
    String row[] = {"#","Item Name","HSN/SAC","Description","Qty.","Rate","Price"};
    DefaultTableModel model = new DefaultTableModel(data, row);
    JTable table = new JTable(model);
    JScrollPane pane = new JScrollPane(table);

    public void mainPage() {
        Mcve obj = new Mcve();
        JFrame frame = new JFrame("MCVE");
        frame.setExtendedState(JFrame.MAXIMIZED_BOTH);
        frame.setDefaultCloseOperation(frame.EXIT_ON_CLOSE);
        JInternalFrame iframe = new JInternalFrame();
        JButton save , add;
        save = new JButton("Save");
        add = new JButton("Add Item");
        save.setSize(75,40);
        add.setSize(85,40);
        iframe.setTitle("Inventory");
        iframe.add(pane);
        iframe.add(save, BorderLayout.WEST);
        iframe.add(add, BorderLayout.SOUTH);
        frame.add(iframe);
        iframe.setClosable(true);
        save.setVisible(true);
        add.setVisible(true);
        iframe.setVisible(true);
        frame.setVisible(true);
        save.addActionListener((ActionEvent) ->{
            saver();
        });
        add.addActionListener((ActionEvent) -> {
            rowAdder();
        });
    }
    public void saver(){
        for(int i = 0; i<=model.getRowCount();i++){
            Double d= Double.parseDouble((String) model.getValueAt(i,4));
            Double d2= Double.parseDouble((String) model.getValueAt(i,5));
            Double d3=d*d2;
            model.setValueAt(d3,i,6);
        }
    }
    public void rowAdder(){
        String row[][] = {};
        model.addRow(row);
    }
    public static void main(String[] args) {
        Mcve obj = new Mcve();
        obj.mainPage();
    }
} 

3 个答案:

答案 0 :(得分:2)

列是零索引的。因此,第4列和第5列是索引3和4

如果第六列是结果的占位符,则可能为空,因此错误地调用model1.getValueAt(i, 5)会返回null,因为该单元格为空。

Double d = Double.parseDouble((String) model1.getValueAt(i, 3));
Double d2 = Double.parseDouble((String) model1.getValueAt(i, 4));
Double d3 = d * d2;
model1.setValueAt(d3, i, 5);

答案 1 :(得分:2)

只需使用Stacktrace和文档:

我们可以看到这是Double.parseDouble调用抛出异常的调用。

  

线程中的异常&#34; AWT-EventQueue-0&#34;显示java.lang.NullPointerException
  在
  sun.misc.FloatingDecimal.readJavaFormatString(FloatingDecimal.java:1838)
  at sun.misc.FloatingDecimal.parseDouble(FloatingDecimal.java:110)在
   java.lang.Double.parseDouble(Double.java:538)
  Busy.saver(Busy.java:246)

Double.parseDouble的文档告诉你:

  

抛出:
      - NullPointerException - 如果字符串为null

因此,您要将null值传递给Double.parseString

我的理由是你仍然在&#34;编辑&#34;当您单击按钮进行保存时,您将不会提交该值,因此模型仍会将单元格视为空(null)。您可以在saver方法的开头强制结束版本。

TableCellEditor editor = table.getCellEditor();
if (editor != null) {
    editor.stopCellEditing();
}

来自Guillaume answer

当然,如果单元格不是数字值(空数字或非数字),这不会阻止异常。所以解决方案是捕获每一行的异常。

for (int i = 0; i <= model.getRowCount(); i++) {
    try{
        Double d = Double.parseDouble((String) model.getValueAt(i, 4));
        Double d2 = Double.parseDouble((String) model.getValueAt(i, 5));
        Double d3 = d * d2;
        model.setValueAt(d3, i, 6);
    } catch (NullPointerException | NumberFormatException e){
        model.setValueAt("N/A", i, 6);
    }
}

然后,您可以检查vincrichaud answer以更正您将从正在使用的循环中获得的java.lang.ArrayIndexOutOfBoundsException

答案 2 :(得分:1)

for(int i = 0; i<=model1.getRowCount();i++)你会过多地循环一次。你需要去i<model1.getRowCount())

正如AxelH在评论中提到的,这不会解决您的NPE问题。但是,您的代码中仍然存在错误,只要您解决NPE就会导致问题。