Row hiding in Jtable

Hi Group,
I have a custom table renderer in which I have to make some of the rows in the table as invisible depending upon the row value. I tried by taking the each value in a string and making it invisible using component.setVisible(false).
But still the data in the table whose value is "hello" are visible instead of invisible. I could not understand why it is becoming visible
Here is the code:
public Component prepareRenderer(TableCellRenderer renderer, int rowIndex, int vColIndex){
               Component comp = super.prepareRenderer(renderer, rowIndex, vColIndex);
               String sValue = ((String)(this.getValueAt(rowIndex,0)));
               if (sValue != null && sValue.equalsIgnoreCase("hello") && !isCellSelected(rowIndex, vColIndex)) {
                    comp.setBackground(Color.gray);
                    comp.setVisible(false);
               }else if(sValue != null && sValue.equalsIgnoreCase("dude") && !isCellSelected(rowIndex, vColIndex)){
                    comp.setBackground(Color.pink);
                    //comp.setVisible(true);
               }else if(sValue != null &&isCellSelected(rowIndex, vColIndex)){                    
                    comp.setBackground(Color.BLACK);                    
                    ((Component)(comp)).setVisible(false);
               }else{
                    comp.setBackground(Color.gray);     
               return comp;          
Thanks in advance.

you could always set the text color of those rows to the current background color. you would have to handle when the cells were highlighted, and when they are unhighlighted, but it could be a solution.

Similar Messages

  • How to refresh an existing row of a JTable

    Hi all,
    I have to refresh the data of an existing row of a JTable after some time in thread. The code snippet is
    DefaultTableModel model=new DefaultTableModel(data,columnNames);
    table = new JTable(model)
                   public boolean isCellEditable(int row, int col)
                   return false;
    Now I also add rows to this table within the run() of the thread as
    model.addRow(new Object []{sub1,sub6,sub12,sub3,sub18});
    My problem is that I want to refresh the data of this added row within the thread.
    Any help is highly appreciable. Thanks in advance.
    Regards,
    Har Krishan

    Hmmm. His qhestion does not seem to be with how to change the value of a field, but how to get the table to recognize the change. I thought such things were automatic. The model fires a value changed event and the JTable picks up the event and refreshes. I'm not sure why your table is not refreshing under these circumstances. Perhaps a more complete code snippet. Please use the open and close code tags to format your code if you include it.

  • To get the unique id of the selected row in a JTable as in Database

    Hi,
    After fetching the recodrs from the Database, I have displayed them in a JTable. Though I fetched all the columns from db, I am displying only only 2 columns, say Name and Number neither of which is unique, however I have a unique ID for each record in the db. Now when I select some row in the JTable, I need to know its unique ID (the one which is in the db) which i have not displayed in the JTable.
    Is there any API method that can store the unique ids of a table? Or how can this be done?
    Thanks in Advance.

    Although, if you don't want the Id visible in the table, then you need to remove its TableColumn from the TableColumnModel.
    Then when you want to reference the id you need to use:
    table.getModel.getValueAt(...);

  • How to delete the selected rows in a JTable on pressing a button?

    How to delete the selected rows in a JTable on pressing a button?

    You are right. I did the same.
    Following is the code where some of them might find it useful in future.
    jTable1.selectAll();
    int[] array = jTable1.getSelectedRows();
    for(int i=array.length-1;i>=0;i--)
    DefaultTableModel model = (DefaultTableModel)jTable1.getModel();
    model.removeRow(i);
    }

  • How to clear the rows in a jTable

    Can anyone tell me how to clear the contents of all the rows in a jTable?

    This is how I did. Posting the same.
    jTable1.selectAll();
    int[] array = jTable1.getSelectedRows();
    for(int i=array.length-1;i>=0;i--)
    DefaultTableModel model = (DefaultTableModel)jTable1.getModel();
    model.removeRow(i);
    Regards.

  • How can i add rows to a JTable at run time ??????

    hi there
    how can i add a row to a JTable at run time? and display the table after the change? thank you.

    For adding or removing the rows from the JTable, you have to use the methods on the table model. I would show you a simple implementation of table model.
    public class MyTableModel extends AbstractTableModel {
    private ArrayList rowsList = null;
    private String [] columns = { "Column 1" , "Column 2", "Column 3"};
    public MyTableModel() {
    rowsList = new ArrayList();
    public int getRowCount() {
    return rowsList.size();
    public int getColumnCount() {
    return columns.length;
    public void addRow(MyRow myRow) {
    //MyRow is any of your object.
    rowsList.add(myRow);
    fireTableDataChanged();
    public void removeRow(int rowIndex) {
    rowsList.remove(rowIndex);
    fireTableRowsDeleted(rowIndex, rowIndex);
    public Object getValueAt(int row, in col) {
    MyRow currentRow = (MyRow)rowsList.get(row);
    switch (col) {
    case 0:
    //return the value of first cell
    break;
    case 1 :
    //return the value of second cell
    break;
    case 2 :
    //return the value of third cell
    break;
    }Then create the table using the TableModel using the constructor new JTable(TableModel) and then when you want to add/remove a row from the table, call myTableModel.addRow(MyRow) or myTableModel.removeRow(rowIndex)....I hope that this solves your problem.

  • How to increase the number of rows in a jTable dynamically?

    Can anyone help me in increasing the number of rows in a jTable dynamically without using DefaultTableModel?
    I don't want to use DefaultTableModel because my program is about to finish except this problem.
    Thanks in advance.

    Presumably you're using your own custom table model class. Modify that so that it returns the number of rows you want. Though presumably it would do this anyway so I've no idea what the problem is.
    Do you mean you've added rows to the table model but they're not being reflected in the table itself? You need to fire events - AbstractTableModel provides simple methods to fire them, but if you're not using that then you'll have to fire them manually.

  • To change the font of a selected row in a Jtable

    Hello,
    Is it possible to change the font of a selected row in a jtable?
    i.e. if all the table is set to a bold font, how would you change the font of the row selected to a normal (not bold) font?
    thank you.

    String will be left justified
    Integer will be right justified
    Date will be a simple date without the time.
    As it will with this renderer.Only if your custom renderer duplicates the code
    found in each of the above renderers. This is a waste
    of time to duplicate code. The idea is to reuse code
    not duplicate and debug again.
    No, no, no there will be NO duplicated code.
    A single renderer class can handle all types ofdata.
    Sure you can fit a square peg into a round hole if
    you work hard enough. Why does the JDK come with
    separate renderers for Date, Integer, Double, Icon,
    Boolean? So that, by default the rendering for common classes is done correctly.
    Because its a better design then having code
    with a bunch of "instanceof" checks and nested
    if...else code.This is only required for customization BEYOND what the default renderers provide
    >
    And you would only have to use instanceof checkswhen you required custom
    rendering for a particular classAgreed, but as soon as you do require custom
    renderering you need to customize your renderer.
    which you would also have to do with theprepareRenderer calls too
    Not true. The code is the same whether you treat
    every cell as a String or whether you use a custom
    renderer for every cell. Here is the code to make the
    text of the selected line(s) bold:
    public Component prepareRenderer(TableCellRenderer
    renderer, int row, int column)
    Component c = super.prepareRenderer(renderer, row,
    , column);
         if (isRowSelected(row))
              c.setFont( c.getFont().deriveFont(Font.BOLD) );
         return c;
    }It will work for any renderer used by the table since
    the prepareRenderer(...) method returns a Component.
    There is no need to do any kind of "instanceof"
    checking. It doesn't matter whether the cell is
    renderered with the "Object" renderer or the
    "Integer" renderer.
    If the user wants to treat all columns as Strings or
    treat individual columns as String, Integer, Data...,
    then they only need to override the getColumnClass()
    method. There is no change to the prepareRenderer()
    code.
    Have you actually tried the code to see how simple it
    is?
    I've posted my code. Why don't you post your solution
    that will allow the user to bold the text of a Date,
    Integer, and String data in separate column and then
    let the poster decide.Well, I don't see a compilable, runnable demo anywhere in this thread. So here's one
    import javax.swing.*;
    import javax.swing.table.*;
    import java.awt.*;
    import java.text.DateFormat;
    import java.text.SimpleDateFormat;
    import java.util.Arrays;
    import java.util.Date;
    import java.util.Vector;
    public class TableRendererDemo extends JFrame{
        String[] headers = {"String","Integer","Float","Boolean","Date"};
        private JTable table;
        public TableRendererDemo() {
            buildGUI();
        private void buildGUI() {
            JPanel mainPanel = (JPanel) getContentPane();
            mainPanel.setLayout(new BorderLayout());
            Vector headerVector = new Vector(Arrays.asList(headers));
             Vector data = createDataVector();
            DefaultTableModel tableModel = new DefaultTableModel(data, headerVector){
                public Class getColumnClass(int columnIndex) {
                    return getValueAt(0,columnIndex).getClass();
            table = new JTable(tableModel);
    //        table.setDefaultRenderer(Object.class, new MyTableCellRenderer());
            table.setDefaultRenderer(String.class, new MyTableCellRenderer());
            table.setDefaultRenderer(Integer.class, new MyTableCellRenderer());
            table.setDefaultRenderer(Float.class, new MyTableCellRenderer());
            table.setDefaultRenderer(Date.class, new MyTableCellRenderer());
            JScrollPane jsp = new JScrollPane(table);
            mainPanel.add(jsp, BorderLayout.CENTER);
            pack();
            setLocationRelativeTo(null);
            setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        private Vector createDataVector(){
            Vector dataVector = new Vector();
            for ( int i = 0 ; i < 10; i++){
                Vector rowVector = new Vector();
                rowVector.add(new String("String "+i));
                rowVector.add(new Integer(i));
                rowVector.add(new Float(1.23));
                rowVector.add( (i % 2 == 0 ? Boolean.TRUE : Boolean.FALSE));
                rowVector.add(new Date());
                dataVector.add(rowVector);
            return dataVector;
        public static void main(String[] args) {
            Runnable runnable = new Runnable() {
                public void run() {
                    TableRendererDemo tableRendererDemo = new TableRendererDemo();
                    tableRendererDemo.setVisible(true);
            SwingUtilities.invokeLater(runnable);
        class MyTableCellRenderer extends DefaultTableCellRenderer{
            public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
                 super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
                if ( isSelected){
                    setFont(getFont().deriveFont(Font.BOLD));
                else{
                    setFont(getFont().deriveFont(Font.PLAIN));
                if ( value instanceof Date){
                    SimpleDateFormat formatter =(SimpleDateFormat) SimpleDateFormat.getDateInstance(DateFormat.MEDIUM);
                    setText(formatter.format((Date)value));
                if(value instanceof Number){
                   setText(((Number)value).toString());
                return this;
    }Hardly a "bunch of instanceof or nested loops. I only used the Date instanceof to allow date format to be specified/ modified. If it was left out the Date column would be "18 Apr 2005" ( DateFormat.MEDIUM, which is default).
    Cheers
    DB

  • The columns of a selected row in a JTable

    Hello guys,
    I am trying to loop through the columns of a selected row in a JTable. Any ideas how i can do that?
    Thanks in advance for your replies.
    Antana.

    there is getValueAt(int row, int column) method in JTable.
    will this help you?
    and please post swing related queries to swing forum.
    --Azodious_                                                                                                                                                                                                                                                                                                           

  • Deleting a row from a JTable using AbstractTableModel

    Hi,
    Can someone please help me on how should i go about deleting a row in a jtable using the AbstractTableModel. Here i know how to delete it by using vector as one of the elements in the table. But i want to know how to delete it using an Object[][] as the row field.
    Thanks for the help

    Hi,
    I'm in desperate position for this please help

  • How can I add a new row in a JTable dynamically?

    Dear Sir(s)
    I want to add a new row in a Jtable as I press enter key the time focus is on the last cell of the row? pls help

    TomDooley wrote:
    Hello,
    ...I write directly to a cvs file ...my loop slows down to 0.2 Hz
    Writing a series of 5 values to a file should not take so long. There is probably something wrong in the way you are saving your data. May be you should post a simplified version of your vi, so we could see how to improve your code.
    CC
    Chilly Charly    (aka CC)
             E-List Master - Kudos glutton - Press the yellow button on the left...        

  • How do you set the font color for a specific entire row inside a JTable?

    How do you set the font color for a specific entire row inside a JTable?
    I want to change the font color for only a couple of rows inside a JTable.
    I've seen some ways to possibly do this with an individual cell.
    Clarification on changing the font color in an individual cell would be helpful too if
    there is no easy way to do this for a row.

    hai,
    Try out with this piece of code.Create your table and assign the renderer to each column in the table.
    CellColorRenderer m_CellColorRenderer = new CellColorRenderer();
    for(int i=0;i<your_JTable.getColumnCount();i++)
    your_JTable.getColumnModel().getColumn(i).setCellRenderer(m_CellColorRenderer);
    class CellColorRenderer extends JLabel implements TableCellRenderer
    CellColorRenderer()     
    setOpaque(true);     
    setHorizontalAlignment(LEFT);
    setVerticalAlignment(CENTER);
    setBackground(Color.white);
    setForeground(Color.black);
    protected void setValue(Object value)
         setText((value == null) ? "" : value.toString());
    public Component getTableCellRendererComponent(JTable table,Object value,boolean isSelected, boolean hasFocus, int row,int column)
         if(isSelected == true)
              setForeground(Color.red);
         else
              setForeground(Color.black);
         setValue(value);
         return this;
    regards,
    bala

  • JTable help - trying to copy/paste a row in a JTable

    Hello,
    Geez, JTable is such a pain..... I am trying copy a range of rows within a JTable using an Abstract Table Model). I need to use this Abstract model as I have a custom String Tokenizing routine which accesses a flat text file which is my "table" so-to-speak.....
    The sequence of events are:
    1. Highlight the selected rows via the Mouse
    2. Select "Copy" from a menu pull down which then runs
    my copy method which resides in my abstract table model,which properly figures out which cells I need to copy (see below code), and opens up new rows at the bottom
    of the JTable.
    I am trying to automatically take those selected cells and then paste them into the opened up rows at the end of the table when choosing "Paste" from the menu.
    Here is the copy method, and the code that calls it from my main application. I am having a bit of trouble trying to figure out the Paste routine which is where I need help.
    Sorry if this is a bit redundant, but I've been struggling with it...... I know that the System Clipboard is available, but I just cant get that to work for me...
    Does 1.4.1 have an "easy" way to do this so I don't have to re-invent the wheel ????
    Thanks in advance
    From my main app:
    private void updateTheFiles(String updateType)
    // Determine which model we are working with //
    currmodel = (DataFileTableModel)vec.elementAt(tabnum) ;
    System.out.println("File = " + fileNameArray[tabnum] );
    if (updateType == "Save") {     
    System.out.println("updateType = " + updateType );
    Object tfs = new TextFileSaver(currmodel,fileNameArray[tabnum],"Pipe",true) ;}
    if (updateType == "Insert") {
    System.out.println("updateType = " + updateType );
    int a = currmodel.getColumnCount() ;
    Object [] aRow = new Object [a];
    currmodel.addRow(aRow); }
    if (updateType == "Delete") {
    System.out.println("updateType = " + updateType );
    currmodel.deleteRows(startRowToBeDeleted, endRowToBeDeleted); }
    if (updateType == "Copy") {
    System.out.println("updateType = " + updateType );
    ----> currmodel.copyRows(startRowToBeDeleted, endRowToBeDeleted);
    // if (updateType == "Paste") {
    // System.out.println("updateType = " + updateType );
    // TablePaste tp = new TablePaste(userTable) ;
    // if (updateType == "Find") {
    // System.out.println("updateType = " + updateType );
    // Object fnd = new FindReplace() ; }
    // currmodel.copyRows(startRowToBeDeleted, endRowToBeDeleted); }
    Table Model:
    import javax.swing.*;
    import javax.swing.table.*;
    import javax.swing.event.*;
    import java.io.* ;
    import java.util.* ;
    import java.lang.* ;
    public class DataFileTableModel extends AbstractTableModel {
    //public class DataFileTableModel extends DefaultTableModel {
    protected Vector data;
    protected Vector columnNames ;
    protected Vector copyVec ;
    protected String datafile;
    public DataFileTableModel(String f){
    datafile = f;
    initVectors();
    public void initVectors() {
    String aLine ;
    data = new Vector();
    columnNames = new Vector();
    try {
    FileInputStream fin = new FileInputStream(datafile);
    BufferedReader br = new BufferedReader(new InputStreamReader(fin));
    // extract column names
    StringTokenizer st1 =
    new StringTokenizer(br.readLine(), "|");
    while(st1.hasMoreTokens())
    columnNames.addElement(st1.nextToken());
    // extract data
    while ((aLine = br.readLine()) != null) {
    StringTokenizer st2 =
    new StringTokenizer(aLine, "|");
    while(st2.hasMoreTokens())
    data.addElement(st2.nextToken());
    br.close();
    catch (Exception e) {
    e.printStackTrace();
    public int getRowCount() {
    return data.size() / getColumnCount();
    public int getColumnCount(){
    return columnNames.size();
    public String getColumnName(int columnIndex) {
    String colName = "";
    if (columnIndex <= getColumnCount())
    colName = (String)columnNames.elementAt(columnIndex);
    return colName;
    public Class getColumnClass(int columnIndex){
    return String.class;
    public boolean isCellEditable(int rowIndex, int columnIndex) {
    return true;
    public Object getValueAt(int rowIndex, int columnIndex) {
    return (String)data.elementAt( (rowIndex * getColumnCount()) + columnIndex);
    public void setValueAt(Object aValue, int rowIndex, int columnIndex) {
    data.setElementAt(aValue, (rowIndex * getColumnCount())+columnIndex) ;
    fireTableCellUpdated(rowIndex, columnIndex);
    public void addRow(Object[] aRow) {
    for (int i=0; i < aRow.length; i++)
    data.add(aRow);
    int size = getRowCount();
    fireTableRowsInserted(size-1,size-1);
    public void deleteRows(int startRow, int endRow)
    int tempRow = 0;
    int actualRows = 0;
    if (endRow < startRow)
    tempRow = endRow ;
    endRow = startRow ;
    startRow = tempRow ; }
         if (startRow < 0 || endRow > getRowCount())
         return;
         actualRows = (endRow - startRow) + 1 ;
         // determine the starting point (cell) to start deleting at //
         int colCount = getColumnCount() ;
         int cell = startRow * colCount ;
         // determine the total number of cells to delete //
         int totColCount = (getColumnCount() * actualRows) ;
         for (int d = 0; d < totColCount; d++)
         data.remove(cell) ;
    fireTableRowsDeleted(startRow,endRow) ;
    public void copyRows(int cStartRow, int cEndRow)
    System.out.println("Startrow = " + cStartRow) ;
    System.out.println("Endrow = " + cEndRow) ;
    int cTempRow = 0;
    int cActualRows = 0;
    if (cEndRow < cStartRow)
    cTempRow = cEndRow ;
    cEndRow = cStartRow ;
    cStartRow = cTempRow ; }
         if (cStartRow < 0 || cEndRow > getRowCount())
         return;
         cActualRows = (cEndRow - cStartRow) + 1 ;
         // determine the starting (cell) to start copying from //
         int cStartCell = cStartRow * getColumnCount() ;
         // determine the total number of cells to copy //
         int cTotCells = (getColumnCount() * cActualRows) ;
         // determine the ending cell //
         int cEndCell = (cStartCell + cTotCells) - 1 ;
         System.out.println("Start Cell = " + cStartCell) ;
         System.out.println("End Cell = " + cEndCell) ;
         System.out.println("Total Cells = " + cTotCells) ;     
         // Now we have to load the empty rows with the copied data //
         System.out.println("getrowcount = " + getRowCount()) ;
         // Open up empty rows where the copied data will reside //
         for (int ci = 0 ; ci < cActualRows ; ci++ )
         Object [] cRow = new Object [getColumnCount()] ;
         addRow(cRow) ;
         int newRowStart = (getRowCount() - cActualRows) ;
         int newRowEnd = getRowCount() - 1 ;
         System.out.println("new row start = " + newRowStart) ;
         System.out.println("new row end = " + newRowEnd ) ;

    Hi Veeru,
    I like to copy and paste in Excel too, so just do it!
    This forum is intended to help on specific problems. As you only told us what you like we can offer no help.
    But you may search the forum for all those other Excel related threads to find hints/examples/thoughts on this...
    Message Edited by GerdW on 01-12-2010 01:06 PM
    Best regards,
    GerdW
    CLAD, using 2009SP1 + LV2011SP1 + LV2014SP1 on WinXP+Win7+cRIO
    Kudos are welcome

  • How do you make the rows in a JTable uneditable.

    Hi
    Does anyone knows how to make the rows in a JTable uneditable.
    --kirk                                                                                                                                                                                   

    Hi,
    implement a TableModel, e.g AbstractTableModel and use it to initialise
    your table. (JTable aTable = new JTable(myAbstractTableModel))
    And if you want your table to be editable implement isCellEditable() in your table model, and let it return true. If not let it return false, or don't implement it att all.

  • How to create new rows in a JTable dynamically?

    I want to add new rows to a JTable dynamically based on my resultset from the database .
    How to do ?
    Please help me
    Thanks in advance

    Thank u for ur reply .But still i need to clarify something.
    I've used the below code to create a basic table within my frame.
    Object[][] data = {      {"dilipp", "r",      "early", "10","20"}};
    String[] columnNames = {"First Name", "Last Name", "payment", "from", "to"};
    table = new JTable(data, columnNames);
    after this i connect to database and query .The values returned are to be populated in the table created above through say a button "Next" month.
    now my button event goes like this :
    public void actionPerformed(ActionEvent e)
         if (e.getActionCommand().equals("next"))
    here i need to add a new row for the values
    How to add here ?
    please tell me

Maybe you are looking for