Java 单击按钮时从 jtable 中删除选定的行

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/23465295/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 23:10:25  来源:igfitidea点击:

remove a selected row from jtable on button click

javaswingjtableactionevent

提问by kdubey007

I want to remove a Selected row from a table in java. The event should be performed on button click. I will be thank full if someone helps...

我想从 java 中的表中删除选定的行。该事件应在按钮单击时执行。如果有人帮助,我将不胜感激...

For example there is a table named sub_table with 3 columns i.e sub_id, sub_name,class. when I select one of the rows from that table and click delete button that particular row should be deleted..

例如,有一个名为 sub_table 的表,包含 3 列,即 sub_id、sub_name、class。当我从该表中选择一行并单击删除按钮时,应删除该特定行。

回答by Braj

It's very simple.

这很简单。

  • Add ActionListeneron button.
  • Remove selected row from the model attached to table.
  • 添加 ActionListener按钮。
  • 从附加到表的模型中删除选定的行。

Sample code: (table having 2 columns)

示例代码:(表有 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());
        }
    }
});