【问题标题】:remove a selected row from jtable on button click单击按钮时从 jtable 中删除选定的行
【发布时间】:2014-06-21 07:56:52
【问题描述】:

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

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

【问题讨论】:

  • Sooooooo.....没有代码?
  • this 可能重复一个。
  • 不...我完全卡住了请帮助
  • 卡在哪里?任何代码。
  • 好的....谢谢我明白了....

标签: java swing jtable actionevent


【解决方案1】:

这很简单。

  • 在按钮上添加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());
        }
    }
});

【讨论】:

  • table.getSelectedRow() 给出的“视图”索引并不总是与“模型”索引相同,这是毫无价值的。例如,如果表已排序,则所有索引都可能不同。您可以使用table.convertRowIndexToModel(int index) 将索引从getSelectedRow() 转换为模型索引。
  • @cubrr 是的,你是对的。谢谢指正。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-02-06
相关资源
最近更新 更多