Java Question

Receiving a lot of error messages when trying to delete rows from JTable

I have a problem with deleting rows from JTable. My code based on this question: How do you remove selected rows from a JTable?

public static void removeSelectedRows(JTable table){
DefaultTableModel model = (DefaultTableModel) table.getModel();
int[] rows = table.getSelectedRows();
for (int i = rows.length - 1; i >= 0; i--) {

When I press button to delete selected rows:

JButton button = new JButton("Delete selected");
button.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e) {

I receive a lot of error messages in my terminal:

Exception in thread "AWT-EventQueue-0" java.lang.ClassCastException: javax.swing.JTable$1 cannot be cast to javax.swing.table.DefaultTableModel
at ConfFrame.removeSelectedRows(
at ConfFrame$1.actionPerformed(
at javax.swing.AbstractButton.fireActionPerformed(
at javax.swing.AbstractButton$Handler.actionPerformed(
at javax.swing.DefaultButtonModel.fireActionPerformed(
at javax.swing.DefaultButtonModel.setPressed(
at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(
at java.awt.Component.processMouseEvent(
at javax.swing.JComponent.processMouseEvent(
at java.awt.Component.processEvent(
at java.awt.Container.processEvent(
at java.awt.Component.dispatchEventImpl(
at java.awt.Container.dispatchEventImpl(
at java.awt.Component.dispatchEvent(
at java.awt.LightweightDispatcher.retargetMouseEvent(
at java.awt.LightweightDispatcher.processMouseEvent(
at java.awt.LightweightDispatcher.dispatchEvent(
at java.awt.Container.dispatchEventImpl(
at java.awt.Window.dispatchEventImpl(
at java.awt.Component.dispatchEvent(
at java.awt.EventQueue.dispatchEventImpl(
at java.awt.EventQueue.access$500(
at java.awt.EventQueue$
at java.awt.EventQueue$
at Method)
at java.awt.EventQueue$
at java.awt.EventQueue$
at Method)
at java.awt.EventQueue.dispatchEvent(
at java.awt.EventDispatchThread.pumpOneEventForFilters(
at java.awt.EventDispatchThread.pumpEventsForFilter(
at java.awt.EventDispatchThread.pumpEventsForHierarchy(
at java.awt.EventDispatchThread.pumpEvents(
at java.awt.EventDispatchThread.pumpEvents(

Answer Source

You are creating your table with fixed data so an inner class is used as your TableModel.

Instead you need to create your JTable with code something like:

DefaultTableModel model = new DefaultTableModel(...);
JTable table = new JTable( model );

Now in your code you will be able to get the TableModel and cast it to a DefaultTableModel.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download