Coloring JTable rows depending on the actual and previous value

I need to change the background of the entire row of a JTable, but with the condintion of checking the value (Integer) in the column 0 of each row.
I the actual value is equal to previous value I keep the same color (any color) if it is different I must change the color (to any other color).
Any ideas how I could do that? I suppose I cant use CellRenderer because the Table is already full, so I was thinking about making a looping thru the table and chaning the background colors, but I have no idea how to do that.
So far I have this code:
int totalRows = modProdutos.getRowCount();
int totalCols = modProdutos.getColumnCount();
System.out.println("Total rows: " + totalRows);
TableColumnModel tcm = tbProdutos.getColumnModel();
DefaultTableModel modelo = (DefaultTableModel) tbProdutos.getModel();
if (totalRows > 0) {
    int numeroOSAntes = (Integer) tbProdutos.getValueAt(0, 0);
    for (int i = 0; i < totalRows; i++) {
        int numeroOS = (Integer) tbProdutos.getValueAt(i, 0);
        if (numeroOS == numeroOSAntes) {
            // Paint the background with the same color (any color)
            System.out.println("Same Color: " + numeroOSAntes + " - " + numeroOS);
        } else {
            // Paint the background with a different color (any other color)
            System.out.println("Different color: " + numeroOSAntes + " - " + numeroOS);
        // keep the previous control number
        numeroOSAntes = numeroOS;
}

        jTable1 = new JTable(0,4){
            @Override
            public Component prepareRenderer(TableCellRenderer renderer, int row, int column) {
                Component c = super.prepareRenderer(renderer, row, column);
                c.setBackground(Color.YELLOW);
                boolean yellow = true;
                for (int i = 1; i <= row; i++) {
                    if(!getValueAt(i,0).toString().equals(getValueAt(i-1,0).toString())){
                        yellow = !yellow;
                if(!yellow){
                    c.setBackground(Color.WHITE);
                return c;
        model = (DefaultTableModel)jTable1.getModel();
        model.addTableModelListener(new TableModelListener() {
            public void tableChanged(TableModelEvent e) {
                jTable1.repaint();
        });

Similar Messages

  • How can I compare the actual and expected values in Unit testing when they are XML files?

    I have created a unit test for a method in VS 2008. My expected value and actual value are XMLs. Therefore though the output is same as I expect it gives an error as I am doing string comparison now. How can I compare these 2 XMLs in expected output and
    actual output format in Unit Testing?
    mayooran99

    In unit test, when you want to validate XML files, you feed them into the class / struct that you want to feed the XML into and compare the values there (You don't just feed it in XMLReader and feed it line by line, right? But if it really is, that's how
    you should also test it in unit tests).
    In short, how you'd use the XML in your code, that's how you should test it in unit test.

  • Need to display different colors for Actuals and forecasting values in WAD

    Hi Gurus,
    My requirement in the report is, I need to display different colors for particular values like Actuals(say value type 10) and for forecasting values(say value type 20) , and data will uploaded from flat file.
    Scenario : If I upload the data for March Month, I receive actual values upto March(Jan to March month) and from April to Dec(Forecast values with value type 20),  Every month I will be getting file and similarly for subsequent months, i will get current month actual values and forwarding months forecasting values,
    Now , my requirement is, When ever i execute the Report, Say if i execute for April Month, Upto April( Jan to April for actual values should be displayed in one color) and from May to Dec ( forecast values should be displayed in different color).
    I had tried with following options like exceptions and could not display , as it runs based on key figure values where as my requiremnet is based on the CALMONTH , i need to show different colors for both actual and forecast values.
    Kindly, help me out from this,
    Thanks

    Hi,
    it is not necesseary that you need to do that in WAD , you can do the same in BEx platform, Since WAD is build above the bex reports. so automatially any changes done in Report will be replicated in WAD
    Go for Exceptions in Bex. Give some range for Actuals and Forcasting at the creation of the exception.
    if you do those changes in BEX automatically it will replicate in the WAD.
    for more information please read this link
    http://help.sap.com/saphelp_nw04/helpdata/en/68/253239bd1fa74ee10000000a114084/content.htm
    hope this will solve your problem.
    Santosh

  • Actual and Commitments values are not Appearing in Internal order report

    Hi
    We have done budget in KO22 for Internal Order and active the availability controle after that we made PO with the same IO and with account assignment category 'A' and GR also happened.
    So when we run the report (S_ALR_87013019 - List: Budget/Actual/Commitments ), system is not showing Actual and Commitments values...
    Please help me in this regard...
    Thanks,
    Saisri

    Hi,
    Here we are giving internal order in PO with account assignment category 'A'
    In case of Account assignment category 'K'  it is showing the Actual values in Report.
    Why is it showing Actal /commitment values incase of 'K'  ?
    Why it is not showing when we select the 'A' category ?
    Please provide me answer about my queries...plz
    Thanks,
    Saisri

  • Where could we find the CT and PT values  for Particular Device ???

    I 'm facing a scenario in  a report  i need to place a  field device number and assosiated  CT's and PT's .
    where could we find the CT and PT values  for Particular Device ??? basically im MM consultant   we don't ahave  DM consultant  please help with this issue???
    means actually i got the table and field  details  for transformation ratio (or) CT/PT ratio
                          ETYP_UEBERVER. from the screen EG03 , t-code
                            but im not sure   this  is the exact field that i require  ....
    can any one help ....   i will be very  thankfull to your  solution  inadvance....

    The transformation ratio are the attributes of a "Winding Group".  Find winding group of a device and then you'll get the desired information.

  • Tables req: Actual and planned values

    Hello Experts,
    I would like to create a new zprogram, which will give me output.
    Cost element- planned values- actual values-. Day1 actual cost -day2 actual costu2026day31 actual cost.
    Can any one tell me in which tables the planned(KP06) and actual data will be stored?

    Hi,
    Actual and plan values on line item level are stored in COEP. COSP is the table for totals (again for both actual and plan). You distinguish between the two by 'Value type' field.
    Regards,
    Eli

  • Find Retroactive actuals and previous

    Hi,
        I have got the Retroactive differences from the function module ( HR99L00_GET_RETRO_MONTH_DIFF ) for a given retroactive month. Further, i need to get
    <b>1.  The actuals (A) for the given retroactive month. Do we have and function module for this ?
    2.Similarly, i want to have the previous (P) for the given retroactive month.for this do we have any function module?</b>
    Earnings : wagetyp1     wagetyp2....................................................
    Old         : 30500          18300
    New        : 30500          0
    <b>Diff         :   0             -18300</b>
    I have got the difference from the function  module       HR99L00_GET_RETRO_MONTH_DIFF.
    which is in bold.
    Plz can anyone help me to get the old and new values?
    Regards,
    Vani.
    (points will be rewarded for the right answers).

    Hi
    Use the function module.
    CD_EVALUATION_PERIODS
    first get results directory for the pernr using the function module 'CU_READ_RGDIR'.
    LOOP AT it_rgdir  WHERE ipend BETWEEN p_begda AND p_endda
                             AND void  = space
                             AND ocrsn = space
                             AND inocr = space
                            AND inper = v_ipper.
    ENDLOOP.
    CLEAR it_evp. REFRESH it_evp.
          CALL FUNCTION 'CD_EVALUATION_PERIODS'
               EXPORTING
                   bonus_date      = p_endda
                    inper_modif     = it_rgdir-iperm
                    inper           = it_rgdir-inper
               TABLES
                    rgdir           = it_rgdir
                    evpdir          = it_evp
               EXCEPTIONS
                    no_record_found = 1
                    OTHERS          = 2.
          IF sy-subrc <> 0.
    MESSAGE ID SY-MSGID TYPE SY-MSGTY NUMBER SY-MSGNO
            WITH SY-MSGV1 SY-MSGV2 SY-MSGV3 SY-MSGV4.
          ENDIF.

  • How can i do to see the master and text values of the Key figure 0UNIT

    Hi gurus,
    How can i do to see the master and text values of the Key figure 0UNIT, please step by step, i m in the key figure 0UNIT but i want to see if the UNIT  for example BX = BOX, something like this is that i want to check,  thanks!

    If you look at the unit tables, you will see the values and texts.  It's in SPRO, not in RSA1.  My access is limited on my system here, but the documentation says to go to t-code CUNI.  I believe in that tcode you can look at all of the unit equivalencies and what each unit's text is ..... like an ea means each; KG = Kilogram; etc...
    I am on an 3.x system, so in SPRO I go to BW CIG=>General Settings=>Check units of measurement.
    Brian

  • How to avoid the Amount and Date values for VOID Cheques

    Hi All,
    I had created a two window i.e For Amount and Date. If I process the cheque the Amount value and Date should not trigger for VOID CHEQUES.
    Can any one tel me how to avoid the Amount and Date values for VOID Cheques
    Your help will be greatly appreciated.
    Regards
    Yathish

    Hi,
    I dont know which tablel you are referring to, is it PAYR table and the field VOIDR?
    If a cheque is voided, it would have a reason and it is stored in VOIDR field of this PAYR table.
    Check if the field VOIDR is filled, if it is filled, do not print the amount and date.
    Regards
    Subramanian

  • I cannot find the next and previous button in iTunes get info menu? Is there anyone that has also experienced this problem that can help me please

    I cannot find the next and previous button in iTunes get info menu?
    Is there anyone that has also experienced this problem that can help me please
    I have the lates version of Itunes

    I have managed to figure out how to solve this problem, after looking around I saw a lot of people kept saying makesure it is list view however this still did not work, I found the only way for me get these buttons back was to change the Movie to a TV Show and only then did the "Next" and "Previous" button appear. Right Click> Get Info > Options > Media Kind and then Select TV Show, this is extremely inconvienent but the only way that I found that has worked so far.
    Hope this works for you too!!

  • I want to select a specific rectangular position from intensity graph to extract the x and y values

    I want to select specfic rectangular postion from an intensity graph to extract the X and Y values at that specific position.
    Is this possible using LabVIEW?
    @nk

    Hi nk,
    Is this possible using LabVIEW?
    Yes.
    I want to select specfic rectangular postion from an intensity graph to extract the X and Y values at that specific position.
    Just select the positions! What's your problem in doing so?
    Btw. when you select positions you already know their XY values!? I don't get the point of your task...
    Best regards,
    GerdW
    CLAD, using 2009SP1 + LV2011SP1 + LV2014SP1 on WinXP+Win7+cRIO
    Kudos are welcome

  • Error 13641 - The Subnet prefix must be between the starting and ending values

    Hi All,
    I can honestly say hand on heart that this is the first time I have ever asked for help in a forum in over 15 years but this is doing my head in..
    I have a Sys Center 2012 R2 deployment..  VMM R2 up to RU3, Edge Cluster (2 hosts), Management Cluster (2 hosts), 2 x Production Compute Clusters (total of 20 hosts).  I have a HA Network Virt Gateway deployed on the edge cluster.
    All Hosts have the new DHCP install done and the RU3 SQL patch is completed as outlined in deployment manual.
    Everything had been running fine for some time after RU3 update...  I am experiencing an issue whereby I get the following error anytime I try and attach a NVGRE VM network to a VM, or when I try and migrate a VM with a NVGRE network attached to another
    host.
    Error (13641)
    The specified subnet prefix must be between the starting and ending values for the range.
    Starting value: 4
    Ending value: 30
    Recommended Action
    Specify a suitable subnet prefix.
    All subnets in the entire network are /24's so prefix isn't an issue.
    I can successfully attach a standard vm network but get the above error when working with NVRGE networks.. 
    Further to this, if I restart VMM the DHCP function to VM's with NVGRE networks doesn't get picked up until I trigger a change in config on the VM, then it will get IP and function as expected.
    I have checked all logs, there aren't any errors that I can see.
    get-netvirtualizationlookuprecord throws out VM's and PA's as expected, but again not until I manually interfere with the VM in question.
    Have any of you come across this before??  I want to check before I go rebuilding the PA network entirely and having to cleanup all existing VM networks to do it..
    Any help or guidance would be appreciated..
    Cheers
    Nathan

    I have seen this message before, "specify a suitable subnet prefix".
    In my case, the NVGRE policies were out of sync due to HW issues on several hosts.
    Here's some steps in order to troubleshoot/fix:
    run the following cmdlet: Get-SCVMHost | Read-SCVMhost -RunAsynchronously
    Check for any errors in the job log that refers to "Network Virtualization".
    If this doesn't help, a recycle of the VMM Management server should do a "hard refresh" of the NVGRE policies, and it might include a reboot of the nvgre hosts too.
    This solved the case in my situation.
    -kn 
    Kristian (Virtualization and some coffee: http://kristiannese.blogspot.com )

  • Shading part of a JTable Cell dependent upon the value of the cell

    Hi
    Was hoping some one woudl be able to provide some help with this. I'm trying to create a renderer that will "shade" part of a JTable cell's background depending upon the value in the cell as a percentage (E.g. if the cell contains 0.25 then a quarter of the cell background will be shaded)
    What I've got so far is a renderer which will draw a rectangle whose width is the relevant percentage of the cell's width. (i.e. the width of the column) based on something similar I found in the forum but the part I'm struggling with is getting it to draw this rectangle in any cell other than the first cell. I've tried using .getCellRect(...) to get the x and y position of the cell to draw the rectangle but I still can't make it work.
    The code for my renderer as it stands is:
    import java.awt.Component;
    import java.awt.Graphics;
    import java.awt.Graphics2D;
    import javax.swing.JLabel;
    import javax.swing.JTable;
    import javax.swing.table.TableCellRenderer;
    public class PercentageRepresentationRenderer extends JLabel implements TableCellRenderer{
         double percentageValue;
         double rectWidth;
         double rectHeight;
         JTable table;
         int row;
         int column;
         int x;
         int y;
         public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
              if (value instanceof Number)
                   this.table = table;
                   this.row = row;
                   this.column = column;
                   Number numValue = (Number)value;
                   percentageValue = numValue.doubleValue();
                   rectHeight = table.getRowHeight(row);
                   rectWidth = percentageValue * table.getColumnModel().getColumn(column).getWidth();
              return this;
         public void paintComponent(Graphics g) {
            x = table.getCellRect(row, column, false).x;
            y = table.getCellRect(row, column, false).y;
              setOpaque(false);
            Graphics2D g2d = (Graphics2D)g;
            g2d.fillRect(x,y, new Double(rectWidth).intValue(), new Double(rectHeight).intValue());
            super.paintComponent(g);
    }and the following code produces a runnable example:
    import javax.swing.JFrame;
    import javax.swing.JScrollPane;
    import javax.swing.JTable;
    import javax.swing.table.DefaultTableModel;
    public class PercentageTestTable extends JFrame {
         public PercentageTestTable()
              Object[] columnNames = new Object[]{"A","B"};
              Object[][] tableData = new Object[][]{{0.25,0.5},{0.75,1.0}};
              DefaultTableModel testModel = new DefaultTableModel(tableData,columnNames);
              JTable test = new JTable(testModel);
              test.setDefaultRenderer(Object.class, new PercentageRepresentationRenderer());
              JScrollPane scroll = new JScrollPane();
              scroll.getViewport().add(test);
              add(scroll);
         public static void main(String[] args)
              PercentageTestTable testTable = new PercentageTestTable();
              testTable.pack();
              testTable.setVisible(true);
              testTable.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }If anyone could help or point me in the right direction, I'd appreciate it.
    Ruanae

    This is an example I published some while ago -
    import java.awt.*;
    import javax.swing.*;
    import javax.swing.table.*;
    public class Fred120 extends JPanel
        static final Object[][] tableData =
            {1, new Double(10.0)},
            {2, new Double(20.0)},
            {3, new Double(50.0)},
            {4, new Double(10.0)},
            {5, new Double(95.0)},
            {6, new Double(60.0)},
        static final Object[] headers =
            "One",
            "Two",
        public Fred120() throws Exception
            super(new BorderLayout());
            final DefaultTableModel model = new DefaultTableModel(tableData, headers);
            final JTable table = new JTable(model);
            table.getColumnModel().getColumn(1).setCellRenderer( new LocalCellRenderer(120.0));
            add(table);
            add(table.getTableHeader(), BorderLayout.NORTH);
        public class LocalCellRenderer extends DefaultTableCellRenderer
            private double v = 0.0;
            private double maxV;
            private final JPanel renderer = new JPanel(new GridLayout(1,0))
                public void paintComponent(Graphics g)
                    super.paintComponent(g);
                    g.setColor(Color.CYAN);
                    int w = (int)(getWidth() * v / maxV + 0.5);
                    int h = getHeight();
                    g.fillRect(0, 0, w, h);
                    g.drawRect(0, 0, w, h);
            private LocalCellRenderer(double maxV)
                this.maxV = maxV;
                renderer.add(this);
                renderer.setOpaque(true);
                renderer.setBackground(Color.YELLOW);
                renderer.setBorder(null);
                setOpaque(false);
                setHorizontalAlignment(JLabel.CENTER);
            public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int col)
                final JLabel label = (JLabel) super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, col);
                if (value instanceof Double)
                    v = ((Double)value).doubleValue();
                return renderer;
        public static void main(String[] args) throws Exception
            final JFrame frame = new JFrame("Fred120");
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.setContentPane(new Fred120());
            frame.pack();
            frame.setLocationRelativeTo(null);
            frame.setVisible(true);
    }

  • Conditionally Color a row based on the Day of the Week for that row ?

    Hi,
    I have a Table containing some timing entries for each day. I have been trying to format some rows depending on a value in one of the columns for that row. What I would like to achieve is color the cell background gray for every row where the Date found in the first Column isn't a Week Day.
    I have been trying many things by now, but can't seem to figure it out. Does anyone have suggestions ? I have included a screenshot of what I would like to achieve :
    Thanks a lot in advance,
    Stefaan
    Message was edited by: Stefaan Lesage

    Variations on my post linked in Badunit's message here:
    You'll need a second table with one column and as many rows as Table 1 (which contains the dates).
    The formula for Table 2 assumes the dates are in column B of Table 1.
    =OR(WEEKDAY(Table 1::B)=1,WEEKDAY(Table 1::B)=7)
    Enter the formula in the same row as the first data row in Table 1, and Fill it down.
    Rule for conditional formatting for all cells in Table 2: Equals TRUE
    Other instructions as in the linked message.
    Regards,
    Barry

  • Getting ClassCastException When Trying To Color JTable Row?

    hi there
    i'm trying to set color for JTable Rows Using the method prepareRenderer
    and get the values of the second column which contains integer values
    and if it contain 0 integer value set the color row as red
    its already works and the row with 0 is set to red but when i try to select any cell in the table
    i'm getting
    java.lang.ClassCastException: java.lang.String cannot be cast to java.lang.Integerat prepareRenderer
    although the second row which i'm trying to test it's values is Integer not String????????????
    here's the code:
    import javax.swing.border.*;
    import java.awt.*;
    import javax.swing.*;
    import javax.swing.table.*;
    import java.awt.event.*;
    import javax.swing.JFrame;
    public class Column_Filter {
      static JTable table;
    static DefaultTableModel dtm;  
        public static void main(String[] args) {
             String[]columns={"Name","Number","Price"};
             Object[][]data={  {"a",new Integer(5),new Integer(200)}
             ,{"b",new Integer(7),new Integer(400)}
             ,{"c",new Integer(0),new Integer(100)}
             ,{"d",new Integer(8),new Integer(800)}
             ,{"e",new Integer(3),new Integer(300)}         
             dtm=new DefaultTableModel(data,columns);
                        table=new JTable(dtm){
                      public Class getColumnClass(int column)
                        return getValueAt(0, column).getClass();
                             public Component prepareRenderer(TableCellRenderer renderer, int row, int column)
                        Component c = super.prepareRenderer(renderer, row, column);
                        if (!c.getBackground().equals(getSelectionBackground()))
                             Integer type = (Integer)getModel().getValueAt(row, 1);
                             if(type!=null)                                                            
                             c.setBackground(type==0 ? Color.RED : Color.WHITE );
                        else
                        c.setBackground(Color.white);
                        return c;
             TableColumnModel columnModel = table.getColumnModel();
             TableColumn col1 = columnModel.getColumn(1);         
             col1.setCellEditor(new TableEditor());
             TableColumn col2 = columnModel.getColumn(2);
             col2.setCellEditor(new TableEditor());
             table.setPreferredScrollableViewportSize(new Dimension(280,160));
             JScrollPane scroll=new JScrollPane(table);
             JLabel label=new JLabel("Column Stuff",JLabel.CENTER);
             JPanel panel=new JPanel();
             panel.add(scroll);
            JFrame frame=new JFrame("Column Stuff");
            frame.add(label,BorderLayout.NORTH);
            frame.add(panel,BorderLayout.CENTER);
            frame.setSize(300,300);
            frame.setResizable(false);
            frame.setVisible(true);
            frame.setLocationRelativeTo(null);
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                 table=new JTable();     
                   table.setModel(new DefaultTableModel(new Object [][][] {},new String [] {"Name", "Number","Price"}) {
                Class[] types = new Class [] {
                    java.lang.String.class, java.lang.String.class,java.lang.String.class
                public Class getColumnClass(int columnIndex) {
                    return types [columnIndex];
          class TableEditor extends DefaultCellEditor
              TableEditor()
                   super( new JTextField() );               
                setClickCountToStart(0);
              public boolean stopCellEditing()
                        String editingValue = (String)getCellEditorValue();
                    if(!editingValue.equals("")){
                 try
                int i = Integer.parseInt(editingValue);
                catch(NumberFormatException nfe)
                ((JComponent)getComponent()).setBorder(new LineBorder(Color.red));       
                getComponent().requestFocusInWindow();      
                JOptionPane.showMessageDialog(null,"Data Input Error","Error",JOptionPane.ERROR_MESSAGE);
                return false;          
                    else{                                             
                     getComponent().requestFocusInWindow();
                     fireEditingCanceled();
                     JOptionPane.showMessageDialog(null,"Data Input Error","Error",JOptionPane.ERROR_MESSAGE);
                  return false;              
                   return super.stopCellEditing();
                   public Component getTableCellEditorComponent(
                   JTable table, Object value, boolean isSelected, int row, int column)
                   Component c = super.getTableCellEditorComponent(table, value, isSelected, row, column);
                   ((JComponent)c).setBorder(new LineBorder(Color.BLACK));
                   return c;
         }

    hi again camickr
    i changed the stopCellEditing as you mentioned
    changed the getCellEditorValue to return an integer
    and give exception and error message if the value can't be converted into integer(non numeric)
    but the problem is when i run the program and change the value in any cell with numeric values
    or with non numeric or not changing the value and press enter
    it give the error message meaning it cannot convert the value to integer
    even if enter an int or don't change the value ????????
    here's what i did
    import javax.swing.border.*;
    import java.awt.*;
    import javax.swing.*;
    import javax.swing.table.*;
    import java.awt.event.*;
    import javax.swing.JFrame;
    public class Column_Filter {
      static JTable table;
    static DefaultTableModel dtm;  
        public static void main(String[] args) {
             String[]columns={"Name","Number","Price"};
             Object[][]data={  {"a",new Integer(5),new Integer(200)}
             ,{"b",new Integer(7),new Integer(400)}
             ,{"c",new Integer(0),new Integer(100)}
             ,{"d",new Integer(8),new Integer(800)}
             ,{"e",new Integer(3),new Integer(300)}         
             dtm=new DefaultTableModel(data,columns);
                        table=new JTable(dtm){
                      public Class getColumnClass(int column)
                        return getValueAt(0, column).getClass();
                             public Component prepareRenderer(TableCellRenderer renderer, int row, int column)
                        Component c = super.prepareRenderer(renderer, row, column);
                        if (!c.getBackground().equals(getSelectionBackground()))
                             Integer type = (Integer)getModel().getValueAt(row, 1);                                                            
                             c.setBackground(type==0 ? Color.RED : Color.WHITE );
                        return c;
             TableColumnModel columnModel = table.getColumnModel();
             TableColumn col1 = columnModel.getColumn(1);         
             col1.setCellEditor(new TableEditor());
             TableColumn col2 = columnModel.getColumn(2);
             col2.setCellEditor(new TableEditor());
             table.setPreferredScrollableViewportSize(new Dimension(280,160));
             JScrollPane scroll=new JScrollPane(table);
             JLabel label=new JLabel("Column Stuff",JLabel.CENTER);
             JPanel panel=new JPanel();
             panel.add(scroll);
            JFrame frame=new JFrame("Column Stuff");
            frame.add(label,BorderLayout.NORTH);
            frame.add(panel,BorderLayout.CENTER);
            frame.setSize(300,300);
            frame.setResizable(false);
            frame.setVisible(true);
            frame.setLocationRelativeTo(null);
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                 table=new JTable();     
                   table.setModel(new DefaultTableModel(new Object [][][] {},new String [] {"Name", "Number","Price"}) {
                Class[] types = new Class [] {
                    java.lang.String.class, java.lang.Integer.class,java.lang.Integer.class
                public Class getColumnClass(int columnIndex) {
                    return types [columnIndex];
          class TableEditor extends DefaultCellEditor
              TableEditor()
                   super( new JTextField() );               
                setClickCountToStart(0);
              public boolean stopCellEditing()
                   try
                        Integer editingValue = (Integer)getCellEditorValue();
                   catch(ClassCastException exception)
               //when i enter any value in any cell this code is executed even i enter an int or don't change the value
                ((JComponent)getComponent()).setBorder(new LineBorder(Color.red));       
                getComponent().requestFocusInWindow();      
                JOptionPane.showMessageDialog(null,"Data Input Error","Error",JOptionPane.ERROR_MESSAGE);
                return false;
                   return super.stopCellEditing();
                   public Component getTableCellEditorComponent(
                   JTable table, Object value, boolean isSelected, int row, int column)
                   Component c = super.getTableCellEditorComponent(table, value, isSelected, row, column);
                   ((JComponent)c).setBorder(new LineBorder(Color.BLACK));
                   return c;
         }

Maybe you are looking for