0

I have this code and i want to color each cell with a different color for example i wanna color cell number 1,1 with red and cell number 1,2 with light red and so on.How is it possible?i went through many examples but all of them show how to color a cell on mouse click or over and i want niether of it.Thanks in advance.

package test;

public class ModelJTable extends JFrame {
    private DefaultTableModel model;

    private JTable table;

    public ModelJTable() throws IOException {
        super();
        model = new DefaultTableModel();
        model.addColumn("price");
        model.addColumn("quantity");
        model.addColumn("buy");
        model.addColumn("sell");
        String array[][] = new String[6][6];
        array[0][0] = "35";
        array[0][1] = "1";
        array[0][2] = "2";
        array[1][0] = "34";
        array[1][1] = "2";
        array[1][2] = "3";
        array[2][0] = "37";
        array[2][1] = "2";
        array[2][2] = "6";
        array[3][0] = "33";
        array[3][1] = "7";
        array[3][2] = "8";
        array[4][0] = "34";
        array[4][1] = "9";
        array[4][2] = "4";
        array[5][0]="35";
        array[5][1]="9";
        array[5][2]="6";

        String mainarray[][] = new String[6][6];
                //copy all elements of array to mainarray


        for(int i=0;i<5;i++)
        {
            String temp[]={""};
            model.addRow(temp);
        }
        for (int i = 5; i < 10; i++) {
            model.insertRow(i, array[i-5]);
            // System.out.print(mainarray[i][j]+" ");
        }
        table = new JTable(model);

        JTextField textBox=new JTextField();
        TableColumn soprtColumn=table.getColumnModel().getColumn(1);

        soprtColumn.setCellEditor(new DefaultCellEditor (textBox));

        table.setCellSelectionEnabled(true);

        textBox.setBackground(Color.RED);
        JPanel inputPanel = new JPanel();
        inputPanel.add(addButton);
        inputPanel.add(removeButton);
        Container container = getContentPane();
        container.add(new JScrollPane(table), BorderLayout.CENTER);
        container.add(inputPanel, BorderLayout.NORTH);

        setDefaultCloseOperation(EXIT_ON_CLOSE);
        setSize(400, 300);
        setVisible(true);
    }

        public static void main(String args[]) throws IOException {
        new ModelJTable();
    }
     public Component getTableCellRendererComponent
     (JTable table, Object value, boolean isSelected,
     boolean hasFocus, int row, int column) 
  {
      Component cell = model.getTableCellRendererComponent
         (table, value, isSelected, hasFocus, row, column);
      if( value instanceof Integer )
      {
          Integer amount = (Integer) value;
          if( amount.intValue() < 0 )
          {
              cell.setBackground( Color.red );
              // You can also customize the Font and Foreground this way
              // cell.setForeground();
              // cell.setFont();
          }
          else
          {
              cell.setBackground( Color.white );
          }
      }
      return cell;
  }
}
mKorbel
  • 109,525
  • 20
  • 134
  • 319
maddy
  • 109
  • 4
  • 13
  • 1
    This question has been answered dozens of times on SO (see the "Related" links in the right column of this question). The answer is always the same: use a custom `TableCellRenderer`. Google "Swing tutorial JTable renderer". – Guillaume Polet Jun 04 '13 at 12:27
  • 1
    [link]http://stackoverflow.com/questions/5673430/java-jtable-change-cell-color – Jannis Alexakis Jun 04 '13 at 12:30
  • @Gulliaume Polet ,@Jannis Alexakis....But this is not what i m looking for??i want my table to be colored when i display it – maddy Jun 04 '13 at 12:39
  • 2
    Well yes, this is what the example does. It shows you how to subclass the DefaultTableCellRenderer in order to color your cells which ever way you like. If this isn´t what you´re looking for, then I don´t understand your question. – Jannis Alexakis Jun 04 '13 at 12:43
  • @maddy This is exactly what you are asking for. Here is another example of what you ask: http://stackoverflow.com/questions/7181699/changing-swing-jtable-cell-colors If this is not what you want, then your question is unclear. – Guillaume Polet Jun 04 '13 at 14:03

1 Answers1

2
  • there are a few mistakes I can't comment something

  • change if (isRowSelected(row) && isColumnSelected(column)) { to if ((row == 2) && (column == 2)) { (have to test before if number of rows/columns is greater than ...) then

enter image description here

from code

import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
import javax.swing.border.LineBorder;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.table.*;

public class RemoveAddRows extends JFrame {

    private static final long serialVersionUID = 1L;
    private Object[] columnNames = {"Type", "Company", "Shares", "Price"};
    private Object[][] data = {
        {"Buy", "IBM", Integer.valueOf(1000), Double.valueOf(80.50)},
        {"Sell", "MicroSoft", Integer.valueOf(2000), Double.valueOf(6.25)},
        {"Sell", "Apple", Integer.valueOf(3000), Double.valueOf(7.35)},
        {"Buy", "Nortel", Integer.valueOf(4000), Double.valueOf(20.00)}
    };
    private JTable table;
    private DefaultTableModel model;
    private javax.swing.Timer timer = null;

    public RemoveAddRows() {
        model = new DefaultTableModel(data, columnNames) {
            private static final long serialVersionUID = 1L;

            @Override
            public Class getColumnClass(int column) {
                return getValueAt(0, column).getClass();
            }
        };
        table = new JTable(model) {
            private static final long serialVersionUID = 1L;

            @Override
            public Component prepareRenderer(TableCellRenderer renderer, int row, int column) {
                Component c = super.prepareRenderer(renderer, row, column);
                if (isRowSelected(row) && isColumnSelected(column)) {
                    ((JComponent) c).setBorder(new LineBorder(Color.red));
                }
                return c;
            }
        };
        DefaultTableCellRenderer stringRenderer = (DefaultTableCellRenderer) table.getDefaultRenderer(String.class);
        stringRenderer.setHorizontalAlignment(SwingConstants.CENTER);
        ListSelectionModel rowSelMod = table.getSelectionModel();
        rowSelMod.addListSelectionListener(new ListSelectionListener() {
            @Override
            public void valueChanged(ListSelectionEvent e) {
                int row = table.getSelectedRow();
                int col = table.getSelectedColumn();
                String str = "Selected Row(s): ";
                int[] rows = table.getSelectedRows();
                for (int i = 0; i < rows.length; i++) {
                    str += rows[i] + " ";
                }
                str += "Selected Column(s): ";
                int[] cols = table.getSelectedColumns();
                for (int i = 0; i < cols.length; i++) {
                    str += cols[i] + " ";
                }
                str += "Selected Cell: " + table.getSelectedRow() + ", " + table.getSelectedColumn();
                System.out.println(str);
                Object value = table.getValueAt(row, col);
                System.out.println(String.valueOf(value));
            }
        });
        table.setPreferredScrollableViewportSize(table.getPreferredSize());
        JScrollPane scrollPane = new JScrollPane(table);
        add(scrollPane);
        JButton button1 = new JButton("Remove all rows");
        button1.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent arg0) {
                if (model.getRowCount() > 0) {
                    for (int i = model.getRowCount() - 1; i > -1; i--) {
                        model.removeRow(i);
                    }
                }
                System.out.println("model.getRowCount() --->" + model.getRowCount());
            }
        });
        JButton button2 = new JButton("Add new rows");
        button2.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent arg0) {
                start();
            }
        });
        JPanel southPanel = new JPanel();
        southPanel.add(button1);
        southPanel.add(button2);
        add(southPanel, BorderLayout.SOUTH);
    }

    private void start() {
        timer = new javax.swing.Timer(2500, updateCol());
        timer.start();
    }

    public Action updateCol() {
        return new AbstractAction("text load action") {
            private static final long serialVersionUID = 1L;

            @Override
            public void actionPerformed(ActionEvent e) {
                DefaultTableModel model = (DefaultTableModel) table.getModel();
                Object[] data0 = {"Buy", "IBM", Integer.valueOf(1000), Double.valueOf(80.50)};
                model.addRow(data0);
                Object[] data1 = {"Sell", "MicroSoft", Integer.valueOf(2000), Double.valueOf(6.25)};
                model.addRow(data1);
                Object[] data2 = {"Sell", "Apple", Integer.valueOf(3000), Double.valueOf(7.35)};
                model.addRow(data2);
                Object[] data3 = {"Buy", "Nortel", Integer.valueOf(4000), Double.valueOf(20.00)};
                model.addRow(data3);
                System.out.println("model.getRowCount() --->" + model.getRowCount());
                timer.stop();
                int rowIndex = table.getRowCount() - 1;
                table.changeSelection(rowIndex, 0, false, false);
            }
        };
    }

    public static void main(String[] args) {
        javax.swing.SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                RemoveAddRows frame = new RemoveAddRows();
                frame.setDefaultCloseOperation(EXIT_ON_CLOSE);
                frame.pack();
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
            }
        });
    }
}
mKorbel
  • 109,525
  • 20
  • 134
  • 319
  • Thanks a lot for your help but this is not what i want.This is changing the grid color when i click on a particular cell but i want the entire cell to be filled with color and not after mouse selection but i want the cell 2,2 to be colored when i D-I-S-P-L-A-Y it.Thankyou for giving your time for reading and understanding my horrible code – maddy Jun 05 '13 at 06:33
  • re_read my point second change if (isRowSel....(there no issue to code whole code by yours..., rest I leave to you), you can to add any else if (another coordinated), but then is required to use rollback defined in else (table.getBackground) – mKorbel Jun 05 '13 at 06:46