1

I've two questions

1.I want to change color of a Cell of JTable on mouse click. I've added a listener, like toggle between two colors, if currently it is green, it should turn to blow on other click

String[][] data = new String[rows][columns];
DefaultTableModel model = new DefaultTableModel(data, header);
JTable table = new JTable(model);
table.addMouseListener(new CellClickListener());

// Using following MouseListener

public class CellClickListener extends MouseAdapter{
  public void mouseClicked(MouseEvent e) {
    JTable target = (JTable)e.getSource();
    int row = target.getSelectedRow();
    int column = target.getSelectedColumn();
    // How to getCell object here and change its background color to clicked cell
  }
}

2.How can I set different column width, like firstColumn.setWidth(20), secondColumn.setWidth(40). I've already disabled auto resize table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);

Yousuf Soomro
  • 169
  • 2
  • 3
  • 10
  • 1. you have to reset setBackdround(table.getBackground()) 2. depends of what do you really want to do (for AUTO_RESIZE_OFF loop in column model and to setPreferredSize) – mKorbel Mar 06 '14 at 13:56
  • Sorry i don't get it. setBackground() on which object? – Yousuf Soomro Mar 06 '14 at 14:06
  • Take a look > http://stackoverflow.com/questions/7181699/changing-swing-jtable-cell-colors/7182010#7182010 – guisantogui Mar 06 '14 at 14:07
  • I've seen that already, but in render only works only time of creation, but I want to change background on CLICK event, using a listener. – Yousuf Soomro Mar 06 '14 at 14:10
  • 1
    for 1, I still have no idea for it (I'm looking for an answer), but for 2: take a look at [this](http://stackoverflow.com/questions/16113950/jtable-change-column-font) - look at the code of the question (SetPreferredWidth). Maybe not the best option, but it works – Frakcool Mar 07 '14 at 16:34
  • Frakcool: Thanks, got second question solved already, but for 1. answer provided by @Gabriel Câmara is much closer, it changes suppose cell A2's background to green, but after that if i click other cell suppose B5, B5's background turns into green but A2's background turns into white again because of render. – Yousuf Soomro Mar 07 '14 at 20:14

2 Answers2

2

You have to create your own CellRenderer and also use a MouseAdapter Here's an SSCCE to elucidate what I mean: Hope it helps =)

public class JTableTest extends JFrame {

    private JPanel      contentPane;
    private JScrollPane scrollPane;
    private JTable      table;
    private int         col;
    private int         rowz;

    /**
     * Launch the application.
     */
    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    teste frame = new teste();
                    frame.setVisible(true);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    /**
     * Create the frame.
     */
    public JTableTest() {
        initComponents();
    }

    private void initComponents() {
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setBounds(100, 100, 450, 300);
        contentPane = new JPanel();
        contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
        contentPane.setLayout(new BorderLayout(0, 0));
        setContentPane(contentPane);

        scrollPane = new JScrollPane();
        contentPane.add(scrollPane, BorderLayout.CENTER);

        table = new JTable();
        table.setModel(new DefaultTableModel(new Object[][] { { "", null, null, "" }, { null, null, null, null }, { null, null, null, "" },
                        { null, null, null, null }, }, new String[] { "Column 0", "Column 1", "Column 2", "Column 3" }));
        table.getColumnModel().getColumn(0).setMinWidth(200); // Here's how to
                                                                // change a
                                                                // column width
        scrollPane.setViewportView(table);
        table.setDefaultRenderer(Object.class, new CustomModel());
        table.addMouseListener(new CustomListener());
    }

    public class CustomListener extends MouseAdapter {
        @Override
        public void mouseClicked(MouseEvent arg0) {
            super.mouseClicked(arg0);
            // Select the current cell
            rowz = table.getSelectedRow();
            col = table.getSelectedColumn();

            // Repaints JTable
            table.repaint();
        }
    }

    public class CustomModel extends DefaultTableCellRenderer {

        /**
         * 
         */
        private static final long   serialVersionUID    = 1L;

        @Override
        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);
            Color c = Color.WHITE;
            if (isSelected && row == rowz & column == col)
                c = Color.GREEN;
            label.setBackground(c);
            return label;
        }
    }

}
Gabriel Câmara
  • 1,249
  • 15
  • 22
1

I have been working on the same issue for some days. I have developed a general function

setColorAtCell(Jtable table,Color colr,int row,int column)

which could do things in much better way.

Here is the code which is working for the above question You can also checkout the code from my github

import java.awt.Color;

import java.awt.Component;

import javax.swing.JOptionPane;

import javax.swing.JTable;

import javax.swing.table.DefaultTableCellRenderer;



public class ChangeCellColorJTable extends javax.swing.JFrame {

    public static Color[][] table_color = new Color[40][40];
    //this array is used to change the table color

    public static Object[][] table_value = new Object[40][40];
    //this array is used to change the table values

    public ChangeCellColorJTable() {
        initComponents();
        initTable();                    //Initializing the table
        refreshtable(mytable,1,1);      
    }

    public static void initTable(){
        int i,j;
        Object[][] data = new Object[][]{
                {10,10},
                {11,11},
                {12,12},
                {13,13}
        };
        for(i = 0;i < 4;i++ ){
            for(j = 0;j<2;j++){             
                mytable.setValueAt(data[i][j], i, j);   //Setting values in Jtable    
                table_value[i][j] = data[i][j];         //Setting same values table array 
            }
        }
        for(i = 0;i<4;i++){
            for(j = 0;j<2;j++){
                table_color[i][j] = Color.getColor("#f9f4bd");  //Setting initial color of the table
                                                                //Not Mandatory
            }
        }
    }
    private void initComponents() {         //These code is to initialize the Components to be Displayed
        jScrollPane1 = new javax.swing.JScrollPane();
        mytable = new javax.swing.JTable();
        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        mytable.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null},
                {null, null},
                {null, null},
                {null, null}
            },
            new String [] {
                "Title 1", "Title 2"
            }
        ));
        mytable.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                mytableMouseClicked(evt);
            }
        });
        jScrollPane1.setViewportView(mytable);
        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 375, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(13, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap(13, Short.MAX_VALUE)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 275, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap())
        );
       pack();
    }
    //MouseClicked on Table Event
    private void mytableMouseClicked(java.awt.event.MouseEvent evt) {           //MouseClickEvent                             
        int row,column;
        Color colr = Color.CYAN;
        JTable target = (JTable)evt.getSource();
        row = target.getSelectedRow();
        column = target.getSelectedColumn();
        setColorAtCell(mytable,colr,row,column);        
    }           

    //referesh table function by call custom_renderer
    public static void refreshtable(JTable table,int row,int column){
        int i;
        try{
            mytable.getColumnModel().getColumn(column).setCellRenderer(new Custom_Renderer());
        }catch(Exception e){
            JOptionPane.showMessageDialog(null, "error there");
        }
    }
    //this function could be used for changing the color at specific cell
    //Provided we use a Table Color Array (table_color)
    public static void setColorAtCell(JTable table,Color colr,int row,int column){
        table_color[row][column] = colr;
        refreshtable(table,row,column);
        refreshtable(table,row,column);
    }

    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new ChangeCellColorJTable().setVisible(true);
            }
        });
    }

    private javax.swing.JScrollPane jScrollPane1;
    public static javax.swing.JTable mytable;               
}


class Custom_Renderer extends DefaultTableCellRenderer 
{
    Custom_Renderer(){

    }

    @Override
    public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column)
    {
        Component cellComponent = super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
        Object value_present = table.getValueAt(row, column);
        Object value_in_table = ChangeCellColorJTable.table_value[row][column];
        if(value_present.equals(value_in_table)){           //This condition I used so that the Specific cell come into the condition
            Color color = ChangeCellColorJTable.table_color[row][column];
            cellComponent.setBackground(color);
        }else{
            cellComponent.setBackground(Color.blue);
        }
        return cellComponent;
    }
}
Frakcool
  • 10,915
  • 9
  • 50
  • 89
Reck
  • 1,388
  • 11
  • 20
  • 1
    Please describe your approach in the answer and include relevant code snippets. – Maciej Lach Sep 25 '15 at 06:01
  • I'll take out the downvote once you place your code *here* (Stack Overflow) into your answer. Having external links isn't a good idea. Also as Maciej Lach said, describe what your code does. And please, take out your name from answer, it's already seen on your profile. And btw, why are you thanking us? – Frakcool Sep 25 '15 at 06:06
  • This does not really answer the question. If you have a different question, you can ask it by clicking [Ask Question](http://stackoverflow.com/questions/ask). You can also [add a bounty](http://stackoverflow.com/help/privileges/set-bounties) to draw more attention to this question once you have enough [reputation](http://stackoverflow.com/help/whats-reputation). – André Schild Sep 25 '15 at 06:31
  • How rude it was. Anyways I have changed according to your comments. – Reck Sep 25 '15 at 08:04
  • @Frakcool I have removed the link ,"thank you" and "my name" as well . Sorry all, I am new to stackoverflow. I hardly know any ettiquettes in writing answers here.If anythings wrong now in the answer, please correct me. – Reck Sep 25 '15 at 08:08
  • @AndréSchild , it does answer the answer the question. – Reck Sep 25 '15 at 08:10
  • @AndréSchild. Its a complete code please run and check whether the question is answered or not. If anythings wrong or it does not really answer the question.Please correct me. – Reck Sep 25 '15 at 08:13
  • We could give condition in the renderer function. To workout the answer for "if currently it is green, it should turn to blow on other click" – Reck Sep 25 '15 at 08:21
  • @Reck if you're new at writing answers here, then please [Take the tour](http://stackoverflow.com/tour), format your code correctly and check if your code really solves the question. I should also recommend you reading other people answers so you get an idea on how an answer should look like. – Frakcool Sep 25 '15 at 14:36
  • And I'm sorry if it sounded rude, it's just we have little time to help others with their questions, and we're grateful that you made this api, and that you want to distribute it, but spamming the same answer on 4 different questions could be seen as spam. That's why I'm trying to prevent that and giving you feedback so you can improve the quality of your answer. Please take the tour and read some other questions and answers from other users, so you can compare them with your 1st answer. – Frakcool Sep 25 '15 at 16:28
  • I was trying to make a general function to change – Reck Sep 26 '15 at 04:35
  • setColorAtCell() something like that to change the cell color. I posted my answer in different question because they were related to changing a cell in Jtable. Just by taking to extra arrays (table_color & table_value). We could change these arrays by whatever condition we want. And then simply call the renderer fucntion. Thats what setColorAtCell() does. Changes the values in the table_color and calls custom_renderer. – Reck Sep 26 '15 at 04:45
  • Actually I should have flagged the answers in different questions. There I accept my mistake. Next time before participating I would be using Correct Format. – Reck Sep 26 '15 at 04:48
  • @Reck I edited tyour answer so you can see an example on how it should look like and compare it with your past answers :) – Frakcool Sep 26 '15 at 15:48
  • Yeah thats good format I guess.Only one question from my side @Frakcool. Does my code didn't solved the above question. I found it solving the above question thats why I thought to answer. – Reck Sep 26 '15 at 21:29
  • Actually yes, but I had my downvote still until you had confirmed you received and looked at my edit, that way, you'll have better questions / answers which fit on SOF format. But I hadn't tested your code until 5 mins ago. Just keep an eye on these recommendations :) – Frakcool Sep 26 '15 at 21:49