用int row= jt.getSelectedRow();if(row!=-1)dtm.removeRow(row);就可以删除指定行了。
我给你个例子,你看了就明白了。
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;
public class G {
private Object[][] cells={{"some",0},{"any",1},{"even",2},
{"text",0},{"and",1},{"text",2}};
private String[] columnNames={"Column 1","Column 2"};
JFrame jf;
JButton jb;
JTable jt;
JPanel jp,jp1;
JScrollPane scrollPane;
DefaultTableModel dtm;
G(){
jf=new JFrame("JTable");
jb=new JButton("删除");
jb.addActionListener(new AddActionListener());
dtm = new DefaultTableModel(cells,columnNames);
jt = new JTable(dtm);
jt.setPreferredScrollableViewportSize(new Dimension(300,120));
scrollPane = new JScrollPane(jt);
jp=new JPanel();
jp1=new JPanel();
jp1.add(jb);
jp.setLayout(new GridLayout(2,1));
jp.add(scrollPane);
jp.add(jp1);
jf.add(jp,BorderLayout.CENTER);
jf.setSize(400,400);
jf.setVisible(true);
jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
class AddActionListener implements ActionListener{
public void actionPerformed(ActionEvent ae) {
if(ae.getSource()==jb){
int row= jt.getSelectedRow(); //这句选择要删除的行
if(row!=-1) //这句判断是否有选中的行
dtm.removeRow(row); //这句删除指定行
}
}
}
public static void main(String[] args) {
new G();
}
}