qxnlyf
2021-06-26 17:02
采纳率: 100%
浏览 28
已采纳

java如何解决空指针异常

源代码是这个样子的

​
package com.booking.view;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.Point;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Vector;

import javax.swing.AbstractButton;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JRootPane;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.ListSelectionModel;
import javax.swing.RowSorter;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableCellRenderer;
import javax.swing.table.TableModel;
import javax.swing.table.TableRowSorter;

import com.booking.constants.Constants;
import com.booking.entity.Flight;
import com.booking.entity.Ticket;
import com.booking.model.Booking;
import com.booking.util.CalendarPanel;
import com.booking.util.ViewBackgroundUtil;

import sun.swing.DefaultLookup;

public class Flightview extends BaseFrame implements ActionListener{
/**
 * @Fields serialVersionUID
 */
	private static final long serialVersionUID=1;
private static final String oldIdNumber = null;
private static final AbstractButton IDNumber = null;
private JFrame frame = null;
private JTextField flightTextField;
private Ticket ticket;
private JButton choose;

	/**
	 * @Fields backBtn:返回
	 */
	private JButton backBtn;
	/**
	 * @Fields refund:退票k
	 */
	private JButton refund;
	/**
	 * @Fields alter:改签
	 */
	private JButton alter;
	/**
	 * @Fields orderNoOrIdentityNo :前一窗口传递的搜索条件
	 */
	private String orderNoOrIdentityNo;
	/**
	 * @Fields date : 出行日期
	 */
	private JTextField startDate;
	public Boolean isSelect=false;
	private JTextField textField;
	public Flightview(String orderNoOrIdentityNo) {
		this.orderNoOrIdentityNo=orderNoOrIdentityNo;
		init();
	}
	public Flightview(JTextField textField, RefundOrAlterView refundOrAlterView) {
		 this.textField = textField;
		 this.orderNoOrIdentityNo=textField.getText();
	      init();
	}
	public Flightview(JFrame frame, JTextField flightTextField, Ticket ticket) {
	      super();
	      this.frame = frame;
	      this.flightTextField = flightTextField;
	      this.ticket = ticket;
	      this.init();
	  }
	private void init() {
		ViewBackgroundUtil.setBG(this, "img/bg2.jpg");
		JLabel title =new JLabel("购票订单列表");
		title.setBounds(60,20,700,30);
		Vector columnNames=new Vector();
		columnNames.add("订单号");
		columnNames.add("始发地");
		columnNames.add("目的地");
		columnNames.add("乘机人");
		columnNames.add("身份证号");
		columnNames.add("日期");
		DefaultTableModel tableModel=new DefaultTableModel(getTableData(),columnNames);		
		JTable table=new JTable(tableModel) {
			public Component prepareRenderer(TableCellRenderer renderer,int row,int column) {
			Component comp=super.prepareRenderer(renderer,row,column);
			Point p=getMousePosition();
			if(p!=null) {
				int rowUnderMouse=rowAtPoint(p);
				if(rowUnderMouse==row) {
					comp.setBackground( Color.ORANGE);
				}else {
					comp.setBackground(DefaultLookup.getColor(this, ui, "Table.alternateRowColor"));
				}
			}
			return comp;
			}
		};	
		RowSorter sorter = new TableRowSorter(tableModel);
		table.setRowSorter(sorter);				
		table.setRowHeight(23);
		table.setAutoscrolls(true);
		table.setFillsViewportHeight(true);
		table.setEnabled(false);
		JScrollPane scrollPane=new JScrollPane(table);
		scrollPane.setBounds(60,60,640,400);//创建显示表格的滚动面板
		backBtn=new CustomButton(100,500,CustomButton.LEFT);
		backBtn.setText("返回");
		backBtn.addActionListener(this);
		backBtn.setActionCommand("backToRefundOrAlterView");
		refund =new CustomButton(300,500,CustomButton.LEFT);
		refund.setText("退票");
		refund.addActionListener(this);
		refund.setActionCommand("refund");
		alter=new CustomButton(500,500,CustomButton.LEFT);
		alter.setText("改签");
		alter.addActionListener(this);
		alter.setActionCommand("alter");
		this.getContentPane().add(scrollPane,BorderLayout.NORTH);
		this.getContentPane().add(backBtn);
		this.getContentPane().add(refund);
		this.getContentPane().add(alter);	
		table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
		table.getTableHeader().setReorderingAllowed(false);	
		table.setRowSelectionAllowed(true);
		 List<String> orderList =  new ArrayList<>();
	    	table.addMouseListener(new MouseAdapter() {
	 private int rowUnderMouse = -1;
	public void mouseClicked(MouseEvent e) {
	   orderList.clear();
	  	int row =((JTable)e.getSource()).rowAtPoint(e.getPoint()); 
	 	if(row == -1) {
	  	return;
	   	}
		int numCols = table.getColumnCount();
	 	TableModel model = table.getModel();
		for (int i = 0; i < numCols; i++) {
			orderList.add(model.getValueAt(row, i).toString());
		}
			JTable table = (JTable)e.getSource();					
	   Point p = table.getMousePosition();
		    if(p != null){
		      rowUnderMouse = table.rowAtPoint(p);
		     if(rowUnderMouse >= 0){
	 for(int i=0;i<table.getColumnCount();i++){
		 table.prepareRenderer(table.getCellRenderer(rowUnderMouse,i),rowUnderMouse,i);
	  if(rowUnderMouse != 0){
	  table.prepareRenderer(table.getCellRenderer(rowUnderMouse-1,i),rowUnderMouse-1,i);
	       }
	       if(rowUnderMouse != table.getRowCount()-1){
        table.prepareRenderer(table.getCellRenderer(rowUnderMouse+1,i),rowUnderMouse+1,i);
	              }
             }
	   table.repaint(table.getVisibleRect());
      }
     }
	}
	});
	}	
	/**
	 * @Title: getTableData
	 * @Description: 获取table数据
	 * @return
	 */
@SuppressWarnings({ "rawtypes", "unchecked" })
      private Vector getTableData() {
		Vector data = new Vector();
		Booking bookingService = new Booking();
		Map<String, Object> resultMap = bookingService.readData(orderNoOrIdentityNo);
		List<Ticket> tickets = (List<Ticket>)resultMap.get(Constants.RESULT_KEY_DATA);
		if (tickets == null || tickets.isEmpty()) {
		return data;
		}
		String s=null;
		for (int i = 0; i < tickets.size(); i++) {
		Ticket t = tickets.get(i);
	    Vector vector = new Vector();
		vector.add(t.getOrderNo());
		vector.add(t.getStartAddress());
		vector.add(t.getEndAddress());
		vector.add(t.getUserName());
		vector.add(t.getIdentityNo());
		vector.add(t.getTravelDate());
		data.add(vector);
			}
		return data;
		}
@Override
public void actionPerformed(ActionEvent e) {
	String actionCommand=e.getActionCommand();
	switch(actionCommand) {
	case"backToRefundOrAlterView"://点击返回按钮
		Flightview.this.setVisible(false);
		break;
	case "refund":
	if (JOptionPane.showConfirmDialog(null, "退票将扣除票价的10%作为手续费,确认退票?", 
		"提示", JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION) {
			Booking bookService = new Booking();
			String resultCode =bookService.deleteOrderInfo(IDNumber.getText());
			IDNumber.setText(oldIdNumber);
			JOptionPane.showMessageDialog(null, "退票成功!",
				"退票结果", JOptionPane.INFORMATION_MESSAGE);
			refund=new JButton ();
			refund.setVisible(true);
				break;
				}
		case "alter":
		if (JOptionPane.showConfirmDialog(null, "改签将加收票价的10%作为手续费,确认?", 
		"提示", JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION) {
		startDate = new JTextField();
		startDate.setBounds(380, 320, 200, 33);
		CalendarPanel calendar = new CalendarPanel(startDate, "yyyy-MM-dd");
		String a=JOptionPane.showInputDialog("请输入更改的日期");		
		Booking bookService = new Booking();
		String resultCode =bookService.updateTravelDateInfo(IDNumber.getText(),a);
		alter=new JButton();
		alter.setVisible(true);
		break;
							}
						}
					}
}

​

然后系统报错像下面这样,我应该怎么改才会没有空指针异常?

Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
	at com.booking.view.Flightview.actionPerformed(Flightview.java:243)
	at javax.swing.AbstractButton.fireActionPerformed(Unknown Source)
	at javax.swing.AbstractButton$Handler.actionPerformed(Unknown Source)
	at javax.swing.DefaultButtonModel.fireActionPerformed(Unknown Source)
	at javax.swing.DefaultButtonModel.setPressed(Unknown Source)
	at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(Unknown Source)
	at java.awt.Component.processMouseEvent(Unknown Source)
	at javax.swing.JComponent.processMouseEvent(Unknown Source)
	at java.awt.Component.processEvent(Unknown Source)
	at java.awt.Container.processEvent(Unknown Source)
	at java.awt.Component.dispatchEventImpl(Unknown Source)
	at java.awt.Container.dispatchEventImpl(Unknown Source)
	at java.awt.Component.dispatchEvent(Unknown Source)
	at java.awt.LightweightDispatcher.retargetMouseEvent(Unknown Source)
	at java.awt.LightweightDispatcher.processMouseEvent(Unknown Source)
	at java.awt.LightweightDispatcher.dispatchEvent(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$500(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$JavaSecurityAccessImpl.doIntersectionPrivilege(Unknown Source)
	at java.security.ProtectionDomain$JavaSecurityAccessImpl.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$JavaSecurityAccessImpl.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)
  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • CSDN专家-sinjack 2021-06-26 17:17
    已采纳

    你找到报错的位置,跟你代码有关的地方。对象为空导致的。

    点赞 1 评论

相关推荐 更多相似问题