如何在JTable中找到所选行以将其删除?

时间:2015-04-10 02:52:45

标签: java swing jtable actionlistener defaulttablemodel

我尝试将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;
        }
    }
}

任何想法在按下每个按钮时删除它的行?

1 个答案:

答案 0 :(得分:2)

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

它提供了渲染器/编辑器以及获取行的简单方法。