如何在 Java 中从 JTable 中删除选定的行?
awtjavaobject oriented programmingprogrammingswing
JTable 是 JComponent 类的子类,用于显示复杂的数据结构。JTable 组件可以遵循 模型视图控制器 (MVC) 设计模式,以 行和列 显示数据。JTable 可以生成 TableModelListener、TableColumnModelListener、ListSelectionListener、CellEditorListener 和 RowSorterListener 接口。我们可以使用 DefaultTableModel 类的 removeRow() 方法从 JTable 中删除 选定的行。
语法
public void removeRow(int row)
示例
import java.awt.*; import java.awt.event.*; import javax.swing.*; import javax.swing.table.*; public class RemoveSelectedRowTest extends JFrame { private JTable table; private DefaultTableModel model; private Object[][] data; private String[] columnNames; private JButton button; public RemoveSelectedRowTest() { setTitle("RemoveSelectedRow Test"); data = new Object[][] {{"101", "Ramesh"}, {"102", "Adithya"}, {"103", "Jai"}, {"104", "Sai"}}; columnNames = new String[] {"ID", "Name"}; model = new DefaultTableModel(data, columnNames); table = new JTable(model); table.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION); button = new JButton("Remove"); button.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent ae) { // check for selected row first if(table.getSelectedRow() != -1) { // remove selected row from the model model.removeRow(table.getSelectedRow()); JOptionPane.showMessageDialog(null, "Selected row deleted successfully"); } } }); add(new JScrollPane(table), BorderLayout.CENTER); add(button, BorderLayout.SOUTH); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setSize(400, 300); setLocationRelativeTo(null); setVisible(true); } public static void main(String args[]) { new RemoveSelectedRowTest(); } }