繁体   English   中英

jtable复选框选中的行单击按钮时从表中删除?

[英]jtable checkbox checked row remove from table when click button?

下面的代码是我按钮操作的一部分。Jtable包含最后一行是复选框。 当我单击保存按钮时,所选行必须从表行中删除... !!!'

动作执行代码

@Override
public void actionPerformed(ActionEvent e) {
if(e.getSource()==btnSave){
    for (int i = 0; i < retunTable.getRowCount(); i++) {
        Boolean chked = Boolean.valueOf(retunTable.getValueAt(i, 4)
                .toString());
        String dataCol1 = retunTable.getValueAt(i, 1).toString();
        if (chked) {


            JOptionPane.showMessageDialog(null, dataCol1);
            colVaules.add(dataCol1);
            returnBook();
            DefaultTableModel dm=(DefaultTableModel) retunTable.getModel();


        }
    }
}

}

试试看 您的类应该已经覆盖了模型的getColumnClass() ,因此无需尝试执行toString() getValueAt()应该返回一个可强制转换的Boolean对象。 同样,如果要循环并在循环中动态删除行,则需要考虑到每次删除一行时模型的行数都会减少,因此每次删除一行时也需要i-- 请参见下面的示例。

import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.SwingUtilities;
import javax.swing.table.DefaultTableModel;

public class TestCheckedTable {

    public TestCheckedTable() {
        String[] cols = {"col 1", "col 2", "col 3"};
        Object[][] data = new Object[15][];
        for (int i = 0; i < data.length; i++) {
            data[i] = new Object[]{"Hello", "World", false};
        }

        final DefaultTableModel model = new DefaultTableModel(data, cols) {
            @Override
            public Class<?> getColumnClass(int col) {
                return col == 2 ? Boolean.class : String.class;
            }
        };
        JTable table = new JTable(model);

        JButton button = new JButton("Delete Checked Rows");
        button.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                for (int i = 0; i < model.getRowCount(); i++) {
                    Boolean checked = (Boolean) model.getValueAt(i, 2);
                    if (checked) {
                        model.removeRow(i);
                        i--;
                    }
                }
            }
        });

        JFrame frame = new JFrame("test");
        frame.add(new JScrollPane(table));
        frame.add(button, BorderLayout.SOUTH);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.pack();
        frame.setVisible(true);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                new TestCheckedTable();
            }

        });
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM