Question

i am having one Jtable and assign rendered for column. Now i want to split particular cell into two parts so that i can provide two value in to it. Splitting can be through Cellrenderer or may be anything else.enter image description here

Was it helpful?

Solution

Use JPanel with GridLayout as the cell renderer:

public Component getTableCellRendererComponent(JTable table, Object value, 
  boolean isSelected, boolean hasFocus,int row,int col) {
    if (isSplitted(value) {
        JPanel panel = new JPanel(new GridLayout(1,2));
        JLabel left = new JLabel(getLeft(value));
        JLabel right = new JLabel(getRight(value));        
        panel.add(left);
        panel.add(right);    
        return panel; 
      } else {
        return super.getTableCellRendererComponent(
           table, value, isSelected, hasFocus, row, col)
      }
}  

Here getLeft, getRight and isSplitted are up to you to define for the value you render in that cell.

If makes sense, you can also optimize retaining an instance of this panel with the two labels; it is possible to reuse it on every call upon setting the required content. For the case when left and rights components are very different in size, BorderLayout may work better.

Similarly, you can provide the cell editor, just you need JTextField or the like as JLabel is not editable. Derive from AbstractCellEditor, overriding getCellEditorValue (return the value composed from the panel) and getTableCellEditorComponent (return the panel itself after setting the fields to the current value).

@Stifler has commented on my answer:

public Component getTableCellRendererComponent(JTable table, Object obj, 
    boolean isSelected,  boolean hasFocus, int row, int column) {
    Component cell = super.getTableCellRendererComponent(
      table, obj, isSelected, hasFocus, row, column);
    JPanel panel = new JPanel(new GridLayout(1, 2));
    if ("History".equals(obj)) {
        JTextField left = new JTextField("Left");
        left.setEditable(true);
        JTextField right = new JTextField("Right");
        left.setEditable(true);
        panel.add(left);
        panel.add(right);
        return panel;
    }
    return cell;
}  
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top