remove a selected row from jtable on button click
Asked Answered
V

1

8

I want to remove a Selected row from a table in java. The event should be performed on button click. I will be thank full if someone helps...

For example there is a table named sub_table with 3 columns i.e sub_id, sub_name,class. when I select one of the rows from that table and click delete button that particular row should be deleted..

Varia answered 5/5, 2014 at 5:19 Comment(5)
Soooooo..... no code?Preview
possible duplicate of this one.Forevermore
no...i am completely stucked plz helpVaria
Stuck on where? Any code.Ileneileo
ok....thanx I got it....Varia
R
10

It's very simple.

  • Add ActionListener on button.
  • Remove selected row from the model attached to table.

Sample code: (table having 2 columns)

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());
        }
    }
});
Robles answered 5/5, 2014 at 5:27 Comment(2)
It's worth nothing that the "view" index given by table.getSelectedRow() is not always the same as the "model" index. For example, if the table is sorted, all of the indices may be different. You can convert the index from getSelectedRow() into the model index with table.convertRowIndexToModel(int index).Cork
@cubrr yes you are right. Thanks for correcting it.Robles

© 2022 - 2024 — McMap. All rights reserved.