java 从 JTable 中删除 1 个选定的行

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17254587/
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-11-01 01:27:39  来源:igfitidea点击:

Remove 1 selected Row from JTable

javaswingjtabledefaulttablemodel

提问by user2445977

I try for almost 2 hours to figure out how to remove and update 1 row from a JTable but somehow it wont work. I use the following code:

我尝试了将近 2 个小时来弄清楚如何从 JTable 中删除和更新 1 行,但不知何故它不起作用。我使用以下代码:

DefaultTableModel modelTable = (DefaultTableModel) jTabelRooster.getModel();

modelTable.addRow(new Object[]{lid.getLidnummer().toString(), lid.getLidvoornaam(), lid.getLidtussenvoegsel(),lid.getLidachternaam(), lid.getAanwezig()});

Ok so far so good.. rows are nicely added.. but now i would like to remove them:

到目前为止一切顺利.. 行很好地添加.. 但现在我想删除它们:

int SelectedRow = jTabelRooster.getSelectedRow();
modelTable.removeRow(SelectedRow);

When i do this i get the following error: Exception in thread "AWT-EventQueue-0" java.lang.ArrayIndexOutOfBoundsException: 2 >= 2

当我这样做时,我收到以下错误: 线程“AWT-EventQueue-0”中的异常 java.lang.ArrayIndexOutOfBoundsException: 2 >= 2

Your help would be appreciated

您的帮助将不胜感激

EDIT: the jTabelRooster has been inserterd by the gui layout manager So i have this code now, and i dont get much succes:

编辑:jTabelRooster 已被 gui 布局管理器插入所以我现在有这个代码,但我没有得到太多成功:

private void initRoosterDetail()
{
   for(int i = 0; i < leden.size(); i++)
        {
            lid = leden.get(i);

            modelTable.addRow(new Object[]{lid.getLidnummer().toString(), lid.getLidvoornaam(), lid.getLidtussenvoegsel(),lid.getLidachternaam(), lid.getAanwezig()});

        }
}
private void jbInschrijvingVerwijderenActionPerformed(java.awt.event.ActionEvent evt) {                                                          
        int SelectedRow = jTabelRooster.getSelectedRow();
        modelTable.removeRow(jTabelRooster.convertRowIndexToModel(SelectedRow));
  }  

this must be it :)

这一定是它:)

When i select 1 row in the table and press the cancelbutton.. i receive this message:

当我选择表中的 1 行并按下取消按钮时.. 我收到此消息:

Exception in thread "AWT-EventQueue-0" java.lang.ArrayIndexOutOfBoundsException: 2 >= 2

线程“AWT-EventQueue-0”中的异常 java.lang.ArrayIndexOutOfBoundsException: 2 >= 2

========================================================================================================================================================================================================================================================================================================================================

================================================== ================================================== ================================================== ================================================== ================================================== ================================================== ============================

Thanx all for the help... i know what i did wrong... it had to do with a tableModelListener i used.. so this left me with another problem :)

感谢所有的帮助......我知道我做错了什么......它与我使用的 tableModelListener 有关......所以这给我留下了另一个问题:)

 jTabelRooster.getModel().addTableModelListener(
        new TableModelListener()
        {
        public void tableChanged(TableModelEvent evt) 
        {
             if(jTabelRooster.getSelectedColumn() == 4)
             {
              }
    }

});

This code was messing the deleterow command.

这段代码弄乱了 deleterow 命令。

I have 1 boolean column with checkboxes in it :(

我有 1 个带有复选框的布尔列:(

回答by Amarnath

int selectedRow = jTabelRooster.getSelectedRow();
modelTable.removeRow(SelectedRow);

If no row is selected then jTabelRooster.getSelectedRow()will return -1

如果没有选择行,则jTabelRooster.getSelectedRow()返回-1

So before you delete check whether a row is selected or not.

因此,在删除之前检查是否选择了一行。

int selectedRow = jTabelRooster.getSelectedRow();
if(selectedRow != -1) {
    modelTable.removeRow(selectedRow);
}

P.S: Try to follow java naming conventions. Variable name should start with a lowercase.

PS:尽量遵循java命名约定。变量名应该以小写开头。

EDIT:An example which shows how to add and remove rows using DefaultTableModelfrom a table.

编辑:一个示例,展示了如何使用DefaultTableModel从表中添加和删​​除行。

private void createUI() {
        JFrame frame = new JFrame();

        frame.setLayout(new BorderLayout());

        final JTable table = new JTable();
        final DefaultTableModel model = new DefaultTableModel(5, 3);
        table.setModel(model);

        JPanel btnPnl = new JPanel(new BorderLayout());
        JPanel bottombtnPnl = new JPanel(new FlowLayout(FlowLayout.CENTER));

        JButton addBtn = new JButton("Add");
        JButton deleteBtn = new JButton("Remove");
        bottombtnPnl.add(addBtn);
        bottombtnPnl.add(deleteBtn);

        addBtn.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                model.addRow(new Object[]{});
            }
        });

        deleteBtn.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                int selRow = table.getSelectedRow();
                if(selRow != -1) {
                    model.removeRow(selRow);
                }
            }
        });

        btnPnl.add(bottombtnPnl, BorderLayout.CENTER);

        table.getTableHeader().setReorderingAllowed(false);

        frame.add(table.getTableHeader(), BorderLayout.NORTH);
        frame.add(table, BorderLayout.CENTER);
        frame.add(btnPnl, BorderLayout.SOUTH);

        frame.setTitle("JTable Example.");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.pack();
        frame.setVisible(true);
    }

回答by Hovercraft Full Of Eels

All we can say based on this code:

基于此代码,我们只能说:

private void jbInschrijvingVerwijderenActionPerformed(java.awt.event.ActionEvent evt) {                                                          
    int SelectedRow = jTabelRooster.getSelectedRow();
    modelTable.removeRow(jTabelRooster.convertRowIndexToModel(SelectedRow));
}

and this error:

和这个错误:

Exception in thread "AWT-EventQueue-0" java.lang.ArrayIndexOutOfBoundsException: 2 >= 2

is that somehow your TableModel held by modelTable is out of sync with the actual model that is held by the jTabelRooster JTable, and that's about it. We know this because your selected row in the JTable is row number 2 which is the 3rd row, but your model held by modelTable is showing that it holds only 2 rows. How or why this is occurring is impossible for us to guess based on the limited information that you've presented so far.

不知何故,modelTable 持有的 TableModel 与 jTabelRooster JTable 持有的实际模型不同步,仅此而已。我们知道这一点是因为您在 JTable 中选择的行是第 2 行,即第 3 行,但是 modelTable 持有的模型显示它仅包含 2 行。根据您目前提供的有限信息,我们无法猜测这是如何或为什么会发生这种情况。

Again, you should strongly consider creating and posting an sscce.

同样,您应该强烈考虑创建和发布sscce