Problem with removing elements from a JTable

  • Java
  • Thread starter zak100
  • Start date
  • Tags
    Elements
In summary: Two.add("Circle 2"); rowTwo.add(" " + circle2.getDim1()); rowTwo.add(" "); rowTwo.add(" "); rowTwo.add(" "); rowTwo.add(" " + areaC2); rowThree.add("Circle 3"); rowThree.add(" " + circle3.getDim1()); rowThree.add(" "); rowThree.add(" "); rowThree.add(" "); rowThree.add(" " + areaC3); } else if(result2==0){ /*rowOne.remove(0); rowTwo.remove(0); rowThree.remove(0); model.getDataVector().removeAllElements();model.fireTableDataChanged();
  • #1
zak100
462
11
Hi,
I am using a vector to store vales in the Jtable. I am storing 3 rows in the table. I have written a clean button handler to remove values from the table. Its code is:


Java:
rowOne.removeAllElements();
        rowTwo.removeAllElements();
        rowThree.removeAllElements();
        //model.fireTableDataChanged();
        model.removeRow(0);-----> exception here

When i am pressing this button, I am getting following Exception:

Exception in thread "AWT-EventQueue-0" java.lang.ArrayIndexOutOfBoundsException: 0 >= 0
at java.util.Vector.elementAt(Vector.java:474)
at javax.swing.table.DefaultTableModel.getValueAt(DefaultTableModel.java:649)
at javax.swing.JTable.getValueAt(JTable.java:2717)
at javax.swing.JTable.prepareRenderer(JTable.java:5706)
at javax.swing.plaf.synth.SynthTableUI.paintCell(SynthTableUI.java:683)
at javax.swing.plaf.synth.SynthTableUI.paintCells(SynthTableUI.java:580)
at javax.swing.plaf.synth.SynthTableUI.paint(SynthTableUI.java:364)
at javax.swing.plaf.synth.SynthTableUI.update(SynthTableUI.java:275)
at javax.swing.JComponent.paintComponent(JComponent.java:780)
at javax.swing.JComponent.paint(JComponent.java:1056)
at javax.swing.JComponent.paintChildren(JComponent.java:889)
at javax.swing.JComponent.paint(JComponent.java:1065)
at javax.swing.JViewport.paint(JViewport.java:728)
at javax.swing.JComponent.paintChildren(JComponent.java:889)
at javax.swing.JComponent.paint(JComponent.java:1065)
at javax.swing.JComponent.paintChildren(JComponent.java:889)
at javax.swing.JComponent.paint(JComponent.java:1065)
at javax.swing.JComponent.paintToOffscreen(JComponent.java:5210)
at javax.swing.RepaintManager$PaintManager.paintDoubleBuffered(RepaintManager.java:1579)
at javax.swing.RepaintManager$PaintManager.paint(RepaintManager.java:1502)
at javax.swing.RepaintManager.paint(RepaintManager.java:1272)
at javax.swing.JComponent._paintImmediately(JComponent.java:5158)
at javax.swing.JComponent.paintImmediately(JComponent.java:4969)
at javax.swing.RepaintManager$4.run(RepaintManager.java:831)
at javax.swing.RepaintManager$4.run(RepaintManager.java:814)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:76)
at javax.swing.RepaintManager.paintDirtyRegions(RepaintManager.java:814)
at javax.swing.RepaintManager.paintDirtyRegions(RepaintManager.java:789)
at javax.swing.RepaintManager.prePaintDirtyRegions(RepaintManager.java:738)
at javax.swing.RepaintManager.access$1200(RepaintManager.java:64)
at javax.swing.RepaintManager$ProcessingRunnable.run(RepaintManager.java:1732)
at java.awt.event.InvocationEvent.dispatch(InvocationEvent.java:311)
at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:756)
at java.awt.EventQueue.access$500(EventQueue.java:97)
at java.awt.EventQueue$3.run(EventQueue.java:709)
at java.awt.EventQueue$3.run(EventQueue.java:703)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:76)
at java.awt.EventQueue.dispatchEvent(EventQueue.java:726)
at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:201)
at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:116)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:105)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:101)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:93)
at java.awt.EventDispatchThread.run(EventDispatchThread.java:82)

where rowOne, rowTwo and rowThree are vectors.

Some body please guide me how to solve this problem.

Zulfi.
 
Last edited:
Technology news on Phys.org
  • #2
An ArrayOutOfBoundsException is due to attempting to manipulate something that doesn't exist. I.E. trying to access the 1st record of an empty set. If you can set a breakpoint before the error, you'll probably see that it's empty.
 
  • #3
Hi,
Hi,

Thanks for your reply.

I have modified:

rowOne.removeAllElements();

rowTwo.removeAllElements();

rowThree.removeAllElements();

//model.fireTableDataChanged();

Object obj=model.getValueAt(0, 0);

model.removeRow(0);I am using the debugger to check the value of obj or the expression :

Object obj=model.getValueAt(0, 0);But i am not getting any thing. I am seeing the stuff in my table. How can i get rid of the stuff from table view. If its deleted then how can i get rid of it from Table view.
Some body please guide me.

Zulfi.
 
  • #4
It might be easier to assist you if you could post the relevant code.
 
  • #5
Hi,
I am using NetBeans. My application class contains following code:
Java:
public class FigureInheritanceJFrame extends javax.swing.JFrame {
    DefaultTableModel model = new DefaultTableModel(new Object[]{"FigureName","Dimension 1","Dimension 2", "Dimension 3", "Dimension 4", "Area"},0  );
    //final DefaultTableModel model=null;
    //model = (DefaultTableModel) figTable.getModel();
    Vector<String> rowOne = new Vector<String>();
    Vector<String> rowTwo = new Vector<String>();
    Vector<String> rowThree = new Vector<String>();
  
    String cBoBoxItem="Rectangle";
    private DefaultComboBoxModel modelC;
    /**
     * Creates new form FigureInheritanceJFrame
     */
    public FigureInheritanceJFrame() {//Application Class Constrcutor populating comboBox
      
        initComponents();
        modelC = new DefaultComboBoxModel ( );
      
modelC.addElement("Rectangle" );
modelC.addElement("Circle" );
modelC.addElement("Triangle" );
        cBoBox.setModel(modelC);
      
    }
[B]//Button Handler code to insert the data into table[/B]
private void btnADTActionPerformed(java.awt.event.ActionEvent evt) {                                     
        // TODO add your handling code here:
       double areaC1=0, areaC2 =0, areaC3=0;
       double areaR1=0, areaR2= 0, areaR3=0;
       double areaT1=0, areaT2= 0, areaT3=0;
JOptionPane.showMessageDialog(null," "+ cBoBoxItem );
       int result1=-1; int result2=-1; int result3=-1;
        result1 = cBoBoxItem.compareTo("Circle");
        result2 = cBoBoxItem.compareTo("Rectangle");
        result3 = cBoBoxItem.compareTo("Triangle");
JOptionPane.showMessageDialog(null," "+ cBoBoxItem + " res1= "+ result1 + " res2 "+ result2 + " res3= "+ result3);
       if(result1==0){
           /*rowOne.remove(0);
           rowTwo.remove(0);
           rowThree.remove(0);
           model.getDataVector().removeAllElements();
model.fireTableDataChanged();*/
         
           Circle circle1 = new Circle(10);
           areaC1= circle1.area();
           Circle circle2 = new Circle(11);
           areaC2= circle2.area();
           Circle circle3 = new Circle(12);
           areaC3= circle3.area();
rowOne.add("Circle 1");
           rowOne.add(" " + circle1.getDim1());
           rowOne.add(" ");
           rowOne.add(" ");
           rowOne.add(" ");
           rowOne.add(" " + areaC1);
           model.addRow(rowOne);
figTable.setModel(model);
rowTwo.add("Circle 2");
           rowTwo.add(" " + circle2.getDim1());
           rowTwo.add(" ");
           rowTwo.add(" ");
           rowTwo.add(" ");
           rowTwo.add(" " + areaC2);
           model.addRow(rowTwo);
figTable.setModel(model);
rowThree.add("Circle 3");
           rowThree.add(" " + circle1.getDim1());
           rowThree.add(" ");
           rowThree.add(" ");
           rowThree.add(" ");
           rowThree.add(" " + areaC1);
model.addRow(rowThree);
figTable.setModel(model);
         
           /*rowOne.remove(0);
           rowTwo.remove(0);
           rowThree.remove(0);*/
           result1=-1;
       }
       else if (result2==0){
   [B] //code to add rectangle data into table[/B]
}
else if(result3==0){
[B]//code to add triangle data into table[/B]
}
[B]//Then there is comboBox handler which retrieves the item selected from ComboBox:[/B]
private void cBoBoxActionPerformed(java.awt.event.ActionEvent evt) {                                     
        // TODO add your handling code here:
        cBoBoxItem = cBoBox.getSelectedItem().toString();
    }
[B]//Following is the code for clear button handler:[/B]
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
        // TODO add your handling code here:
rowOne.removeAllElements();
        rowTwo.removeAllElements();
rowThree.removeAllElements();
//model.fireTableDataChanged();
        Object obj=model.getValueAt(0, 0);
        model.removeRow(0);
        //model.removeRow(1);
        //model.removeRow(2);
//figTable.setModel(model);*/
      
    }

Okay now I would tell you my problem. My comboBox contain 3 items: Rectangle, Triangle & Circle. If I select circle then it would store data of 3 Circle objects in the table. It works fine. Now I select Rectangle then instead of storing Rectangle data in the table, it stores Circle data into the table again.This is problem. I think because I am not clearing the Vector (maybe). So I wrote the code for clear button which I would call after storing data of any figure in the table so that Vector becomes empty & then it won't store redundant data in the data i.e the data of previously selected item from comboBox into the table . That is first I would select circle from ComboBox. Then I would press add button to store circle data in combo Box & then I would press clear & I would store the data of any other figure like Triangle or Rectangle so that the table should not be populated with redundant data.This is my problem that my program is storing the data of first selected figure in the table again and again even if select a different figure from combobox.Some body please guide me about the clear button.

Zulfi.
 
  • #6
That code is very incomplete which makes debugging it difficult but, from what I do see, I don't think that your objects are in the state that you think that they are.
 
  • #7
Hi,
Okay, i am sending you the whole code:

Java:
import javax.swing.*;
import java.util.*;

import javax.swing.table.DefaultTableModel;

abstract class Figure{
    double dim1;
    double dim2;
    Figure(double a, double b){
        dim1 =a;
        dim2=b;
    }
    double getDim1(){return dim1;}
    double getDim2(){return dim2;}
    abstract double area();
   
}
class Triangle extends Figure{
    Triangle(double a, double b){
        super(a, b);
    }
    double area(){
        return dim1 * dim2/2.0;
    }
}
class Rectangle extends Figure{
    Rectangle(double a, double b){
        super(a,b);
    }
    double area(){
        return dim1 * dim2;
    }
}

class Circle extends Figure{
    Circle(double r){
        super(r,r);
    }
    double area(){
        return dim1 * dim2 * 3.14;
    }
}
public class FigureInheritanceJFrame extends javax.swing.JFrame {
    DefaultTableModel model = new DefaultTableModel(new Object[]{"FigureName","Dimension 1","Dimension 2", "Dimension 3", "Dimension 4", "Area"},0  );
    //final DefaultTableModel model=null;
    //model = (DefaultTableModel) figTable.getModel();
    Vector<String> rowOne = new Vector<String>();
    Vector<String> rowTwo = new Vector<String>();
    Vector<String> rowThree = new Vector<String>();
   
    String cBoBoxItem="Rectangle";
    private DefaultComboBoxModel modelC;
    /**
     * Creates new form FigureInheritanceJFrame
     */
    public FigureInheritanceJFrame() {
       
        initComponents();
        modelC = new DefaultComboBoxModel ( );
       
        modelC.addElement("Rectangle" );
        modelC.addElement("Circle" );
        modelC.addElement("Triangle" );
        cBoBox.setModel(modelC);
       
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">                         
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        jScrollPane1 = new javax.swing.JScrollPane();
        figTable = new javax.swing.JTable();
        btnADT = new javax.swing.JButton();
        cBoBox = new javax.swing.JComboBox<>();
        jButton1 = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

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

        btnADT.setText("Add Data in Table");
        btnADT.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnADTActionPerformed(evt);
            }
        });

        cBoBox.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cBoBoxActionPerformed(evt);
            }
        });

        jButton1.setText("Clean");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(btnADT)
                .addGap(102, 102, 102))
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addContainerGap()
                        .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 510, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGap(67, 67, 67)
                        .addComponent(cBoBox, javax.swing.GroupLayout.PREFERRED_SIZE, 103, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(62, 62, 62)
                        .addComponent(jButton1)))
                .addContainerGap(33, Short.MAX_VALUE))
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGap(40, 40, 40)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 119, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(30, 30, 30)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(cBoBox, javax.swing.GroupLayout.PREFERRED_SIZE, 49, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jButton1))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 8, Short.MAX_VALUE)
                .addComponent(btnADT)
                .addGap(50, 50, 50))
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(39, 39, 39)
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(102, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );

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

    private void btnADTActionPerformed(java.awt.event.ActionEvent evt) {                                      
        // TODO add your handling code here:
       double areaC1=0, areaC2 =0, areaC3=0;
       double areaR1=0, areaR2= 0, areaR3=0;
       double areaT1=0, areaT2= 0, areaT3=0;
       JOptionPane.showMessageDialog(null," "+ cBoBoxItem );
       int result1=-1; int result2=-1; int result3=-1;
        result1 = cBoBoxItem.compareTo("Circle");
        result2 = cBoBoxItem.compareTo("Rectangle");
        result3 = cBoBoxItem.compareTo("Triangle");
        JOptionPane.showMessageDialog(null," "+ cBoBoxItem + " res1= "+ result1 + " res2 "+ result2 + " res3= "+ result3);
       if(result1==0){
           /*rowOne.remove(0);
           rowTwo.remove(0);
           rowThree.remove(0);
           model.getDataVector().removeAllElements();
           model.fireTableDataChanged();*/
          
           Circle circle1 = new Circle(10);
           areaC1= circle1.area();
           Circle circle2 = new Circle(11);
           areaC2= circle2.area();
           Circle circle3 = new Circle(12);
           areaC3= circle3.area();
           rowOne.add("Circle 1");
           rowOne.add(" " + circle1.getDim1());
           rowOne.add(" ");
           rowOne.add(" ");
           rowOne.add(" ");
           rowOne.add(" " + areaC1);
           model.addRow(rowOne);
           figTable.setModel(model);
           rowTwo.add("Circle 2");
           rowTwo.add(" " + circle2.getDim1());
           rowTwo.add(" ");
           rowTwo.add(" ");
           rowTwo.add(" ");
           rowTwo.add(" " + areaC2);
           model.addRow(rowTwo);
           figTable.setModel(model);
           rowThree.add("Circle 3");
           rowThree.add(" " + circle1.getDim1());
           rowThree.add(" ");
           rowThree.add(" ");
           rowThree.add(" ");
           rowThree.add(" " + areaC1);
           model.addRow(rowThree);
           figTable.setModel(model);
          
           /*rowOne.remove(0);
           rowTwo.remove(0);
           rowThree.remove(0);*/
           result1=-1;
       }
       else if (result2==0){
         
           /*rowOne.remove(0);
           rowTwo.remove(0);
           rowThree.remove(0);
           model.getDataVector().removeAllElements();
           model.fireTableDataChanged();*/
           Rectangle rect1 = new Rectangle(10, 20);
           areaR1 = rect1.area();
           Rectangle rect2 = new Rectangle(11, 21);
           areaR2 = rect2.area();
           Rectangle rect3 = new Rectangle(12, 22);
           areaR3 = rect3.area();
           rowOne.add("Rectangle 1");
           rowOne.add(" " + rect1.getDim1());
           rowOne.add(" " + rect1.getDim2());
           rowOne.add(" ");
           rowOne.add(" ");
           rowOne.add(" " + areaR1);
           model.addRow(rowOne);
           figTable.setModel(model);
           rowTwo.add("Rectangle 2");
           rowTwo.add(" " + rect2.getDim1());
           rowTwo.add(" " + rect2.getDim2());
           rowTwo.add(" ");
           rowTwo.add(" ");
           rowTwo.add(" " + areaR2);
           model.addRow(rowTwo);
           figTable.setModel(model);
           rowThree.add("Rectangle 3");
           rowThree.add(" " + rect3.getDim1());
           rowThree.add(" " + rect3.getDim2());
           rowThree.add(" ");
           rowThree.add(" ");
           rowThree.add(" " + areaR3);
           model.addRow(rowThree);
           figTable.setModel(model);
           /*rowOne.remove(0);
           rowTwo.remove(0);
           rowThree.remove(0);*/
           result2=-1;
          
          
       }
       else if(result3==0){
          
           /*rowOne.remove(0);
           rowTwo.remove(0);
           rowThree.remove(0);
           model.getDataVector().removeAllElements();
           model.fireTableDataChanged();*/
           Triangle triangle1 = new Triangle(20, 30);
           areaT1 = triangle1.area();
           Triangle triangle2 = new Triangle(20, 30);
           areaT2 = triangle2.area();
           Triangle triangle3 = new Triangle(20, 30);
           areaT3 = triangle3.area();
           Rectangle rect1 = new Rectangle(10, 20);
           areaR1 = rect1.area();
           Rectangle rect2 = new Rectangle(11, 21);
           areaR2 = rect2.area();
           Rectangle rect3 = new Rectangle(12, 22);
           areaR3 = rect3.area();
           rowOne.add("Triangle 1");
           rowOne.add(" " + triangle1.getDim1());
           rowOne.add(" " + triangle1.getDim2());
           rowOne.add(" ");
           rowOne.add(" ");
           rowOne.add(" " + areaT1);
           model.addRow(rowOne);
           figTable.setModel(model);
           rowTwo.add("Triangle 2");
           rowTwo.add(" " + triangle1.getDim1());
           rowTwo.add(" " + triangle2.getDim2());
           rowTwo.add(" ");
           rowTwo.add(" ");
           rowTwo.add(" " + areaT2);
           model.addRow(rowTwo);
           figTable.setModel(model);
           rowThree.add("Triangle 3");
           rowThree.add(" " + triangle3.getDim1());
           rowThree.add(" " + triangle3.getDim2());
           rowThree.add(" ");
           rowThree.add(" ");
           rowThree.add(" " + areaT3);
           model.addRow(rowThree);
           figTable.setModel(model);
           /*rowOne.remove(0);
           rowTwo.remove(0);
           rowThree.remove(0);*/
           result3=-1;
         
          
       }
       /* DefaultTableModel model = new DefaultTableModel(new Object[]{"1","2","3"},0  ); 
JScrollPane scrollPane = new JScrollPane(table);
TableEg() {
  Vector<String> rowOne = new Vector<String>();
    rowOne.addElement("Row1-Column1");
    rowOne.addElement("Row1-Column2");
    rowOne.addElement("Row1-Column3");
    model.addRow(rowOne);
  
    Vector<String> rowTwo = new Vector<String>();
    rowTwo.addElement("Row2-Column1");
    rowTwo.addElement("Row2-Column2");
    rowTwo.addElement("Row2-Column3");
    model.addRow(rowTwo);
 
    table.setModel(model);*/
  
    }                                     

    private void cBoBoxActionPerformed(java.awt.event.ActionEvent evt) {                                      
        // TODO add your handling code here:
        cBoBoxItem = cBoBox.getSelectedItem().toString();
    }                                     

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {                                        
        // TODO add your handling code here:
        rowOne.removeAllElements();
        rowTwo.removeAllElements();
        rowThree.removeAllElements();
        //model.fireTableDataChanged();
        Object obj=model.getValueAt(0, 0);
        model.removeRow(0);
        //model.removeRow(1);
        //model.removeRow(2);
        //figTable.setModel(model);*/
       
    }                                       

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(FigureInheritanceJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(FigureInheritanceJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(FigureInheritanceJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(FigureInheritanceJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new FigureInheritanceJFrame().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify                    
    private javax.swing.JButton btnADT;
    private javax.swing.JComboBox<String> cBoBox;
    private javax.swing.JTable figTable;
    private javax.swing.JButton jButton1;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JScrollPane jScrollPane1;
    // End of variables declaration                  
}

Plz check the above code & tell me the prob with it. Thanks for your time.
God bless you.

Zulfi.
 
  • #8
Have you noticed what happens when yout try these steps?

Select something like circle from the dropdown and then Add Data in Table.
Select Clean to get the error.
Select something else from the dropdown like triangle.
Select Add Data in Table again.
 
Last edited:
  • #9
Hi,
Select something like circle from the dropdown and then Add Data in Table. (Circle added in the table)
Select Clean to get the error. (Clean: ArrayIndex out of Bound Exception)
Select something else from the dropdown like triangle. (Triangle)
Select Add Data in Table again. (Triangle data added in the table)

So how to get rid of this Array Index out of Bound Exception?

Zulfi.
 
  • #10
zak100 said:
Hi,
Select something like circle from the dropdown and then Add Data in Table. (Circle added in the table)
Select Clean to get the error. (Clean: ArrayIndex out of Bound Exception)
Select something else from the dropdown like triangle. (Triangle)
Select Add Data in Table again. (Triangle data added in the table)

So how to get rid of this Array Index out of Bound Exception?

Zulfi.
You are attempting to access a table cell after you've cleared all of the rows. Would you really expect anything to exist at that point?
 
  • #11
Hi<
In the handler for clean button, I had :
rowOne.removeAllElements();
rowTwo.removeAllElements();
rowThree.removeAllElements();
//model.fireTableDataChanged();
//model.removeRow(0);

I have commented the last two statements. Now i am not getting any Exception. I have removed the table data from memory but table data is still visible on screen. Also i was doing removal of data to avoid repetation of data but it still coming up. So now i have two problems:
i) How to remove the table data from screen ?
ii) After pressing clear if i select any other figure from ComboBox like Circle, i get 6 lines of data in the table of which last 3 are replication of first 3. I don't want data replication and any excess data. This is wrong. I should get only 3 lines. Please guide me.

Zulfi.
 
Last edited:
  • #12
In your btnADTActionPerformed() and jButton1ActionPerformed() methods, you are updating the row1, row2 and row3 variables which exist at the class level. The latter method just clears the data in the row variables instead of removing the references in the model. It also doesn't refresh the model so that you can see the changes.

The first method isn't replacing the previously added rows in the model, it is adding three new references to the row variables so that you are seeing what appears to be a new set of those variables in your table every time you select the btnADT button. This highlights the problem with declaring those variables at the class level instead of within the btnADTActionPerformed() method. What you are really seeing is references to the same three records added to the table over and over so that when you 'clear' the rows you are really just updating the records that are referenced multiple times in your table. You need to actually remove the referenced records from the model instead of just clearing the data in the row1, row2 and row3 variables.
 
  • #13
Hi,
I have used the :
model.setRowCount(0);
It removes the table contents from screen but let's suppose that it removed the contents related to 3 rectangles from the table but when when i select circle from combo box, instead of printing information about circle it again displays the same information about rectangle in the table which i actually deleted earlier.
<
You need to actually remove the referenced records from the model>

Please tell me the command regarding this.

Zulfi.
 

What is a JTable?

A JTable is a graphical user interface component in Java that displays data in a tabular format, similar to a spreadsheet. It consists of rows and columns, and can be customized to allow users to edit or manipulate the data.

Why is it difficult to remove elements from a JTable?

Removing elements from a JTable can be difficult because JTables are designed to display data from a specified data model. This means that the data is not directly stored in the table, but rather in the underlying data model. Therefore, removing elements from the table may require updating the data model as well.

How can I remove elements from a JTable?

To remove elements from a JTable, you will first need to get the selected row or rows from the table. Then, you can use the removeRow() method from the JTable's data model to remove the selected row(s). Finally, you will need to call the fireTableDataChanged() method to notify the table that the data has changed.

What if I want to remove all elements from a JTable?

If you want to remove all elements from a JTable, you can use the setRowCount() method from the JTable's data model to set the number of rows to 0. This will effectively remove all elements from the table. Again, don't forget to call the fireTableDataChanged() method to notify the table of the changes.

Can I remove elements from a JTable without updating the data model?

No, it is not recommended to remove elements from a JTable without updating the data model. This can cause inconsistencies between the data displayed in the table and the actual data in the model. It is best to always update the data model when making changes to a JTable.

Similar threads

  • Programming and Computer Science
Replies
6
Views
4K
  • Programming and Computer Science
Replies
7
Views
3K
Back
Top