我在我的GUI应用程序中制作了JTable
,我想使用添加并删除已创建的按钮来添加行并将行删除,问题是删除我想要的行时所选的行索引,但在调用getSelectedRow()
方法时我得到了NullPointerException
。我试图谷歌它,并没有发现我的问题答案也试图读取Java文档,但我发现这种方法不会抛出通常的例外。从JTable中删除行时出现问题
代码:
// creating the table
JTable table = new JTable(model);
model.addColumn("NO.");
model.addColumn("Name");
model.addColumn("Status");
table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
table.setRowSelectionAllowed(true);
table.setShowGrid(false);
table.getColumnModel().getColumn(0).setPreferredWidth(28);
table.getColumnModel().getColumn(1).setPreferredWidth(222);
table.getColumnModel().getColumn(2).setPreferredWidth(100);
table.setBackground(color);
table.setPreferredScrollableViewportSize(new Dimension(350,250));
table.setFillsViewportHeight(true);
scroll = new JScrollPane(table);
center.add(scroll);
// adding records to it
public class AddEvent implements ActionListener{
public void actionPerformed (ActionEvent event){
String text = write.getText();
if (!text.equals("") && !text.contains(" ")){
String view = "http://www." + text;
write.setText(null);
model.addRow(new Object[]{model.getRowCount()+1, view,"Active"});
}
}
}
// to remove the selected row
public class RemoveEvent implements ActionListener{
public void actionPerformed (ActionEvent event){
int index = table.getSelectedRow(); // it throws the exception here
table.clearSelection();
System.out.println(index);
if(index != -1){
table.remove(index);
}
}
}
1)为了更好地帮助越早,张贴[SSCCE](http://sscce.org/)。 2)最好更改'TableModel'。独自离开桌子。 – 2013-05-10 22:00:37