Google Tag Manager

2013/05/29

Column spanning TableCellRenderer

Code

class ColumnSpanningCellRenderer extends JPanel implements TableCellRenderer{
  private final JTextArea textArea = new JTextArea(2, 999999);
  private final JLabel label = new JLabel();
  private final JLabel iconLabel = new JLabel();
  private final JScrollPane scroll = new JScrollPane();

  public ColumnSpanningCellRenderer() {
    super(new BorderLayout(0, 0));

    scroll.setViewportView(textArea);
    scroll.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_NEVER);
    scroll.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
    scroll.setBorder(BorderFactory.createEmptyBorder());
    scroll.setViewportBorder(BorderFactory.createEmptyBorder());
    scroll.setOpaque(false);
    scroll.getViewport().setOpaque(false);

    textArea.setBorder(BorderFactory.createEmptyBorder());
    textArea.setMargin(new Insets(0, 0, 0, 0));
    textArea.setForeground(Color.RED);
    textArea.setEditable(false);
    textArea.setFocusable(false);
    textArea.setOpaque(false);

    iconLabel.setBorder(BorderFactory.createEmptyBorder(0, 4, 0, 4));
    iconLabel.setOpaque(false);

    Border b1 = BorderFactory.createEmptyBorder(2, 2, 2, 2);
    Border b2 = BorderFactory.createMatteBorder(0, 0, 1, 1, Color.GRAY);
    label.setBorder(BorderFactory.createCompoundBorder(b2, b1));

    setBackground(textArea.getBackground());
    setOpaque(true);
    add(label, BorderLayout.NORTH);
    add(scroll);
  }
  @Override public Component getTableCellRendererComponent(
      JTable table, Object value, boolean isSelected,
      boolean hasFocus, int row, int column) {
    Test test;
    if(value instanceof Test) {
      test = (Test)value;
      add(iconLabel, BorderLayout.WEST);
    }else{
      int mrow = table.convertRowIndexToModel(row);
      String title = value!=null ? value.toString() : "";
      Test t = (Test)table.getModel().getValueAt(mrow, 0);
      String text = t!=null ? t.text : "";
      Icon icon = t!=null ? t.icon : null;
      test = new Test(title, icon, text);
      remove(iconLabel);
    }
    label.setText(test.title);
    textArea.setText(test.text);
    iconLabel.setIcon(test.icon);

    Rectangle cr = table.getCellRect(row, column, false);
    if(column!=0) cr.x -= iconLabel.getPreferredSize().width;
    scroll.getViewport().setViewPosition(cr.getLocation());
    if(isSelected) {
      setBackground(Color.ORANGE);
    }else{
      setBackground(Color.WHITE);
    }
    return this;
  }
}

References

No comments:

Post a Comment