我创建了一个包含3列的JTable,并在前2行中插入了一个值。当我选择第一行或第二行并单击“ GetData”按钮时,所选行中的数据将被打印在控制台上,但是!如果我选择其中没有数据的行,则代码dataString = dataObject.toString();
的这一行上会出现NullPointerException。
我插入了if else语句来检查dataString或dataObject是否包含null或“”值
import java.awt.FlowLayout;
import java.util.Scanner;
import javax.swing.*;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.table.*;
import java.awt.*;
import java.awt.event.*;
import java.util.*;
public class JayTable extends JFrame
{
DefaultTableModel model;
JTable table;
String col[] = {"Name","Address","Gender"};
public static void main(String args[])
{
new JayTable().start();
}
public void start()
{
model = new DefaultTableModel(col,50);
table=new JTable(model)
{
@Override public boolean isCellEditable(int arg0, int arg1)
{
return false;
}
};
table.getColumnSelectionAllowed();
JScrollPane pane = new JScrollPane(table);
JButton button = new JButton("GetData");
table.setValueAt("Ritchie Rich",0,0);
table.setValueAt("The Mansion",0,1);
table.setValueAt("Male",0,2);
table.setValueAt("Flintstone", 1, 0);
table.setValueAt("Rocky Road", 1, 1);
table.setValueAt("Unknown", 1, 2);
add(pane);
add(button);
button.setEnabled(false);
ListSelectionModel listSelectionModel = table.getSelectionModel();
listSelectionModel.addListSelectionListener(new ListSelectionListener()
{
public void valueChanged(ListSelectionEvent e)
{
ListSelectionModel lsm = (ListSelectionModel)e.getSource();
button.setEnabled(!lsm.isSelectionEmpty());
}
});
button.addActionListener(e ->
{
int row = table.getSelectedRow();
int column;
Object dataObject = null;
String dataString = "";
for(column = 0 ; column < table.getColumnCount(); column++)
{
dataObject = table.getValueAt(row, column);
dataString = dataObject.toString();
if(dataObject == null || dataObject.equals("") || dataString ==null || dataString.equals("") )
System.out.println("No value");
else
System.out.print(dataString+", ");
}
System.out.println();
});
setSize(500,400);
setLayout(new FlowLayout());
setDefaultCloseOperation(EXIT_ON_CLOSE);
setLocationRelativeTo(null);
pack();
setVisible(true);
}
}
最佳答案
您的空支票为时已晚。更改为
dataObject = table.getValueAt(row, column);
if(dataObject == null || "".equals(dataObject)) {
System.out.println("No value");
} else {
dataString = dataObject.toString();
if(dataString ==null || "".equals(dataString) )
System.out.println("No value");
else
System.out.print(dataString+", ");
}