簡體   English   中英

在按鈕單擊時從jtable中刪除選定的行

[英]remove a selected row from jtable on button click

我想從java中的表中刪除Selected行。 應該在按鈕點擊時執行該事件。 如果有人幫忙,我會感激不盡的...

例如,有一個名為sub_table的表,其中包含3列,即sub_id,sub_name,class。 當我從該表中選擇其中一行並單擊刪除按鈕時,應刪除該特定行。

這很簡單。

  • 在按鈕上添加ActionListener
  • 從附加到表的模型中刪除選定的行。

示例代碼:(有2列的表)

Object[][] data = { { "1", "Book1" }, { "2", "Book2" }, { "3", "Book3" }, 
                    { "4", "Book4" } };

String[] columnNames = { "ID", "Name" };
final DefaultTableModel model = new DefaultTableModel(data, columnNames);

final JTable table = new JTable(model);
table.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);


JButton button = new JButton("delete");
button.addActionListener(new ActionListener() {

    @Override
    public void actionPerformed(ActionEvent arg0) {
        // check for selected row first
        if (table.getSelectedRow() != -1) {
            // remove selected row from the model
            model.removeRow(table.getSelectedRow());
        }
    }
});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM