Skip to Main Content

Java SE (Java Platform, Standard Edition)

Announcement

For appeals, questions and feedback about Oracle Forums, please email oracle-forums-moderators_us@oracle.com. Technical questions should be asked in the appropriate category. Thank you!

How to prevent using custom cell renderer from disabling row selection?

843806May 18 2007 — edited May 19 2007
Hi again,
As thread's title says, is there a way to enable row selection in JTable when I use custom cell renderer? When I use custom cell renderer row selection (as well as any other selection) seems to be disabled...
Here's sample code that shows what I mean:
import java.awt.*;
import javax.swing.*;
import javax.swing.table.*;

class CellRender extends JLabel implements TableCellRenderer {
	JFrame frame;
	JPanel panel;
	JTable table;
	JScrollPane scrollPane;
	
	public static void main(String[] args) {
		CellRender cr = new CellRender();
	}
	
	CellRender() {
           frame = new JFrame();
	   frame.setLocation(300, 300);
	   frame.setTitle("Test app");
	   frame.setPreferredSize(new Dimension(450, 450));
	   frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
	   panel = new JPanel();
	   table = createTable();
	   scrollPane = new JScrollPane(table);
	   panel.add(scrollPane);
	   frame.add(panel);
	   frame.pack();
	   frame.setVisible(true);
	}
	
	public JTable createTable() {
	   String columns[] = {"Col A", "Col B"};
	   String data[][] = { {"A", "B"}, {"C", "D"} };
	   DefaultTableModel model = new DefaultTableModel(data, columns);
	   JTable table = new JTable(model);
           TableColumn column = null;
           for (int i = 0; i < 2; i++) {
		    column = table.getColumnModel().getColumn(i);   
// if I comment this line and use default renderer there's no problem with selecting rows 
		    column.setCellRenderer(this); 
	   }
	   table.setCellSelectionEnabled(true);
	   return table; 
	}

        public Component getTableCellRendererComponent(JTable table, Object value,
              boolean isSelected, boolean hasFocus, int rowIndex, int colIndex) {
          setText(value.toString());    
          setBorder(BorderFactory.createMatteBorder(0, 7, 0, 0, Color.GREEN));
          if (isSelected)
	  {
              setBackground(Color.RED);
              setForeground(table.getSelectionForeground());
          }
          else
          {
	      setBackground(Color.BLUE);
              setForeground(table.getForeground());
	  }
          return this;
      }
}
Comments
Locked Post
New comments cannot be posted to this locked post.
Post Details
Locked on Jun 16 2007
Added on May 18 2007
5 comments
611 views