2

I found the code to select a specific column on click of a JTable header. For my module, if someone selects a JTable cell all the previous column selection must be erased. I sucessfully change table.setColumnSelectionAllowed(true); or table.setRowSelectionAllowed(false); alternatively in cell editor.

Now

  1. I am unable to restore the default selection foreground and background color.
  2. Unable to clean previous table cell selection once table header is selected after cell selection.

HeaderLocation.java

public class HeaderLocation {  
    private JTable getTable() {  
        int rows = 32, cols = 4;  
        String[] colIds = { "column 1", "column 2", "column 3", "column 4" };  
        Object[][] data = new Object[rows][cols];  
        for(int row = 0; row < rows; row++) {  
            for(int col = 0; col < cols; col++) {  
                data[row][col] = "item " + (row*cols+col+1);  
            }  
        }  
        DefaultTableModel model = new DefaultTableModel(data, colIds);  
        final JTable table = new JTable(model);  
        final JTableHeader header = table.getTableHeader();  
        Enumeration<TableColumn> columns = table.getColumnModel().getColumns();
        while(columns.hasMoreElements()){
            columns.nextElement().setCellEditor(new CustomCellEditor());
        }
        //table.setCellEditor(new CustomCellEditor());
        header.setReorderingAllowed(false);  
        header.addMouseListener(new MouseAdapter() {  
            public void mouseClicked(MouseEvent e) {  
                int col = header.columnAtPoint(e.getPoint());  
                System.out.printf("click cursor = %d%n",  
                                   header.getCursor().getType());  
                if(header.getCursor().getType() == Cursor.E_RESIZE_CURSOR)  
                    e.consume();  
                else {  
                    //System.out.printf("sorting column %d%n", col); 
                    table.setColumnSelectionAllowed(true);
                    table.setRowSelectionAllowed(false);
                    table.clearSelection();
                    table.setColumnSelectionInterval(col,col);
                    //tableModel[selectedTab].sortArrayList(col);  
                }  
            }  
        });  

        return table;  
    }  

    private JMenuBar getMenuBar() {  
        final JMenu view = new JMenu("view");  
        ActionListener l = new ActionListener() {  
            public void actionPerformed(ActionEvent e) {  
                JMenuItem item = (JMenuItem)e.getSource();  
                String className = item.getActionCommand();  
                changePLAF(className, view.getTopLevelAncestor());  
            }  
        };  
        UIManager.LookAndFeelInfo[] info = UIManager.getInstalledLookAndFeels();  
        for(int j = 0; j < info.length; j++) {  
            JMenuItem item = new JMenuItem(info[j].getName());  
            item.setActionCommand(info[j].getClassName());  
            item.addActionListener(l);  
            view.add(item);  
        }  
        JMenuBar menuBar = new JMenuBar();  
        menuBar.add(view);  
        return menuBar;  
    }  

    private void changePLAF(String className, Component c) {  
        try {  
            UIManager.setLookAndFeel(className);  
        } catch(ClassNotFoundException cnfe) {  
            System.err.println("class not found: " + cnfe.getMessage());  
        } catch(InstantiationException ie) {  
            System.err.println("instantiation: " + ie.getMessage());  
        } catch(IllegalAccessException iae) {  
            System.err.println("illegal access: " + iae.getMessage());  
        } catch(UnsupportedLookAndFeelException ulafe) {  
            System.err.println("unsupported laf: " + ulafe.getMessage());  
        }  
        SwingUtilities.updateComponentTreeUI(c);  
    }  

    public static void main(String[] args) {  
        HeaderLocation test = new HeaderLocation();  
        JFrame f = new JFrame();  
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);  
        f.setJMenuBar(test.getMenuBar());  
        f.getContentPane().add(new JScrollPane(test.getTable()));  
        f.pack();  
        f.setLocation(200,200);  
        f.setVisible(true);  
    }  
}  

CustomCellEditor.java

public class CustomCellEditor extends AbstractCellEditor implements TableCellEditor{

    private JComponent component = new JLabel();

    public Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected, int row, int column) {
        System.out.println(row + "," + column);
        //if(getClickCountToStart() == 2)
        //{
        try{    
            table.clearSelection();
            table.setColumnSelectionAllowed(false);
            table.setRowSelectionAllowed(false);
        }
        catch(Exception e)
        {
            System.out.println("Exception::->" + e.getMessage());
        }
        //}
         // Configure the component with the specified value
        component.setOpaque(isSelected);
        ((JLabel)component).setText((String)value);
        component.setForeground(table.getSelectionForeground());
        component.setBackground(table.getSelectionBackground());
        component.setEnabled(false);
        // Return the configured component
        return component;
        }

    @Override
    public Object getCellEditorValue() {
        // TODO Auto-generated method stub
        return ((JLabel)component).getText();
    }
}

I would really appreciate any help related with this.

Michael Yaworski
  • 13,410
  • 19
  • 69
  • 97
user1709952
  • 169
  • 2
  • 7
  • 21
  • 1
    that's not an editor! Please read the appropriate tutorial chapter (see the reference in the swing tag wiki) to understand the concepts of renderer/editor – kleopatra Dec 09 '13 at 13:51
  • unrelated: even if it were a full-fledged editor (aka: serving its role to _change_ the cell content), it would be misbehaving severely because it _must not_ change the state of the caller. – kleopatra Dec 09 '13 at 13:53
  • Now if it is like that How can I revert the column selection into cell selection when user clicks on a specific cell. – user1709952 Dec 09 '13 at 14:04
  • use a mouseListener (and don't forget to read the tutorial :) – kleopatra Dec 09 '13 at 14:14
  • Thanks kleopatra. I just added code for a table mouse listener as below:- – user1709952 Dec 09 '13 at 14:28

2 Answers2

1
new JTable( model )
        {
            public Component prepareRenderer(TableCellRenderer renderer, int row, int column)
            {
                Component c = super.prepareRenderer(renderer, row, column);

                //  Color row based on a cell value

                if (isRowSelected(row)){ //When A row is selected
                                   c.setBackground(getBackground());//Set Background
                                   c.setForeground(color.RED);
                }

                return c;
            }
// Use if(!isRowSelected(row)){} if want to change non-selected row color or background
}
mKorbel
  • 109,525
  • 20
  • 134
  • 319
sampopes
  • 2,646
  • 1
  • 22
  • 34
0

Thanks kleopatra. I just added code for a table mouse listener as below:-

table.addMouseListener(new MouseAdapter() {  
            public void mouseClicked(MouseEvent e) {  

                    //System.out.printf("sorting column %d%n", col); 
                    table.setColumnSelectionAllowed(false);
                    table.setRowSelectionAllowed(false);
                    table.setCellSelectionEnabled(true);
                    //tableModel[selectedTab].sortArrayList(col);  

            }  
        });  

It would resolve the problem. Just removed all the cell editor code. There is a initial Column selection which is present, but it works fine.

user1709952
  • 169
  • 2
  • 7
  • 21