Problem removing rows from JTable

Hello,
I'm having an issue with a JTable that I'm using. At one point in my application, I want to remove all the rows from the table and regenerate them (from a database). When I try to remove the rows and do nothing else, they remain in the table. The rows are being removed from the model, as I have verified this in code, but the display does not refresh at all.
I am using custom renderers to change the background color of a cell based on its value, and I disabled them to see if that was the problem, but alas, it is not.
Any suggestions or ideas why this may be occurring?

I am using model.setRowCount(0); to clear the model, however the display never refreshes. Then you are doing something wrong because its that simple. Only a single line of code is required.
Perhaps I should have included this in my original post.Actually, you should have included demo code in your original post. That way we don't have to guess what you are doing.
If you need further help then you need to create a [url http://homepage1.nifty.com/algafield/sscce.html]Short, Self Contained, Compilable and Executable, Example Program (SSCCE) that demonstrates the incorrect behaviour, because I can't guess exactly what you are doing based on the information provided.
And don't forget to use the [url http://forum.java.sun.com/help.jspa?sec=formatting]Code Formatting Tags so the code retains its original formatting.

Similar Messages

  • White patch after removing row from JTable

    I am working with JTable and removing item from table on clicking on button but after removing row there is white Patch on that row. I don�t want to show this white patch.
    I did repaint table but that is also not working.
    Any thoughts !!!!!!!

    javax.swing.SwingUtilities.invokeLater(new Runnable(){
                public void run(){
                  museTable.setBackground(Color.black);//your color here
              });

  • Remove row from JTable

    I have a JTable, and after selecting a row of the JTable a dialog opens for me to perform an action. But when I close the dialog I want that the row I have selected has disapeared, that means that I want to refresh the view removing the selected row. How can I do this?

    DefaultTableModel.removeRow(...);

  • How to remove a row from JTable

    Hi!
    I'm used to remove rows from JTables getting the model and doing a removeRow(num) like this:
    ((DefaultTableModel)jTable1.getModel()).removeRow(0);
    But with ADF and JDeveloper the model says it's a JUTableBinding.JUTableModel but its not accessible.
    How to remove a row in Jdeveloper 10.1.3.4.0?

    Or maybe is just better to refresh data in the jTable but I do not know either like doing it.

  • Add and remove columns from JTable

    Help me please!
    A try to remove column from JTable. It's removed, but when I try to add column in table, then I get all old (removed early) columns + new column....
    I completely confused with it.....
    Here is my code for remove column:
    class DelC implements ActionListener
              public void actionPerformed (ActionEvent e )
                   int [] HowManyColDelete = table.getSelectedColumns();
                   if (HowManyColDelete.length !=0)
                        TableColumnModel tableCModel = table.getColumnModel();
                        for (int i = HowManyColDelete.length-1; i>-1; i--)
                             table.getColumnModel().removeColumn (tableCModel.getColumn (HowManyColDelete [ i ]));
                   else
                          JOptionPane.showMessageDialog(JOptionPane.getRootFrame(), "Column is not selected!");
         }

    It's little ex for me, I just try understand clearly how it's work (table models i mean). Here is code. All action with tables take place through menu items.
    My brain is boiled, I've try a lot of variants of code, but did't get right result :((
    It's code represent problem, which I've describe above. If you'll try remove column and then add it again, it will be ma-a-a-any colunms...
    I understand, that my code just hide columns, not delete from table model....
    But now I have not any decision of my problem...
    Thanks a lot for any help. :)
    import javax.swing.*;
    import java.awt.*;
    import javax.swing.table.*;
    import java.awt.event.*;
    import javax.swing.table.DefaultTableModel;
    class JTableF extends JFrame
         Object [] [] data = new Object [0] [2];
         JTable table;
         DefaultTableModel model;
         String [] columnNames = {"1", "2"};
         TableColumnModel cm;
         JTableF()
              super("Table features");
              setDefaultLookAndFeelDecorated( true );
              setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
              JMenuBar MBar = new JMenuBar();
              JMenu [] menus =  {new JMenu("A"), new JMenu("B")};
              JMenuItem [] menu1 =  {new JMenuItem("Add row"), new JMenuItem("Delete row", 'D'),  new JMenuItem("Add column"), new JMenuItem("Delete column")};
              menu1 [ 0 ].addActionListener(new AddL());
              menu1 [ 1 ].addActionListener(new DelL());
              menu1 [ 2 ].addActionListener(new AddC());
              menu1 [ 3 ].addActionListener(new DelC());
              for (int i=0; i<menu1.length; i++)
                   menus [ 0 ].add( menu1 [ i ]);
              for (int i=0; i<menus.length; i++)
                   MBar.add(menus );
              JPanel panel = new JPanel ();
              model = new DefaultTableModel( data, columnNames );
              table = new JTable (model);
              cm = table.getColumnModel();
              panel.add (new JScrollPane(table));
              JButton b = new JButton ("Add row button");
              b.addActionListener(new AddL());
              panel.add (b);
              setJMenuBar (MBar);
              getContentPane().add(panel);
              pack();
              setLocationRelativeTo (null);
              setVisible (true);
         class DelC implements ActionListener
              public void actionPerformed (ActionEvent e )
                   int [] HowManyColDelete = table.getSelectedColumns();
                   if (HowManyColDelete.length !=0)
                        TableColumnModel tableCModel = table.getColumnModel();
                        for (int i = HowManyColDelete.length-1; i>-1; i--)
                             int vizibleCol = table.convertColumnIndexToView(HowManyColDelete [ i ]);
                             tableCModel.removeColumn (tableCModel.getColumn (vizibleCol));
                        //cm = tableCModel;
                   else
                        JOptionPane.showMessageDialog(JOptionPane.getRootFrame(), "Column is not selected!");
         class AddC implements ActionListener
              public void actionPerformed (ActionEvent e)
                   //table.setColumnModel(cm);
                   Object NewColumnName = new String();
                   NewColumnName = JOptionPane.showInputDialog ("Input new column name", "Here");
                   int i = model.getRowCount();
                   int j = model.getColumnCount();
                   Object [] newData = new Object [ i ];
                   model.addColumn ( NewColumnName, newData);
         class AddL implements ActionListener
              public void actionPerformed (ActionEvent e)
                   int i = model.getColumnCount();
                   Object [] Row = new Object [ i ];
                   model.addRow ( Row );
         class DelL implements ActionListener
              public void actionPerformed (ActionEvent e)
                   int [] HowManyRowsDelete = table.getSelectedRows();
                   if (HowManyRowsDelete.length !=0)
                        for (int k = HowManyRowsDelete.length-1; k>-1; k--)
                             model.removeRow (HowManyRowsDelete[k]);
                   else
                        JOptionPane.showMessageDialog(JOptionPane.getRootFrame(), "Row is not selected!");
         public static void main (String [] args)
              javax.swing.SwingUtilities.invokeLater(new Runnable()
                   public void run()
                        JTableF inst = new JTableF();

  • Add/remove rows in jTable

    Hello,
    I'm writing an application with Sun ONE Studio 4. The autogenerated code for a JTable is something like: jTable1.setModel(new javax.swing.table.DefaultTableModel...
    How can I add / remove rows from this table? In principle it should work like this: model.removeRow(0); But I don't have a model name in the autogenerated code.
    Thanks for your help, Elke

    DefaultTableModel model = (DefaultTableModel)<table>.getModel();
    model.doWhateverYouWant();
    Cheers,
    Ram

  • Store a reference to a row from JTable

    Hello everyone!
    Me and my school mates are working on a project for a peer to peer application for the school. For file sending we wrote a class that extends Thread. We have a JTable to represent the downloading files. If the mentioned class for sending a file is created, I want to store into it's instance a reference to a row from the JTable. So I can always edit the cell in the tables row that represents the progress of downloading. Until now we were accessing the proper tables row over the rows index. But if we delete some rows from the table (we wand to remove finished downloads), the indexes get mixed up.
    I know that .NET has a class that represents a single row in the table. I would like to store the instance of a row in my class that downloads the file in my Java project.
    Thanks for further help!
    Regards.

    I know that .NET has a class that represents a single row in the table.
    I would like to store the instance of a row in my class that downloads the file in my Java project.You need to create a custom TableModel that stores an Object containing the row information.
    Here is a basic shell to get you started:
    http://forum.java.sun.com/thread.jspa?forumID=57&threadID=610618
    You will need to add method to add/remove rows from the model. You will then need to search the TableModel to find the Object in order to determined which row to update.

  • Hi I am having problems removing mail from trash folder. Can anyone help please

    Hi I am having problems removing mail from trash folder. I can send mails to the folder but cannot delete them permanently from the trash folder. I am using Iphone 3G and anm up to date with OS. Can anyone help please

    Check that there isn't a different Trash folder to the one with the proper Trash symbol on it.
    If you see one in your list of folders rather than a separate one, highlight it, then click on Mailbox...Use this mailbox for...Trash

  • I am having problem removing sim from E51

    I have problems removing sim from my E51. it seems. its very tight there.

    Did you already try these steps?
    Restart the iPhone.
    Try another means of reaching the activation server and attempt to activate.
    Try connecting to a known-good Wi-Fi network if you're unable to activate using a cellular data connection.
    Try connecting to iTunes if you're unable to activate using Wi-Fi.
    Restore the iPhone.
    If you receive an alert message when you attempt to activate your iPhone, try to place the iPhone in recovery mode and perform a restore. If you're still unable to complete the setup assistant due to an activation error, contact Apple for assistance.
    copied from iOS: Troubleshooting activation issues

  • Having problems removing tags from script.

    I'm not using the browser to run Adobe Story, but the Desktop version from my iMac.  Cmd + Double Click works, but once every 30 times.  Is anyone else having this problem removing tags from a script?

    There are other ways to remove tags from a script
    From Tagging Panel:
    - Open Tagging Panel from View Menu
    - Click on Edit button. Here you have the option to delete individual tag-items or remove all from the scene.
    From File Menu
    - Open File - Tagging menu
    Here you will find the options to delete all/manually added/automatically added tags.

  • Temparally remove rows from a ADF table by action event of a jsf page.

    Hello Developers,
    I needed to temporally remove rows of a ADF table when execute action event of corresponding page.
    So in this case my task can describe by following steps,
    (1). I created a ADF table using <af:table> on a jsf page.
    (2). The data populated using a VO.
    (3). Several radio buttons added to the page for temporally remove rows from the table.
    This means one radio button check, it responsible to temporally remove rows which contain empty cell values of a identified column.
    If I check another radio button it should temporally remove identified data included rows but above removed (empty cell included rows) rows should appear in this event
    My ultimate target is temporally remove rows of a table & re call again removed rows another event without again & again query from BC.
    Pleas advice me to archive this task very sealy?
    (Are there have a way to do this using EL or coding in Manage bean ?)
    Thanks in advance..!

    Hi,
    the DCIterator gives you an option to iterate over the fetched rows (the ones you see in the table). You can try call removeAndRetain() on these rows. This will not remove or delete rows but allows you to insert these rows back to the collection.
    JavaDocs:
    * Removes the row from the collection and then retain it for insertion
    * into another location.
    * <p>
    * This method differs from <code>{@link #remove()}</code> in that
    * it just removes the row from the collection. It does not
    * remove the underlying Entity row(s) or database row(s).
    * <p>
    * This method also differs from <code>{@link #removeFromCollection()}</code>
    * in that after the row is removed from the collection, it can be inserted
    * back into the collection at another location.
    void removeAndRetain();
    Frank

  • Removing rows from a JTable

    How can i remove a row from a JTable??

    You need to extends AbstractTableModel rather than use DefaultTableModel as I think from memory this just uses an array to store data.
    If you use a vector in your subclass to store your rows, then you can do something like this:
        public boolean delete(int rowIndex)
            if (rowIndex < 0 || rowIndex >= rowVector.size())
                return false;
            else
                int day = 0;
                MyRowClass row = rowVector.get(rowIndex);
                rowVector.remove(rowIndex);
                rowCount--;
                fireTableRowsDeleted(rowIndex, rowIndex);
                return true;
        }HTH
    Paul C.

  • Delete rows from JTable

    Hello
    I use a JTable with a custom table model that extends javax.swing.table.DefaultTableModel.
    I haven't overwrote the method
    public void removeRow(int row)Now when i use this method the rows always get removed from the end. It doesn't matter which value the parameter row has.
    Even when i call
    myTableModel.removeRow( 0 );it removes the rows at the end of the table.
    It would be nice if someone could help me with this.
    Regards, Michelle

    It's not so easy to do this because it's a big project, but here is the code of the table model.
    import javax.swing.table.*;
    import javax.swing.event.TableModelEvent;
    import javax.swing.event.TableModelListener;
    import java.util.*;
    public class AssignmentsTableModel2 extends DefaultTableModel implements TableModelListener
         static final long serialVersionUID = 41L;
         public AssignmentsTableModel2(String[][] arg1, String[] arg2)
              super(arg1, arg2);
         public Vector getColumnIdentifiers()
              return columnIdentifiers;
         @Override
         public int getColumnCount()
              return this.columnIdentifiers.size();
         @Override
         public int getRowCount()
              return this.dataVector.size();
         @Override
         public String getColumnName(int col)
            return (String)this.columnIdentifiers.elementAt( col );
         @Override
         public Object getValueAt(int rowIndex, int columnIndex)
              return ((Vector)this.dataVector.elementAt( rowIndex )).elementAt( columnIndex );
         @Override
         public void setValueAt( Object val, int rowIndex, int columnIndex )
              ((Vector)this.dataVector.elementAt( rowIndex )).set( columnIndex, val);
              fireTableCellUpdated( rowIndex, columnIndex );
         @Override
         public void tableChanged(TableModelEvent e)
         @Override
         public void setColumnIdentifiers(Vector columnIdentifiers)
              super.setColumnIdentifiers(columnIdentifiers);
         @Override
         public void removeRow(int row)
              this.dataVector.remove(row);
              System.out.println(row + " to remove");
              this.fireTableStructureChanged();
              //super.removeRow(row);
    }I need the model to change the background color of the cells at runtime and I now overwrote the removeRow() method, but it's still the same problem.
    Also I have a custom JTable class that colours the TableHeader of the selected column.
    class PaintedTable extends JTable {
        private static final long serialVersionUID = 1L;
        PaintedTable(AssignmentsTableModel2 atm)
            super(atm);
            setOpaque(false);
            ((JComponent) getDefaultRenderer(Object.class)).setOpaque(false);
        @Override
        public void paintComponent(Graphics g)
             //System.out.println("paint table");
            Color background = new Color(168, 210, 241);
            Color controlColor = new Color(230, 240, 230);
            int width = getWidth();
            int height = getHeight();
            Graphics2D g2 = (Graphics2D) g;
            Paint oldPaint = g2.getPaint();
            g2.setPaint(new GradientPaint(0, 0, background, width, 0, controlColor));
            g2.fillRect(0, 0, width, height);
            g2.setPaint(oldPaint);
            for (int row : getSelectedRows())
                Rectangle start = getCellRect(row, 0, true);
                Rectangle end = getCellRect(row, getColumnCount() - 1, true);
                g2.setPaint(new GradientPaint(start.x, 0, Color.orange, (int) ((end.x + end.width - start.x) * 1.25), 0, controlColor));
                g2.fillRect(start.x, start.y, end.x + end.width - start.x, start.height);
                //System.out.println("rect: (" + start.x + ", " + start.y + ") + (" + (end.x + end.width - start.x) + ", " + start.height +")");
            super.paintComponent(g);
        public boolean isCellEditable(int rowIndex, int colIndex)
            return false;  
    AssignmentsTableModel2 atm = new AssignmentsTableModel2(this.columnValues, this.columnHeaders);     
    PaintedTable table = new PaintedTable( this.atm );

  • Deleting a row from JTable

    I am trying to delete a row from a JTable whenever the button on the last column is pressed. I know to do this, I can use the removeRow(int) method of the tableModel. But the odd thing is when I try to get a handle to the TableModel from the JTable to use that function, i.e. table.getModel().removeRow(int) it doesn't work. But if I explicitly pass in the tableModel into my class it does work. Here's the code below:
    import java.awt.*;
    import java.awt.event.*;
    import java.util.*;
    import javax.swing.*;
    import javax.swing.table.*;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import javax.swing.UIManager;
    import javax.swing.table.TableCellRenderer;
    import javax.swing.table.TableCellEditor;
    import javax.swing.AbstractCellEditor;
    import javax.swing.table.DefaultTableModel;
    public class tester4 extends JFrame
         protected final int BUTTON_COL = 2;
         private TableCellRenderer defaultRenderer;
         private TableCellEditor defaultEditor;
         private JTable workingTable;
         private String[] transactionCols = {"Qty", "Product", "Cancel"};
         private Object[][] data = {{5, "prod1", "Cancel"},
                   {6, "prod2", "Cancel"},
                   {7, "prod3", "Cancel"}};
        public tester4()
              workingTable = new JTable(tableModel);
              workingTable.setName("Working Table");
              defaultRenderer = workingTable.getDefaultRenderer(JButton.class);
              defaultEditor = workingTable.getDefaultEditor(Object.class);
              StatusTableRenderer testRenderer = new StatusTableRenderer(defaultRenderer, defaultEditor, workingTable, tableModel);
              workingTable.setDefaultRenderer(Object.class, testRenderer);
              workingTable.setDefaultEditor(Object.class, testRenderer);
            JScrollPane scrollPane = new JScrollPane( workingTable );
            getContentPane().add( scrollPane );
         private DefaultTableModel tableModel = new DefaultTableModel(data, transactionCols){
              // Only allow button column to be editable, if there is an actual
              // button in that row          
              public boolean isCellEditable(int row, int col){
                   return (col == BUTTON_COL && data[row][col] != "") ? true : false;
              // Overriden getColumnClass method that will return the object
              // class type of the first instance of the data type otherwise
              // returns the Object.class
              public Class getColumnClass(int column){
                for (int row = 0; row < getRowCount(); row++){
                    Object o = getValueAt(row, column);
                    if (o != null){ return o.getClass(); }
                return Object.class;
        public static void main(String[] args)
            tester4 frame = new tester4();
            frame.setDefaultCloseOperation( EXIT_ON_CLOSE );
            frame.pack();
            frame.setVisible(true);
        public class StatusTableRenderer extends AbstractCellEditor
                                                implements TableCellRenderer,
                                                               TableCellEditor,
                                                               ActionListener{
             private TableCellRenderer defaultRenderer;
             private TableCellEditor defaultEditor;
             private JButton cancelButton;
             private JButton editButton;
             private String text;
             private int buttonColumn;
             private int selectedRow;
             private JTable table;
             private DefaultTableModel tableModel;
             public StatusTableRenderer(TableCellRenderer renderer,
                                           TableCellEditor editor,
                                           JTable table,
                                           DefaultTableModel tableModel){
                  defaultRenderer = renderer;
                  defaultEditor = editor;
                  this.table = table;
                  this.tableModel = tableModel;
                  buttonColumn = table.getColumnCount() - 1;
                cancelButton = new JButton();
                editButton = new JButton();
                editButton.setFocusPainted(true);
                editButton.addActionListener(this);
             public StatusTableRenderer(TableCellRenderer renderer,
                                                TableCellEditor editor,
                                                JTable table,
                                                DefaultTableModel tableModel,
                                                int _buttonColumn){
                  this(renderer, editor, table, tableModel);
                  buttonColumn = _buttonColumn;
             public Component getTableCellRendererComponent(JTable table, Object value,
                       boolean isSelected, boolean hasFocus, int row, int column) {
                  if (column == buttonColumn){
                       if (hasFocus){
                            cancelButton.setForeground(table.getForeground());
                            cancelButton.setBackground(UIManager.getColor("Button.background"));
                       else if (isSelected){
                            cancelButton.setForeground(table.getSelectionForeground());
                            cancelButton.setBackground(table.getSelectionBackground());
                       else{
                            cancelButton.setForeground(table.getForeground());
                            cancelButton.setBackground(UIManager.getColor("Button.background"));
                       cancelButton.setText( (value == null) ? "" : value.toString() );
                       return cancelButton;
                return defaultRenderer.getTableCellRendererComponent(
                            table, value, isSelected, hasFocus, row, column);
             public Component getTableCellEditorComponent(JTable table, Object value,
                       boolean isSelected, int row, int column){
                  if (column == buttonColumn){
                       text = ((value == null) ? "": value.toString());
                       editButton.setText(text);
                       selectedRow = row;
                       return editButton;
                  return defaultEditor.getTableCellEditorComponent(
                            table, value, isSelected, row, column);
            public Object getCellEditorValue()
                return text;
            public void actionPerformed(ActionEvent e)
                fireEditingStopped();
                // This works
                tableModel.removeRow(selectedRow);
               // This does not work
              //  table.getModel().removeRow(selectedRow);
    }Take a look at the actionPerfformed method. One way of doing it works, one doesn't. Just trying to understand why me getting a handle to the tableModel through the table doesn't work.
    Message was edited by:
    deadseasquirrels

    It gives me a run-time error Well then your question should be "why do I get this run-time error" and then you would quote the error. Be more descriptive. "It doesn't work" is not descriptive.
    table.getModel().removeRow(selectedRow);I don't use JDK1.5 either. But if you are saying that the above line compiles cleanly with JDK1.5 (because of the auto-boxing feature, or whatever its called), then I see no reason why the code wouldn't work since it recognizes the class as a DefaultTableModel.
    Presumably you commented out the other line so you don't try to delete the row twice. Otherwise you might be getting a indexing error.

  • Problem removing components from JLayeredPane

    Hi all,
    I have a problem showing and hiding components on a JLayeredPane. It goes Something like this:
    In my application I have a button. When this button is pressed I use getLayeredPane to get the frames layered pane. I then add a JPanel containing a number of labels and buttons onto that layered pane on the Popup layer. The panel displays and funcitons correctly.
    The problem comes when I try to remove the panel from the layered pane. The panel does not dissappear and I am no longer able to click on anything else in the frame!
    If anyone has any ideas how to get around this or what the problem might be I'd be very greatful to hear it. Sample code follows:
          * Called when the button on the frame is pressed:
          * @param e
         public void actionPerformed(ActionEvent e)
                    JLayeredPane mLayredPane = getLayeredPane();
              int x = 0, y = 0;
              Container c = this;
              while (true)
                   c = c.getParent();
                   if (c != null)
                        x += c.getLocation().x;
                        y += c.getLocation().y;
                        if (c instanceof JRootPane)
                             break;
                   else
                        break;
              mPanel.setBounds(x, y, 235, 200);
              mLayredPane.add(mPanel, JLayeredPane.POPUP_LAYER);
    //And when a listener fires from the panel I use
    mLayredPane.remove(mPanel);
    //To remove it from the layered pane and in theory return the
    //app to the state it was before the panel was displayedThanks again...

    The problem is you only removed it within the program, without actually removing it from the display. If that makes any sense, or whether thats your problem at all.
    If you are only using this line.
    mLayredPane.remove(mPanel);
    I think if you tell it to repaint and revalidate it should work, though i have never used LayeredPane.
    mLayredPane.repaint();
    mLayredPane.revalidate();

Maybe you are looking for

  • I can't start halo for mac

    Hi, I having some problems with halo for mac. I have a intel duel core mac with windows installed. I have been playing halo for some time now, but about 3 weeks ago I quit for a week. In this time I installed America's Army (the game developed by the

  • Business Components and Database Views - Trouble Creating

    I am trying to create a business component that contains a View that I created in my database. When I get to the fnnal step of creating the business component and it begins to generate the XML and Java code, it bombs out and says that the view object

  • Get customer invoice address from one time vendor

    Hi All, I am working on cheque printing. I have a question with in that.Customer wants if Vendor is one time vendor. I can identify the one  time vendor using 'LFA1-XCPDK  is 'X'  then the customer invoice assress priting in screen How can identify t

  • SENT MAIL NOT APPEARING IMAIL

    I have had the same gmail account for nearly 7 years. I have always used it with the apple mail program (IMAP). Suddenly in the last couple of days my sent mail has totally vanished (except for nearly 300 messages that seem to be pretty much just fro

  • Forms Builder 6i and 9i

    Currently, we have many existing applications that were written using Forms Builder 6i as client/server apps. I need to install Developer9i (Forms) so that I can do a proof of concept that we can do new application development using 9i while being ab