Coloring row problem of JTable

Hi!
I'm the beginer and have a problem while coloring rows in my table. The problem is as follows:
i need to color the whole row when i click a single cell of this row. Everything is ok until i click another cell of another row. When i do it all the row between first and last clicked become colored!
I tryed manipulating table.setSelectionMode(i) - but nothing!
My very simple code:
DefaultTableCellRenderer renderer = new DefaultTableCellRenderer()
            public Component getTableCellRendererComponent(JTable table,Object value, boolean isSelected, boolean hasFocus, int row, int column)
                Component cell = super.getTableCellRendererComponent(table,value, isSelected, hasFocus, row, column);
                if (isSelected) {cell.setBackground(Color.LIGHT_GRAY);return cell;}
                return cell;
for(int i=0; i<table.getColumnCount(); i++)
            table.getColumnModel().getColumn(i).setCellRenderer(renderer);
Please help!
PS I cant use Ctrl button in my program because all the changes in table are in table.isEnable(false)-mode-it is the condition of my work.

Karl already gave the correct answer: once you touched any Color property of a DefaultTableCellRenderer, you have to do it always, that is in any of the logic branches. That's because DTCR has a nasty color "memory" which basically is the net result of inapproriate subclassing (no compelling reason for a renderer to-be a component) and frozen api (couldn't add a setRendererXXColor) at the particular moment of evolution when it was needed. (Our SwingX wiki about swingx renderer/highlighter support has more details)
BTW, if I interpret your code snippet correctly, you are after a different selection color for all columns? If so you can set that color globally for your table instance (hint: api doc is your friend :-), no need for a custom renderer.
HTH
Jeanette

Similar Messages

  • Problem with coloring rows

    hi there,
    how can i get a single row in my jtable colored? i tried out some solutions that were postet here, but they do not work for me. my problem is, that all rows get the new color although i defined it only for one row. i post some code for better understanding and maybe debugging. my jtable consists of 28 rows and 32 colums and i ONLY want row number 18 getting colored pink. any advice are welcome.
    public Tabelle() {
              super("Stundenplan");
              datenmodell = new DatenModell();
              tabelle = new JTable(datenmodell);
              TableColumn column = new TableColumn();
              column = null;
              for (int i = 0; i < 32; i++) {
              column = tabelle.getColumnModel().getColumn(i);
              if (i == 0) {
              column.setPreferredWidth(100);
              column.setCellRenderer(new CenterRenderer());
              else {
              column.setPreferredWidth(50);
              column.setCellRenderer(new CenterRenderer());
              kopf.setBorder(BorderFactory.createEtchedBorder());
              tabellenBox.add(kopf);
              tabellenBox.add(tabelle.getTableHeader());
              tabellenBox.add(tabelle);
              tabellenPanel.add(tabellenBox);
              scrollpane = new JScrollPane(tabellenPanel);
              scrollpane.setPreferredSize(new Dimension(1100, 520));
              getContentPane().add(scrollpane);
    that is the constructor of the jframe. the following code is my custom cell renderer:
    class CenterRenderer extends DefaultTableCellRenderer {
         public Component getTableCellRendererComponent(JTable tab, Object val, boolean sel, boolean foc, int z4, int s4) {
              Component component = super.getTableCellRendererComponent(tab,val,sel,foc,z4,s4);
              ((JLabel)component).setHorizontalAlignment(SwingConstants.CENTER);
              if (z4 == 18) {
                   setBackground(Color.pink);
              return component;
    }

    yeah, i tried it, but then there is some strange behavior. first all rows are white, but if you select row number 18 (the pink one) it becomes pink. then if you select a cell in another column, all becomes white again until you select row number 18 again.
    thats not satisfying for me, so if you have a solution for that, please post it.
    thanks in advance.

  • How to set color of our specified JTable's row

    i need to set color of our specified JTable's row.so send the coddings of that part.

    i need to set color of our specified JTable's row.so
    send the coddings of that part.I think you misunderstand how this forum works...
    If you have a problem, you post your problem here with example code which demonstrates said problem...
    The people here then attempt to help you if they want to.
    You do not post demands for code examples

  • 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

  • Setting colors of the rows of  a JTable

    Hi,
    How can we set multiple colors(foreground) for multiple rows in a JTable?. (i want to set the color of the row depends on the value of a column. Foe example if the value of a particular column is "x" then i want to set the color of that particular row as "RED" or if the value of that column is "y" then i want to set the color of the column as "GREEN". )

    Try this:
    * Method to set custom cell renderer
    *Adopted from
    * http://javaalmanac.com/egs/javax.swing.table/Stripe.html
    JTable theTable = new JTable() {
    public Component prepareRenderer(TableCellRenderer renderer,
    int row, int col) {
    Component c = super.prepareRenderer(renderer, row, col);
    //Example assumes the column number is 1 and value is "Critical"
    if (theTable.getValueAt(row, 1) != null) {
    if (theTable.getValueAt(row, 1).equals("Critical")) {
    if (col == 1) {
    c.setForeground(Color.red);
    c.setBackground(new Color(255, 255, 204));
    c.setFont(new java.awt.Font("MS Sans Serif", 1, 11));
    return c;
    };

  • Problem in JTable cell renderer

    Hi
    One problem in JTable cell. Actually I am using two tables while I am writing renderer for word raping in first table .. but it is affected in last column only remain is not being effected�. Please chaek it out what is exact I am missing�
    Thanks
    package com.apsiva.tryrowmerge;
    import java.awt.*;
    import java.awt.event.*;
    import java.util.ArrayList;
    import java.util.EventObject;
    import java.util.Hashtable;
    import java.net.*;
    import javax.swing.*;
    import javax.swing.border.Border;
    import javax.swing.border.EmptyBorder;
    import javax.swing.event.*;
    import javax.swing.table.TableCellEditor;
    import javax.swing.table.TableCellRenderer;
    import javax.swing.table.TableColumn;
    class Item_Details extends JFrame {
        ApsJTable itemTable = null;
         ApsJTable imageTable = null;     
         ArrayList data = new ArrayList();
         String[] columns = new String[2];
         ArrayList data1 = new ArrayList();
         String[] columns1 = new String[2];
         ItemTableModel itemTableModel = null;
         ItemTableModel itemTableModel1 = null;
         public Item_Details()
              super("Item Details");          
             this.setSize(600,100);
             this.setBackground(Color.WHITE);
              this.setVisible(true);
             init();          
         private void init(){
              ////////////// Get data for first Table Model  ////////////////////////////
              data = getRowData();
              columns = getColData();
              System.out.println(columns[0]);
             itemTableModel = new ItemTableModel(data,columns);
             /////////////Get Data for Second Table Model //////////////////////////////
              try{
                        data1 = getRowData1();
                 }catch(Exception e){}
              columns1 = getColumns1();
             itemTableModel1 = new ItemTableModel(data1,columns1);
             ///////////// Set Data In Both Table Model //////////////////////////////////
              itemTable = new ApsJTable(itemTableModel);
              imageTable = new ApsJTable(itemTableModel1);
              this.itemTable.setShowGrid(false);
              this.imageTable.setShowGrid(false);
              this.itemTable.setColumnSelectionAllowed(false);
              this.imageTable.setColumnSelectionAllowed(false);
              System.out.println(itemTable.getColumnCount());
              this.imageTable.setRowHeight(getImageHeight()+3);
              JScrollPane tableScrollPane = new JScrollPane(this.imageTable,JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
              tableScrollPane.setRowHeaderView(this.itemTable);
              //itemTable.getColumnModel().getColumn(0).setMaxWidth(200);
              itemTable.getColumnModel().getColumn(0).setPreferredWidth(200);
              itemTable.getColumnModel().getColumn(1).setPreferredWidth(600);
              tableScrollPane.getRowHeader().setPreferredSize(new Dimension(800, 0));
              itemTable.getTableHeader().setResizingAllowed(false);
              itemTable.getTableHeader().setReorderingAllowed(false);
              itemTable.setColumnSelectionAllowed(false);
              //itemTable.setRowHeight(25);
              itemTable.setCellSelectionEnabled(false);
              itemTable.setFocusable(false);
              imageTable.getTableHeader().setReorderingAllowed(false);
              imageTable.setFocusable(false);
              imageTable.setCellSelectionEnabled(false);
              //tableScrollPane.setOpaque(false);
              itemTable.setAutoCreateColumnsFromModel(false);
              int columnCount = itemTable.getColumnCount();
              for(int k=0;k<columnCount;k++)
                   TableCellRenderer renderer = null;
                   TableCellEditor editor = null;
                   renderer = new TextAreaCellRenderer();     // NEW
              //     editor = new TextAreaCellEditor();     
              //     TableColumn column = new TableColumn(k,itemTable.getColumnModel().getColumn(k).getWidth(),renderer, editor);
                   System.out.println(k);
                   itemTable.getColumnModel().getColumn(k).setCellRenderer(renderer);          
                   //itemTable.getColumnModel().getColumn(k).setCellEditor(editor);
                   /*itemTable.getColumnModel().getColumn(1).setCellRenderer(new TextAreaCellRenderer());
                   itemTable.getColumnModel().getColumn(1).setCellEditor(new TextAreaCellEditor());*/
    //               itemTable.setShowGrid(false);
                   //itemTable.addColumn(column);
                   //itemTable.getColumnModel().getColumn(k).setCellRenderer(new MultiLineCellRenderer());
                   //itemTable.getColumnModel().getColumn(k).setCellEditor(new TextAreaCellEditor());
    ////////////---------------------- Here background color is being set--------------//////////////////
              this.imageTable.getParent().setBackground(Color.WHITE);
              this.itemTable.getParent().setBackground(Color.WHITE);
              tableScrollPane.setCorner(ScrollPaneConstants.UPPER_LEFT_CORNER,this.itemTable.getTableHeader());
              getContentPane().add(tableScrollPane,BorderLayout.CENTER);
              getContentPane().setVisible(true);
         public static void main(String[] str){
              com.incors.plaf.alloy.AlloyLookAndFeel.setProperty("alloy.licenseCode", "2005/05/28#[email protected]#1v2pej6#1986ew");
              try {
                javax.swing.LookAndFeel alloyLnF = new com.incors.plaf.alloy.AlloyLookAndFeel();
                javax.swing.UIManager.setLookAndFeel(alloyLnF);
              } catch (javax.swing.UnsupportedLookAndFeelException ex) {
              ex.printStackTrace();
              Item_Details ID = new Item_Details();
              ID.setVisible(true);
    public ArrayList getRowData()
         ArrayList rowData=new ArrayList();
         Hashtable item = new Hashtable();
         item.put(new Long(0),new String("Item No:aaaaaaa aaaaaaaa aaaaaaaaa aaaaaa"));
         item.put(new Long(1),new String("RED-1050"));
         rowData.add(0,item);
         item = new Hashtable();
         item.put(new Long(0),new String("Description:rt r trtrt rttrytrr tytry trytry tr tr rty thyjyhjhnhnhgg hhjhgjh"));
         item.put(new Long(1),new String("SYSTEM 18 mbh COOLING 13 mbh HEATING 230/208 v POWER AIRE "));
         rowData.add(1,item);
         item = new Hashtable();
         item.put(new Long(0),new String("Stage:"));
         item.put(new Long(1),new String("Draft"));
         rowData.add(2,item);
         item = new Hashtable();
         item.put(new Long(0),new String("Price: "));
         item.put(new Long(1),new String("999.00"));
         rowData.add(3,item);
         item = new Hashtable();
         item.put(new Long(0),new String("Features:"));
         item.put(new Long(1),new String("SYSTEM COOLING & HEATING 12 mbh 230/208 v POWER AIRE SYSTEM1234 COOLING & HEATING 12 mbh 230/208 v POWER AIRE "));
         rowData.add(4,item);
         item = new Hashtable();
         item.put(new Long(0),new String("Features:"));
         item.put(new Long(1),new String("SYSTEM COOLING & HEATING 12 mbh 230/208 v POWER AIRE SYSTEM1234 COOLING & HEATING 12 mbh 230/208 v POWER AIRE "));
         rowData.add(5,item);
         item = new Hashtable();
         item.put(new Long(0),new String("Features:"));
         item.put(new Long(1),new String("SYSTEM COOLING & HEATING 12 mbh 230/208 v POWER AIRE SYSTEM1234 COOLING & HEATING 12 mbh 230/208 v POWER AIRE "));
         rowData.add(6,item);
         /*item.put(new Long(0),new String("Family Sequence"));
         item.put(new Long(1),new String("8.00"));
         rowData.add(5,item);
         item.put(new Long(0),new String("Family Sequence"));
         item.put(new Long(1),new String("8.00"));
         rowData.add(6,item);
         item.put(new Long(0),new String("Family Sequence"));
         item.put(new Long(1),new String("8.00"));
         rowData.add(7,item);
         return rowData;
    public String[] getColData()
         String[] colData = new String[]{"Attribute","Value"};
         return colData;
    public ArrayList getRowData1()throws MalformedURLException{
         ArrayList rowData = new ArrayList();
         Hashtable item = new Hashtable();
         String str = new String("http://biis:8080/assets/PRIMPRIM/Adj_BeacM_Small.jpg");
         URL url = new URL(str);
         ImageIcon ic = new ImageIcon(url);
         ImageIcon scaledImage = new ImageIcon(ic.getImage().getScaledInstance(getImageHeight(), -1,Image.SCALE_SMOOTH));
         item.put(new Long(0), scaledImage);
         rowData.add(0,item);
         String str1 = new String("http://biis:8080/assets/PRIMPRIM/Adj_BeacM_Small.jpg");
         URL url1 = new URL(str1);
         ImageIcon ic1 = new ImageIcon(url1);
         ImageIcon scaledImage1 = new ImageIcon(ic1.getImage().getScaledInstance(120, -1,Image.SCALE_DEFAULT));
         item.put(new Long(0),scaledImage1);
         rowData.add(1,item);
         return rowData;
    public String[] getColumns1(){
         String[] colData = new String[]{"Image"}; 
         return colData;
    public int getImageHeight(){
         ImageIcon ic = new ImageIcon("c:\\image\\ImageNotFound.gif");
         return ic.getIconHeight();
    class TextAreaCellRenderer extends JTextArea implements TableCellRenderer
         public TextAreaCellRenderer() {
              setEditable(false);
              setLineWrap(true);
              setWrapStyleWord(true);
         public Component getTableCellRendererComponent(JTable table,
              Object value, boolean isSelected, boolean hasFocus,
              int nRow, int nCol)
              if (value instanceof String)
                   setText((String)value);
              // Adjust row's height
              int width = table.getColumnModel().getColumn(nCol).getWidth();
              setSize(width, 1000);
              int rowHeight = getPreferredSize().height;
              if (table.getRowHeight(nRow) != rowHeight)
                   table.setRowHeight(nRow, rowHeight);
              this.setBackground(Color.WHITE);
              return this;

    I think Problem is between these code only
    for(int k=0;k<columnCount;k++)
                   TableCellRenderer renderer = null;
                   TableCellEditor editor = null;
                   renderer = new TextAreaCellRenderer();
                                                                itemTable.getColumnModel().getColumn(k).setCellRenderer(renderer);or in this renderer
    class TextAreaCellRenderer extends JTextArea implements TableCellRenderer
         public TextAreaCellRenderer() {
              setEditable(false);
              setLineWrap(true);
              setWrapStyleWord(true);
         public Component getTableCellRendererComponent(JTable table,
              Object value, boolean isSelected, boolean hasFocus,
              int nRow, int nCol)
              if (value instanceof String)
                   setText((String)value);
              // Adjust row's height
              int width = table.getColumnModel().getColumn(nCol).getWidth();
              setSize(width, 1000);
              int rowHeight = getPreferredSize().height;
              if (table.getRowHeight(nRow) != rowHeight)
                   table.setRowHeight(nRow, rowHeight);
              this.setBackground(Color.WHITE);
              return this;
    }

  • Hi!!! A Problem in JTable

    HI,
    I have a problem in JTable.I have a Jtable and a button named validate.My JTable first displays a set of rows and colums.if we name the colns as a,b and c. when i click the validate button i will take the values of a1 and b1 and do some validations. If it is in correct position then the row remains as it is else i will change the value of b1 to a1 position and vice versa. This happens in a loop till the end and the data vector of the table gets changed accordingly.Now the problem is suppose if there are 10 rows and the value changes in row 1,5,7 thn i need that rows alone to be colored while the button ends its action.Finally the JTable should be viewed as row 1,5,7 colored and others in their default color....
    Please help me...
    Message was edited by:
    tis-is-hari

    You will have to create your own Renderer or use a table like JXTable from swing labs that allows highlighting.

  • Highlighting different rows within a JTable

    I have a JTable that has 20 rows. I also have a Jlist next to the JTable. When someone selects something within the Jlist I want to highlight certain rows depending on what was selected within that list. For instance if a user selects Item1 within the list I want to highlight the 3rd, 8th and 11th row within a JTable. The problem is the JTable API will let you highlight a number of rows but not allow you to specify single rows to highlight at one time. When I run my code to do this I get the last row highlighted. The reason is because the 3rd and 8th row do get highlighted but when I call the setRowSelectionInterval(i, i); where i is the row to highlight it has already passed and will end up highlighting the 11th row only. Is there any work around for this?

    First, make sure you table supports multi-select. Turn it on in this case, otherwise you can't select multiple items.
    To color different rows, you'll have to set a cell renderer and use it to color those rows. It's possible to collor each and every cell a different color, set fonts, images, etc..you just need a good cell renderer.

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

  • Selection Problem with JTable

    Hello,
    i have a selection problem with JTable. I want to allow only single cell selection and additionally limit the selection to the first column.
    I preffered the style from MS Outlook Express where you can select the email accounts to edit.
    It is a table like this:
    Account name  |   Type  |   ...
    --------------|---------|---------------------
    Hotmail       |   POP3  |
    GMX           |   IMAP  |The selection should be only avaibable at 'Hotmail' or 'GMX' - not at 'POP3', 'IMAP' or as complete row selection.
    Please help me!
    Thanks.
    Warlock

    Maybe this will helpimport java.awt.*;
    import javax.swing.*;
    public class Test3 extends JFrame {
      public Test3() {
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        Container content = getContentPane();
        String[] head = {"One", "Two"};
        String[][] data = {{"R1-C1", "R1-C2"}, {"R2-C1", "R2-C2"}};
        JTable jt = new JTable(data, head);
        jt.getColumnModel().setSelectionModel(new MyTableSelectionModel());
        content.add(new JScrollPane(jt), BorderLayout.CENTER);
        jt.setCellSelectionEnabled(true);
        jt.setRowSelectionAllowed(false);
        jt.setColumnSelectionAllowed(false);
        setSize(300, 300);
        setVisible(true);
      public static void main(String[] arghs) { new Test3(); }
    class MyTableSelectionModel extends DefaultListSelectionModel {
      public void setSelectionInterval(int index0, int index1) {
        super.setSelectionInterval(0, 0);
    }

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

  • 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

  • Changing a row colour in JTable, depending on a column value

    Hi,
    I need assistance with the following:
    I need to change the colour of a row in a JTable, depending on a column value. I have been successful on changing one column's colour in each cell, depending on the value by using a CellRenderer extending DefaultTableCellRenderer.I am unable to set the other 2 columns's cell's depending on the first column value's.
    I would appreciate any help, source would be a bonus.
    Thx
    Charl

    Ok, here follows the code as requested. Note that this is the code setting each row in one of my columns depending on the value. Now i have to cgange column0 and column1 's foreground the same as what this column (column2) 's foreground is. Thx
    import java.awt.*;
    import java.util.*;
    import javax.swing.*;
    import javax.swing.table.*;
    class ColorizedCell extends DefaultTableCellRenderer {
    static Hashtable cache;
    static {
    cache = new Hashtable();
    cache.put ("Device Responding to Poll",Color.green);
    cache.put ("Wan link Recovered",Color.green);
    cache.put ("No Response to Device Poll",Color.yellow);
    cache.put ("Wan Link Failure",Color.red);
    cache.put ("Lan Link Failure down",Color.red);
    cache.put ("Device Down",Color.red);
    public Component getTableCellRendererComponent(JTable table,
    Object value, boolean isSelected,
    boolean hasFocus, int row, int column)
    JLabel label = (JLabel) super.getTableCellRendererComponent(table,value,isSelected,hasFocus,row,column);
    label.setText((String)value);
    if(column == 2) {
    //setFont(bold);
    Color c = (Color)cache.get(value);
    label.setForeground(c);
    if (isSelected) {
    label.setOpaque(true);
    label.setBackground(Color.white);
    else {
    //setFont(plain);
    label.setForeground(Color.white);
    return label;
    }

  • Moving rows in a JTable

    Hello to everybody. I would like to ask you if there is a way to change the order of the rows in a JTable by selecting them and dragging with the mouse just as you can do with columns.
    Best regards.
    Alessandro

    Cheers Richard,
    I'm using TableSorter which is part of the TableSorterDemo in How To Use Tables in the Sun Java tutorial if you want to look - it works fine within the demo. I'm afraid I'm fairly new to java so I'm not sure where to look for the problem. I think I'll try using the default tablemodel, see if that works and then add stuff until it all goes wrong again! Is this sensible? Any more ideas?
    Thomas

Maybe you are looking for

  • Question about autodiscover in case of multiple bound namespace

    Hi Experts, I have a question about the autodiscover behaviour. Let's assume we have the below infrastructure: SiteA : MBX-Server-SiteA : Member of a DAG CAS-Server-SiteA : outlook anywhere url = siteA.domain.com SiteB : MBX-Server-SiteB : Member of

  • Logic behind read statement and material

    SORT IT_EKBEF BY EBELN EBELP. READ TABLE IT_EKBEF INTO WA_EKBEF                  WITH KEY EBELN = WA_FINAL-EBELN                           EBELP = WA_FINAL-EBELP BINARY SEARCH. IF SY-SUBRC = 0. WA_FINAL-MENGE = WA_EKBEF-MENGE. ENDIF. the above is my

  • Visibroker and Managed Server problem

    Hi, I have a webapp that connects to a Visibroker (3.4) server for getting some information. When the application is deployed on the admin server itself everything runs fine. I'm not modifying any of the scripts for this. But when I deploy the applic

  • Why one episode in a series

    Please please please can somebody explain to me the following, Just checked the new tv releases to find Air Crash Investigation special report SEASON 1 so thought would have a look opened it up to find one episode in the series and its not even episo

  • Checkbox with javascript unexpectedly unchecks other checkboxs

    Hi, I have a checkbox called applicant_isemailaddress which has onchange javascript if (this.rawValue) {Page1.doYouEmail.presence = "visible";Page1.applicant_allEmailAddresses.presence = "visible";}else {Page1.doYouEmail.presence = "hidden";Page1.app