要从JTable中删除选定的行,您可以使用以下步骤:
int[] selectedRows = jTable.getSelectedRows();
DefaultTableModel tableModel = (DefaultTableModel) jTable.getModel();
for (int i = selectedRows.length - 1; i >= 0; i--) {
tableModel.removeRow(selectedRows[i]);
}
完整的代码示例如下:
import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import java.awt.*;
public class JTableDeleteRowExample {
public static void main(String[] args) {
JFrame frame = new JFrame("JTable Delete Row Example");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(600, 400);
DefaultTableModel tableModel = new DefaultTableModel();
JTable jTable = new JTable(tableModel);
JScrollPane scrollPane = new JScrollPane(jTable);
frame.add(scrollPane, BorderLayout.CENTER);
JButton deleteButton = new JButton("Delete Selected Rows");
deleteButton.addActionListener(e -> {
int[] selectedRows = jTable.getSelectedRows();
for (int i = selectedRows.length - 1; i >= 0; i--) {
tableModel.removeRow(selectedRows[i]);
}
});
frame.add(deleteButton, BorderLayout.SOUTH);
frame.setVisible(true);
}
}
这个示例中,我们创建了一个包含JTable和删除按钮的简单界面。当用户选定JTable中的行并单击删除按钮时,选定的行将从JTable中删除。
领取专属 10元无门槛券
手把手带您无忧上云