如何在 JTable 中找到选中的行并删除它?

How to find the selected row in the JTable to remove it?

我试图制作一个 JTable,其中有一列作为 JButton 用于删除选定的行。 但我仍然不知道在按钮中添加什么 ActionListener 来识别它的行并将其删除。

这是我的代码:

public class JavaApplication81 {
    JFrame frame;
    JPanel panel;
    JTable table;
    JScrollPane tableScroll = new JScrollPane();
    DefaultTableModel tableModel;
    public JavaApplication81(){
        frame = new JFrame("Frame");
        panel = new JPanel();

        String col[] = {" ", "File", "Remove"};
        tableModel = new DefaultTableModel(col,0);
        table = new JTable(){
            private static final long serialVersionUID = 1L;
            //Returning the Class of each column will allow different
            //renderes to be used based on class
            @Override
            public Class getColumnClass(int column){
                return getValueAt(0, column).getClass();
            }
        };
        table.setModel(tableModel);
        table.setPreferredScrollableViewportSize(new Dimension(400,200));
        tableScroll.setViewportView(table);

        Object[] data = {"icon", "file", "Remove"};
        tableModel.addRow(data);

        table.getColumn("Remove").setCellRenderer(new ButtonRenderer());
        table.getColumn("Remove").setCellEditor(new ButtonEditor(new JCheckBox()));

        panel.add(tableScroll);
        frame.add(panel);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(450, 200);
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
    }
    public static void main(String[] args) {
        new JavaApplication81();
    }

    ///////////////////////
    public class ButtonRenderer extends JButton implements TableCellRenderer {

      public ButtonRenderer() {
        setOpaque(true);
      }

      public Component getTableCellRendererComponent(JTable table, Object value,
                       boolean isSelected, boolean hasFocus, int row, int column) {

        setText("Remove");
        return this;
      }
    }

    public class ButtonEditor extends DefaultCellEditor {
        protected JButton button;

        public ButtonEditor(JCheckBox checkBox) {
          super(checkBox);
          button = new JButton();
          button.setOpaque(true);
          button.addActionListener(new ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent e) {

            }
          });
        }

        public Component getTableCellEditorComponent(JTable table, Object value,
                         boolean isSelected, int row, int column) {


          button.setText("Remove");
          return button;
        }
    }
}

有没有想过在按下每个按钮时删除它们的行?

Table Button Column 展示了一种简单的方法。

它提供了 renderer/editor 和获取行的简单方法。