我在我的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