如何从 Java 中的 JTable 中移除选中的行?
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(); } }
输出
广告