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
          });

Similar Messages

  • 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.

  • 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

  • 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

  • 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.

  • Can't delete a file displayed in ListView ("File in use") even after removing it from window.

    I have a ListView displaying a collection of icons. The user can then select different icons (checkboxes) to do things like Copy or Delete.
    Problem is, when I try to delete the actual file from the disk, I get an error telling me the file is "in use" ("vshost.exe", the VS runtime during testing).
    I thought maybe it was because it still appeared in the window and was still in the ImageList, but even after removing it from both locations, I still get the error. My code:
    Dim intCnt As Integer = 0
    Do
    ImageList2.Images.RemoveAt(intIconsChecked(intCnt)) ' Remove from collection.
    lsvCollection.Items.RemoveAt(intIconsChecked(intCnt)) ' Remove from ListView window.
    FileIO.FileSystem.DeleteFile(strIconPath & "\Icon" & Format(intCnt + 1, "00") & ".rsc") ' "+1" b/c Icons start with "01".
    FileIO.FileSystem.DeleteFile(strIconPath & "\Icon" & Format(intCnt + 1, "00") & ".png") ' "In use" Error here.
    ".rsc" deletes just fine, so I know I'm deleting the correct file. Why does VS still think the file is still "in use"?
    Thx

    Mugsy,
    Consider this as food for thought, even if you don't use it.
    If you set it up right then you can control how it works. A reference is a reference and any left behind will cause you grief down the road when you try to delete things.
    As an example, a simple class follows. It does *not* implement IDispose, although it does have a private shared Dispose method in it:
    Public Class MyImages
    Private _bmp As Bitmap
    Private _name As String
    Private _sourceFilePath As String
    Private Sub New(ByVal bmp As Bitmap, _
    ByVal name As String, _
    ByVal filePath As String)
    _bmp = bmp
    _sourceFilePath = filePath.Trim
    _name = name.Trim
    End Sub
    Public ReadOnly Property Bmp As Bitmap
    Get
    Return _bmp
    End Get
    End Property
    Public ReadOnly Property Name As String
    Get
    Return _name
    End Get
    End Property
    Public ReadOnly Property SourceFilePath As String
    Get
    Return _sourceFilePath
    End Get
    End Property
    Public Shared Sub AddNew(ByRef miList As List(Of MyImages), _
    ByVal imageFilePath As String)
    Try
    If miList Is Nothing Then
    Throw New ArgumentNullException("The collection of MyImages cannot be null.")
    ElseIf String.IsNullOrEmpty(imageFilePath) OrElse imageFilePath.Trim = "" Then
    Throw New ArgumentException("The file path of the image cannot be null or empty.")
    ElseIf Not My.Computer.FileSystem.FileExists(imageFilePath) Then
    Throw New IO.FileNotFoundException("The file path of the image could not be located.")
    Else
    ' Should do validation here that the file
    ' is actually an image but I'll not do this
    ' here...
    Dim thisBMP As Bitmap = New Bitmap(imageFilePath)
    miList.Add(New MyImages(thisBMP, GetFileNameWithoutExtension(imageFilePath), imageFilePath))
    End If
    Catch ex As Exception
    Throw
    End Try
    End Sub
    Public Shared Sub AddNew(ByRef miList As List(Of MyImages), _
    ByVal imageFilePath As String, _
    ByVal imageName As String)
    Try
    If miList Is Nothing Then
    Throw New ArgumentNullException("The collection of MyImages cannot be null.")
    ElseIf String.IsNullOrEmpty(imageFilePath) OrElse imageFilePath.Trim = "" Then
    Throw New ArgumentException("The file path of the image cannot be null or empty.")
    ElseIf Not My.Computer.FileSystem.FileExists(imageFilePath) Then
    Throw New IO.FileNotFoundException("The file path of the image could not be located.")
    ElseIf String.IsNullOrEmpty(imageName) OrElse imageName.Trim = "" Then
    Throw New ArgumentException("The name of this image cannot be null or empty.")
    Else
    ' Should do validation here that the file
    ' is actually an image but I'll not do this
    ' here...
    Dim thisBMP As Bitmap = New Bitmap(imageFilePath)
    miList.Add(New MyImages(thisBMP, imageName, imageFilePath))
    End If
    Catch ex As Exception
    Throw
    End Try
    End Sub
    Public Shared Sub Remove(ByRef miList As List(Of MyImages), _
    ByVal imageFilePath As String, _
    Optional ByVal removeFilePathAlso As Boolean = False)
    Try
    If miList Is Nothing Then
    Throw New ArgumentNullException("The collection of MyImages cannot be null.")
    ElseIf String.IsNullOrEmpty(imageFilePath) OrElse imageFilePath.Trim = "" Then
    Throw New ArgumentException("The file path of the image cannot be null or empty.")
    ElseIf Not My.Computer.FileSystem.FileExists(imageFilePath) Then
    Throw New IO.FileNotFoundException("The file path of the image could not be located.")
    Else
    Dim findInstance As System.Collections.Generic.IEnumerable(Of MyImages) = _
    From mi As MyImages In miList _
    Where mi.SourceFilePath = imageFilePath
    If findInstance.Count <> 1 Then
    Throw New ArgumentException("The instance of MyImages specified by the" & vbCrLf & _
    "image file path is not in the collection.")
    Else
    Dispose(findInstance.First)
    If removeFilePathAlso Then
    My.Computer.FileSystem.DeleteFile(findInstance.First.SourceFilePath)
    End If
    miList.Remove(findInstance.First)
    End If
    End If
    Catch ex As Exception
    Throw
    End Try
    End Sub
    Private Shared Sub Dispose(ByVal instance As MyImages)
    If instance IsNot Nothing AndAlso instance._bmp IsNot Nothing Then
    instance._bmp.Dispose()
    instance._bmp = Nothing
    End If
    End Sub
    End Class
    When you look through that, look specifically at the "Remove" method and in particular, look at the order in which things are done. That's the critical part in this.
    I tested it with a simple form:
    Two buttons, a checkbox, and a picturebox. I also copied a small folder full of image files to my desktop since I'll be deleting a file from it. Following is the code for Form1:
    Option Strict On
    Option Explicit On
    Option Infer Off
    Imports System.IO.Path
    Public Class Form1
    Private miList As New List(Of MyImages)
    Private Sub Form1_Load(ByVal sender As System.Object, _
    ByVal e As System.EventArgs) _
    Handles MyBase.Load
    Dim desktop As String = _
    My.Computer.FileSystem.SpecialDirectories.Desktop
    Dim imgFolder As String = _
    Combine(desktop, "Images")
    PictureBox1.BorderStyle = BorderStyle.FixedSingle
    For Each imgFilePath As String In My.Computer.FileSystem.GetFiles(imgFolder)
    MyImages.AddNew(miList, imgFilePath)
    Next
    btn_RemoveFirstImage.Enabled = False
    CheckBox_RemoveSourcePath.Enabled = False
    End Sub
    Private Sub btn_ShowFirstImage_Click(sender As System.Object, _
    e As System.EventArgs) _
    Handles btn_ShowFirstImage.Click
    Try
    If miList.Count >= 1 Then
    With PictureBox1
    .SizeMode = PictureBoxSizeMode.Zoom
    .Image = miList(0).Bmp
    End With
    btn_RemoveFirstImage.Enabled = True
    CheckBox_RemoveSourcePath.Enabled = True
    End If
    Catch ex As Exception
    MessageBox.Show(String.Format("An exception was thrown:{0}{0}{1}", vbCrLf, ex.Message), _
    "Exception", MessageBoxButtons.OK, MessageBoxIcon.Warning)
    End Try
    End Sub
    Private Sub btn_RemoveFirstImage_Click(sender As System.Object, _
    e As System.EventArgs) _
    Handles btn_RemoveFirstImage.Click
    Try
    If miList.Count >= 1 Then
    MyImages.Remove(miList, miList(0).SourceFilePath, CheckBox_RemoveSourcePath.Checked)
    End If
    PictureBox1.Image = Nothing
    btn_RemoveFirstImage.Enabled = True
    CheckBox_RemoveSourcePath.Enabled = True
    Catch ex As Exception
    MessageBox.Show(String.Format("An exception was thrown:{0}{0}{1}", vbCrLf, ex.Message), _
    "Exception", MessageBoxButtons.OK, MessageBoxIcon.Warning)
    End Try
    End Sub
    End Class
    Running it is straightforward:
    Now when I click to show the first one:
    A different image is shown because that first one no longer exists - either in the collection or in the folder.
    Closing/disposing all references is the key and the order matters.
    Something to consider the next time around. :)
    Still lost in code, just at a little higher level.

  • I bought the student and teacher version of CS5 extended for windows. Can I download the Mac version to my new  apple computer  and use the same serial number after removing phtoshop from my PC?

    i bought the student and teacher version of CS5 extended for windows. Can I download the Mac version to my new  apple computer  and use the same serial number after removing phtoshop from my PC?

    Can I download the Mac version to my new  apple computer  and use the same serial number after removing phtoshop from my PC?
    Short answer: not for CS5.
    Platform swaps are available but only for CS6
    Order product | Platform, language swap

  • After removing virus from xp home. itunes gives error -50 when i try to open it

    after removing virus from xp home. itunes gives error -50 when i try to open it.

    Ah, the old jokes are still often the best ones, rIcHaRd ...
    The -50 in that context can indicate damage to your Apple Application Support. (Apple Application Support is where single copies of program files used by multiple different Apple programs are stashed.) So I'd first try a repair install of your Apple Application Support.
    Restart the PC. Head into your Add or Remove programs control, select "Apple Application Support", click "Change" and then click "Repair".
    Does the repair install go through okay? If so, does your iTunes start launching again?

  • 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.

  • How to remove empty lines from xml files after removing nodes from document

    <pre>
    Hi
    <b>i have xml document, which is shown below
    after removing some nodes from the document ,i am getting empty lines in place of removed nodes,how to resolve this and get the proper xml document without any errors</b>
    <?xml version="1.0" encoding="UTF-8" standalone="no"?>
    <!DOCTYPE Message SYSTEM "TRD01.dtd">
    <Message>
    <Header>
    <CounterPartyType>CLIENT</CounterPartyType>
    <CreationTime>20134455</CreationTime>
    <ErrorCode>363 </ErrorCode>
    <ErrorEnterPriseId>N</ErrorEnterPriseId>
    <ErrorStatus>1</ErrorStatus>
    <ErrorSystemId>STL</ErrorSystemId>
    <ErrorTimes>31</ErrorTimes>
    <MessageType>T</MessageType>
    <RecipientEnterpriseId>N</RecipientEnterpriseId>
    <RecipentSystemId>EXM</RecipentSystemId>
    <Remarks>REMARSK</Remarks>
    <SenderEnterpriseId>N</SenderEnterpriseId>
    <SenderSystemId>TR</SenderSystemId>
    </Header>
    </Message>
    <ErrorCode>363 </ErrorCode>
    <ErrorEnterPriseId>NIHK</ErrorEnterPriseId>
    <ErrorStatus>1</ErrorStatus>
    <ErrorSystemId>STL</ErrorSystemId>
    <ErrorTimes>31</ErrorTimes>
    XPathExpression expression5 = xpath.compile(xmlpath5);
    Object result5 = expression5.evaluate(doc, XPathConstants.NODE);
    Node node5 = (Node) result5;
    node5.getParentNode().removeChild(node5);
    XPathExpression expression6 = xpath.compile(xmlpath6);
    Object result6 = expression6.evaluate(doc, XPathConstants.NODE);
    Node node6=(Node) result6;
    node6.getParentNode().removeChild(node6);
    XPathExpression expression7 = xpath.compile(xmlpath7);
    Object result7 = expression7.evaluate(doc, XPathConstants.NODE);
    Node node7=(Node) result7;
    node7.getParentNode().removeChild(node7);
    doc.normalize();
    doc.normalizeDocument();
    TransformerFactory tf = TransformerFactory.newInstance();
    Transformer t = tf.newTransformer();
    t.setOutputProperty(OutputKeys.INDENT, "yes");
    t.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");
    t.setOutputProperty(OutputKeys.METHOD,"xml");
    t.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
    the xml output i am getting is
    <?xml version="1.0" encoding="UTF-8" standalone="no"?>
    <Message>
    <Header>
    <CounterPartyType>CLIENT</CounterPartyType>
    <CreationTime>20134455</CreationTime>
    <MessageType>TRD01</MessageType>
    <RecipientEnterpriseId>N</RecipientEnterpriseId>
    <RecipentSystemId>STL</RecipentSystemId>
    <Remarks>REMARSK</Remarks>
    <SenderEnterpriseId>N</SenderEnterpriseId>
    <SenderSystemId>T</SenderSystemId>
    </Header>
    </Message>
    <b>could you please let me know how to avoid empty lines in the xml doucment output</b>
    this is the method i am using to get the result
    public void ValidateRecord(String xml){
    try{
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    DocumentBuilder db = factory.newDocumentBuilder();
    //parse file into DOM
    /*DOMParser parser = new DOMParser();
    parser.setErrorStream(System.err);
    parser.setValidationMode(DTD_validation);
    parser.showWarnings(true);*/
    System.out.println ("HI THIS xml is validation "+xml);
    Resolver res = new Resolver();
    db.setEntityResolver(res);
    Document doc = db.parse(new InputSource(new StringReader(xml)));
    XPathFactory xpf = XPathFactory.newInstance();
    XPath xpath = xpf.newXPath();
    // XPathExpression expression = xpath.compile("//A/B[C/E/text()=13]");
    String xmlpath="/Message/Header/CounterPartyType/text()";
    String xmlpath1="/Message/Header/RecipentSystemId/text()";
    String xmlpath2="/Message/Header/ErrorSystemId/text()";
    XPathExpression expression = xpath.compile(xmlpath);
    XPathExpression expression1 = xpath.compile(xmlpath2);
    Object result = expression.evaluate(doc, XPathConstants.NODE);
    Object result1 = expression1.evaluate(doc, XPathConstants.NODE);
    Node node = (Node) result;
    Node node1 = (Node) result1;
    System.out.println("the values of the string is " +node.getNodeValue());
    System.out.println("the values of the string is " +node1.getNodeValue());
    // for (int i = 0; i < nodes.getLength(); i++) {
    //System.out.println(nodes.item(i).getNodeValue());
    // CAHNGING THE RECEIPENT NODE
    XPathExpression expression2 = xpath.compile(xmlpath1);
    Object result2 = expression2.evaluate(doc, XPathConstants.NODE);
    Node node2 = (Node) result2;
    System.out.println(node2);
    node2.setNodeValue(node1.getNodeValue());
    System.out.println(node2);
    //removing the nodes from document
    String xmlpath3="/Message/Header/ErrorCode";
    String xmlpath4="/Message/Header/ErrorEnterPriseId";
    String xmlpath5="/Message/Header/ErrorStatus";
    String xmlpath6="/Message/Header/ErrorSystemId";
    String xmlpath7="/Message/Header/ErrorTimes";
    XPathExpression expression3 = xpath.compile(xmlpath3);
    Object result3 = expression3.evaluate(doc, XPathConstants.NODE);
    Node node3 = (Node) result3;
    node3.getParentNode().removeChild(node3);
    XPathExpression expression4 = xpath.compile(xmlpath4);
    Object result4 = expression4.evaluate(doc, XPathConstants.NODE);
    Node node4 = (Node) result4;
    System.out.println("node value");
    System.out.println(node4.getParentNode().getNodeName());
    node4.getParentNode().removeChild(node4);
    XPathExpression expression5 = xpath.compile(xmlpath5);
    Object result5 = expression5.evaluate(doc, XPathConstants.NODE);
    Node node5 = (Node) result5;
    node5.getParentNode().removeChild(node5);
    XPathExpression expression6 = xpath.compile(xmlpath6);
    Object result6 = expression6.evaluate(doc, XPathConstants.NODE);
    Node node6=(Node) result6;
    node6.getParentNode().removeChild(node6);
    XPathExpression expression7 = xpath.compile(xmlpath7);
    Object result7 = expression7.evaluate(doc, XPathConstants.NODE);
    Node node7=(Node) result7;
    node7.getParentNode().removeChild(node7);
    // Node b13Node = (Node) expression.evaluate(doc, XPathConstants.NODE);
    //b13Node.getParentNode().removeChild(b13Node);
    doc.normalize();
    doc.normalizeDocument();
    TransformerFactory tf = TransformerFactory.newInstance();
    Transformer t = tf.newTransformer();
    t.setOutputProperty(OutputKeys.INDENT, "yes");
    t.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");
    t.setOutputProperty(OutputKeys.METHOD,"xml");
    t.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
    t.transform(new DOMSource(doc), new StreamResult(System.out));
    catch (Exception e) {
         e.printStackTrace();
    System.out.println(e.getMessage());
    </pre>
    Edited by: user12185243 on Apr 6, 2013 6:38 AM
    Edited by: user12185243 on Apr 6, 2013 6:41 AM
    Edited by: user12185243 on Apr 6, 2013 6:43 AM
    Edited by: user12185243 on Apr 6, 2013 6:45 AM
    Edited by: user12185243 on Apr 6, 2013 9:00 AM

    either this way we can do this
    1)
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    <b> factory.setIgnoringElementContentWhitespace(true); </b>
    DocumentBuilder db = factory.newDocumentBuilder();
    or
    2)
    java.io.StringWriter sw = new java.io.StringWriter();
    StreamResult sr = new StreamResult(sw);
    t.transform(new DOMSource(doc), sr);
    String xml1 = sw.toString().trim();
    <b> xml1=xml1.replaceAll("\\s",""); </b>
    System.out.println(xml1.trim());

Maybe you are looking for

  • XML parser working with MediaWiki API

    I have a little helper for a MediaWiki server. It intended to work the following way: Client side [GWT] ←rpc→ Server side [GWT] — JWBF ←http→ MediaWiki API+ GWT - Google Web Toolkit 2.0.4 JWBF - Java Wiki Bot Framework 1.3.2 MediaWiki 1.16 XML JDK1.6

  • Why did all my pictures disappear? How can I get them back?

    Every picture in my library disappeared how can I get them back?

  • Open InDesign CS4 files in CS4 in Windows 7

    Hi! I want to open InDesign CS4 files in in InDesign CS4 but it opens with InDesign CS3. What can I do? I also tried 'open with' by right clicking and select a default program but that didn't work for me. I also downloaded registry files from 'Window

  • RunDLL error

    I'm using Windows 7 Ultimate, 64-bit, and I'm having problem with RunDLL error, every time I start my computer there is small window with notification that specified module could not be found, Appdatta/Roaming/newnext.me/nengine.dll  How can I solve

  • GPU RAM (the more the better?)

    What effect will having more RAM on a GPU card have for MPE (or even AE)? I noticed that EVGA makes a 1.5GB and a 3GB version of the GTX580. Other then the obvious price difference, will it improve performance? and in what way? Frederic Segard