I'm using a JTable with a DefaultTableModel. I use the Load Button for populating the JTable.

Anyway, the problem I have is with the Delete row button. (defaulttablemodel.removeRow).

This is the whole project:

package proiect1;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableColumn;
import java.io.*;
import javax.swing.event.*;
import javax.swing.table.TableModel;
import java.util.ArrayList;
import javax.swing.table.AbstractTableModel;



public class tabel extends javax.swing.JFrame implements TableModelListener {
 
    
 DefaultTableModel model1;


    private static ArrayList<clasaIntrebare> listaIntrebari = new ArrayList<clasaIntrebare>();
    private static int n;


    public tabel() {
        initComponents();

        model1= new DefaultTableModel() {

        @Override
        public boolean isCellEditable(int row, int column) {

           if (column == 2 || column == 1 || column == 6)
                return false;

           return true;
        }

        };

        tabel.setModel(model1);

        model1.addColumn("Enunt");
        model1.addColumn("Tip");
        model1.addColumn("ID");
        model1.addColumn("Varianta 1");
        model1.addColumn("Varianta 2");
        model1.addColumn("Varianta 3");
        model1.addColumn("Var. corecta");
       
       TableColumn col = tabel.getColumnModel().getColumn(0);

       col.setPreferredWidth(100);

       col=tabel.getColumnModel().getColumn(1);
       col.setPreferredWidth(35);
       
       col=tabel.getColumnModel().getColumn(2);
       col.setPreferredWidth(35);


   }


     
    // <editor-fold defaultstate="collapsed" desc="Generated Code">
    private void initComponents() {

        jScrollPane1 = new javax.swing.JScrollPane();
        tabel = new javax.swing.JTable();
        Load = new javax.swing.JButton();
        control = new javax.swing.JLabel();
        deleteRow = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        tabel.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null}
            },
            new String [] {
                "Title 1", "Title 2", "Title 3", "Title 4"
            }
        ));
        jScrollPane1.setViewportView(tabel);

        Load.setText("Load");
        Load.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                LoadActionPerformed(evt);
            }
        });

        control.setText("here: ");

        deleteRow.setText("Delete Row");
        deleteRow.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                deleteRowActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addComponent(deleteRow)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 19, Short.MAX_VALUE)
                        .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 510, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(Load)
                        .addGap(107, 107, 107)
                        .addComponent(control, javax.swing.GroupLayout.PREFERRED_SIZE, 187, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 287, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 30, Short.MAX_VALUE))
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addContainerGap()
                        .addComponent(deleteRow)
                        .addGap(58, 58, 58)))
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(Load)
                        .addContainerGap())
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(control, javax.swing.GroupLayout.PREFERRED_SIZE, 33, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(29, 29, 29))))
        );

        pack();
    }// </editor-fold>


    public int corect(String raspuns){

        String x,y="";

        try
        {

            BufferedReader in = new BufferedReader(new FileReader("raspunsuri.txt"));


            while ((x = in.readLine()) != null)
            {

             y+=x;
            }

            // Close our input stream
            in.close();
        }
        // Catches any error conditions
        catch (IOException e)
        {
                System.err.println ("Unable to read from file");
                System.exit(-1);
        }
        

        if (y.indexOf(raspuns)>=0)     // raspuns corect
            return 1;
        else                // rasp incorect
            return 0;


    }



    private void LoadActionPerformed(java.awt.event.ActionEvent evt) {                                            
        
       String str;
       String enunt="", var1,var2,var3;
       int tip, cod, corect=0;

       MD5 obiect= new MD5();
       
       this.loadQ();
       
       int i=0;

        while (i<n){
            enunt=listaIntrebari.get(i).getenunt();
            tip=listaIntrebari.get(i).gettip();;
            cod=listaIntrebari.get(i).getcod();
            var1=listaIntrebari.get(i).getraspuns1();
            var2=listaIntrebari.get(i).getraspuns2();
            var3=listaIntrebari.get(i).getraspuns3();


         str=obiect.crypt(Integer.toString(cod)+" "+ "true" + " "+ "false" +" " + "false");

         if (corect(str)==1)
            corect=1;

           str=obiect.crypt(Integer.toString(cod)+" "+ "false" +" " + "true" + " "+ "false");

           if (corect(str)==1)
                  corect=2;
           
           
          str=obiect.crypt(Integer.toString(cod)+" "+ "false" +" " +"false"+" "+"true"); 
           
          if (corect(str)==1)
                  corect=3;

          model1.addRow(new Object[]{enunt, tip, cod, var1, var2, var3, corect});
        i++;

        }
                    
        model1.addTableModelListener(this);
        
        //adaugareRow.setVisible(false);
        //adaugareRow.setVisible(true);
        //Load.setEnabled(false);
 
    }                                           


    private void deleteRowActionPerformed(java.awt.event.ActionEvent evt) {

       
        try{
            model1.removeRow(0);

        
        tabel.revalidate();
        }
        catch (ArrayIndexOutOfBoundsException e){
            System.out.println("error");
            e.printStackTrace();
        };
    }

public void loadQ(){
        String str;
          try{
            BufferedReader in = new BufferedReader(new FileReader("intrebari.txt"));

            while ( (str=in.readLine()) != null){

                listaIntrebari.add(n, new clasaIntrebare(str,
                                                         Integer.parseInt(in.readLine()), Integer.parseInt(in.readLine()),
                                                         in.readLine(), in.readLine(), in.readLine() ) );
                 n++;
            }
            in.close();


        }

        catch(IOException e){
            System.err.println("Cannot read from file.");
            System.exit(-1);

        }



   }




    public void tableChanged(TableModelEvent e) {
        int row = e.getFirstRow();
        int column = e.getColumn();

        TableModel model = (TableModel)e.getSource();
        String columnName = model.getColumnName(column);
        Object data = model.getValueAt(row, column);

        listaIntrebari.get(e.getFirstRow()).setenunt((String)model1.getValueAt(row, column));

//      Load.setText((String)model1.getValueAt(row, column));
        System.out.println("change: "+ Integer.toString(e.getFirstRow())+" " + Integer.toString(e.getColumn()));

        //control.setText(listaIntrebari.get(e.getFirstRow()).getenunt());
        control.setText(Integer.toString(column));
    }


    

    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new tabel().setVisible(true);

            }
        });
    }

    // Variables declaration - do not modify
    private javax.swing.JButton Load;
    private javax.swing.JLabel control;
    private javax.swing.JButton deleteRow;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTable tabel;
    // End of variables declaration

}

run:
error
java.lang.ArrayIndexOutOfBoundsException: Array index out of range: -1
at java.util.Vector.removeElementAt(Vector.java:515)
at javax.swing.table.DefaultTableModel.removeRow(DefaultTableModel.java:446)
at proiect1.tabel.deleteRowActionPerformed(tabel.java:253)
at proiect1.tabel.access$100(tabel.java:24)
at proiect1.tabel$3.actionPerformed(tabel.java:116)
at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:1995)
at javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.java:2318)
at javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:387)
at javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:242)
at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(BasicButtonListener.java:236)
at java.awt.Component.processMouseEvent(Component.java:6267)
at javax.swing.JComponent.processMouseEvent(JComponent.java:3267)
at java.awt.Component.processEvent(Component.java:6032)
at java.awt.Container.processEvent(Container.java:2041)
at java.awt.Component.dispatchEventImpl(Component.java:4630)
at java.awt.Container.dispatchEventImpl(Container.java:2099)
at java.awt.Component.dispatchEvent(Component.java:4460)
at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4577)
at java.awt.LightweightDispatcher.processMouseEvent(Container.java:4238)
at java.awt.LightweightDispatcher.dispatchEvent(Container.java:4168)
at java.awt.Container.dispatchEventImpl(Container.java:2085)
at java.awt.Window.dispatchEventImpl(Window.java:2478)
at java.awt.Component.dispatchEvent(Component.java:4460)
at java.awt.EventQueue.dispatchEvent(EventQueue.java:599)
at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:269)
at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:184)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:174)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:169)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:161)
at java.awt.EventDispatchThread.run(EventDispatchThread.java:122)

Edited 6 Years Ago by Buffalo101: n/a

Attachments
intrebarea 0
1
0
0
1
2
intrebarea 1
1
1
0
1
2
intrebarea 2
1
2
0
1
2
intrebarea 3
1
3
3
4
5
intrebarea 4
1
4
3
4
5
intrebarea 5
1
5
3
4
5
intrebarea 6
1
6
6
7
8
intrebarea 7
1
7
6
7
8
intrebarea 8
1
8
6
7
8
intrebarea NINJA
1
9
nimic
nimic
nimic
intrebarea NINJA 2
1
10
ninja0
ninja1
ninja2
5f0fdd1db06a02db88cc26e569f7ec4e
ee8cfe4271f0b2fb2d5fa0ce962401fe
b066bb5b279e64883d8985781f526502
868cb0cf3e8f3f29f58d5bedcf6c8499
33c4c0ccecccfcf1ac8912bf6804b588
f18bd80c4ea9932eb371181e220975a9
e6fc85509bccf7cada4a76938272c892
06e5afe8e6bf90ee175ee6edfb799262
39bcf625ceb8395f7078f5782872b8aa
6d617e05ef2df50f39d315293f956fdf
f2d63c8abb7f2c52f9ead71577263bb8

You set the model for tabel in the init method (line 75), but then after returning from that you set a different model for tabel (line 39). That seems odd.

NetBeans generates the code, can't change it.

clasaIntrebare.java:

package proiect1;
import java.util.ArrayList;


public class clasaIntrebare {

private    String enunt;

private    int cod;
private    int tip;
private    int used;


private    String raspuns1;
private    String raspuns2;
private    String raspuns3;


public String getenunt(){

   return this.enunt;
}

public int getcod(){

   return this.cod;
}

public int gettip(){
    return this.tip;
    }

public String getraspuns1(){

   return this.raspuns1;
}

public String getraspuns2(){

   return this.raspuns2;
}

public String getraspuns3(){

   return this.raspuns3;
}

public int getused(){
    return this.used;
    }


public void setused(){
    this.used=1;
    }

public void setenunt(String enunt){
    this.enunt=enunt;
    }

public void setcod(int cod){
    this.cod=cod;
    }

public void settip(int tip){
    this.tip=tip;
    }

public void setraspuns1(String raspuns1){
    this.raspuns1=raspuns1;
    }

public void setraspuns2(String raspuns2){
    this.raspuns2=raspuns2;
    }

public void setraspuns3(String raspuns3){
    this.raspuns3=raspuns3;
    }



public clasaIntrebare(String Enunt,  int Tip, int Cod,

                      String Raspuns1, String Raspuns2,

                      String Raspuns3){

     cod= Cod; // ID

     used=0;

     tip= Tip; // type: radio/checkbox

     enunt= Enunt; //question


     raspuns1= Raspuns1; //choice 1

     raspuns2= Raspuns2; //choice 2

     raspuns3= Raspuns3; // choice 3

}

}

Working now:

private void deleteRowActionPerformed(java.awt.event.ActionEvent evt) {

       
        try{
            //model1.removeRow(tabel.getSelectedRow()); replaced with: 

            ((DefaultTableModel)tabel.getModel()).removeRow(tabel.getSelectedRow());  // -> why does this work and above doesn't? 
        
        tabel.revalidate();
        }
        catch (ArrayIndexOutOfBoundsException e){
            System.out.println("error");
            e.printStackTrace();
        };
    }


    public void tableChanged(TableModelEvent e) {
       int row = e.getFirstRow();
       int column = e.getColumn();

         if (e.getType()!=-1)
        {

        TableModel model = (TableModel)e.getSource();
        String columnName = model.getColumnName(column);
        Object data = model.getValueAt(row, column);   // ->>>>>>>> how to access this? 

        listaIntrebari.get(e.getFirstRow()).setenunt((String)model1.getValueAt(row, column));



        System.out.println("change: "+ Integer.toString(e.getFirstRow())+" " + Integer.toString(e.getColumn()));

        control.setText(listaIntrebari.get(e.getFirstRow()).getenunt());

        }

    else
        control.setText("deleted " + listaIntrebari.get(row).getenunt());
 }

The pieces of code using getValueAt(x, column) generated errors because e.getColumn() is -1.

I added the tableChanged listener to be able to update my arrayList whenever a cell list is modified. I tried using e.getType() to check if the event is DELETE. (delete event : e.getType() returns -1), which works. If anyone has any suggestions about how to do this more graciously, please share.


====

Some explanation for lines 8, 28 please?

Edited 6 Years Ago by Buffalo101: n/a

This article has been dead for over six months. Start a new discussion instead.