Пример #1
0
  // This method from http://www.exampledepot.com/egs/javax.swing.table/PackCol.html
  public int packColumn(JTable table, int vColIndex, int margin) {
    DefaultTableColumnModel colModel = (DefaultTableColumnModel) table.getColumnModel();
    TableColumn col = colModel.getColumn(vColIndex);
    int width = 0;

    // Get width of column header
    TableCellRenderer renderer = col.getHeaderRenderer();
    if (renderer == null) {
      renderer = table.getTableHeader().getDefaultRenderer();
    }
    Component comp =
        renderer.getTableCellRendererComponent(table, col.getHeaderValue(), false, false, 0, 0);
    width = comp.getPreferredSize().width;

    // Get maximum width of column data
    for (int r = 0; r < table.getRowCount(); r++) {
      renderer = table.getCellRenderer(r, vColIndex);
      comp =
          renderer.getTableCellRendererComponent(
              table, table.getValueAt(r, vColIndex), false, false, r, vColIndex);
      width = Math.max(width, comp.getPreferredSize().width);
    }

    // Add margin
    width += 2 * margin;

    // Set the width
    col.setPreferredWidth(width);

    return width;
  }
 public Component getTableCellRendererComponent(
     JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
   final Color color = UIUtil.getTableFocusCellBackground();
   Component component;
   final Module module = value instanceof Module ? (Module) value : null;
   try {
     UIManager.put(UIUtil.TABLE_FOCUS_CELL_BACKGROUND_PROPERTY, table.getSelectionBackground());
     component =
         super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
     if (module != null) {
       setText(
           module.getName()
               + " ("
               + FileUtil.toSystemDependentName(module.getModuleFilePath())
               + ")");
     }
     if (component instanceof JLabel) {
       ((JLabel) component).setBorder(noFocusBorder);
     }
   } finally {
     UIManager.put(UIUtil.TABLE_FOCUS_CELL_BACKGROUND_PROPERTY, color);
   }
   component.setEnabled(ProcessedModulesTable.this.isEnabled());
   if (component instanceof JLabel) {
     final Icon icon = module != null ? ModuleType.get(module).getIcon() : null;
     JLabel label = (JLabel) component;
     label.setIcon(icon);
     label.setDisabledIcon(icon);
   }
   component.setForeground(isSelected ? table.getSelectionForeground() : table.getForeground());
   return component;
 }
Пример #3
0
 public void
     setColumnWidths() { // See
                         // "http://java.sun.com/docs/books/tutorial/uiswing/components/table.html#custom"
   int n = getModel().getColumnCount();
   for (int j = 0; j < n; ++j) {
     TableColumn column = getColumnModel().getColumn(j);
     TableCellRenderer headerRenderer = column.getHeaderRenderer();
     if (headerRenderer == null)
       headerRenderer = getTableHeader().getDefaultRenderer(); // the new 1.3 way
     Component columnComponent =
         headerRenderer.getTableCellRendererComponent(
             this, column.getHeaderValue(), false, false, -1, j);
     Component cellComponent =
         getDefaultRenderer(getColumnClass(j))
             .getTableCellRendererComponent(this, getModel().getValueAt(0, j), false, false, 0, j);
     int wantWidth =
         Math.max(
             columnComponent.getPreferredSize().width
                 + 10, // fudge factor ... seems to always be too small otherwise (on x86 Linux)
             cellComponent.getPreferredSize().width
                 + 10 // fudge factor ... seems to always be too small otherwise (on Mac OS X)
             );
     column.setPreferredWidth(wantWidth);
   }
 }
  public SimpleTextAttributes applyHighlighters(
      @NotNull Component rendererComponent,
      int row,
      int column,
      String text,
      boolean hasFocus,
      final boolean selected) {
    VcsLogHighlighter.VcsCommitStyle style = getStyle(row, column, text, hasFocus, selected);

    assert style.getBackground() != null
        && style.getForeground() != null
        && style.getTextStyle() != null;

    rendererComponent.setBackground(style.getBackground());
    rendererComponent.setForeground(style.getForeground());

    switch (style.getTextStyle()) {
      case BOLD:
        return SimpleTextAttributes.REGULAR_BOLD_ATTRIBUTES;
      case ITALIC:
        return SimpleTextAttributes.REGULAR_ITALIC_ATTRIBUTES;
      default:
    }
    return SimpleTextAttributes.REGULAR_ATTRIBUTES;
  }
Пример #5
0
  private int getHeaderHeight() {
    if ((header == null) || (header.getTable() == null)) {
      return 0;
    }
    int height = 0;
    boolean accomodatedDefault = false;
    TableColumnModel columnModel = header.getColumnModel();
    for (int column = 0; column < columnModel.getColumnCount(); column++) {
      TableColumn aColumn = columnModel.getColumn(column);
      boolean isDefault = (aColumn.getHeaderRenderer() == null);

      if (!isDefault || !accomodatedDefault) {
        Component comp = getHeaderRenderer(column);
        int rendererHeight = comp.getPreferredSize().height;
        height = Math.max(height, rendererHeight);

        // Configuring the header renderer to calculate its preferred size
        // is expensive. Optimise this by assuming the default renderer
        // always has the same height as the first non-zero height that
        // it returns for a non-null/non-empty value.
        if (isDefault && rendererHeight > 0) {
          Object headerValue = aColumn.getHeaderValue();
          if (headerValue != null) {
            headerValue = headerValue.toString();

            if (headerValue != null && !headerValue.equals("")) {
              accomodatedDefault = true;
            }
          }
        }
      }
    }
    return height + 2;
  }
 public Component getTableCellRendererComponent(
     JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
   final Color color = UIUtil.getTableFocusCellBackground();
   Component component;
   T t = (T) value;
   try {
     UIManager.put(UIUtil.TABLE_FOCUS_CELL_BACKGROUND_PROPERTY, table.getSelectionBackground());
     component =
         super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
     setText(t != null ? getItemText(t) : "");
     if (component instanceof JLabel) {
       ((JLabel) component).setBorder(noFocusBorder);
     }
   } finally {
     UIManager.put(UIUtil.TABLE_FOCUS_CELL_BACKGROUND_PROPERTY, color);
   }
   final MyTableModel model = (MyTableModel) table.getModel();
   component.setEnabled(
       ElementsChooser.this.isEnabled()
           && (myColorUnmarkedElements ? model.isElementMarked(row) : true));
   final ElementProperties properties = myElementToPropertiesMap.get(t);
   if (component instanceof JLabel) {
     final Icon icon =
         properties != null ? properties.getIcon() : t != null ? getItemIcon(t) : null;
     JLabel label = (JLabel) component;
     label.setIcon(icon);
     label.setDisabledIcon(icon);
   }
   component.setForeground(
       properties != null && properties.getColor() != null
           ? properties.getColor()
           : (isSelected ? table.getSelectionForeground() : table.getForeground()));
   return component;
 }
Пример #7
0
  @Override
  public int getRowHeight() {
    if (myRowHeightIsComputing) {
      return super.getRowHeight();
    }

    if (myRowHeight < 0) {
      try {
        myRowHeightIsComputing = true;
        for (int row = 0; row < getRowCount(); row++) {
          for (int column = 0; column < getColumnCount(); column++) {
            final TableCellRenderer renderer = getCellRenderer(row, column);
            if (renderer != null) {
              final Object value = getValueAt(row, column);
              final Component component =
                  renderer.getTableCellRendererComponent(this, value, true, true, row, column);
              if (component != null) {
                final Dimension size = component.getPreferredSize();
                myRowHeight = Math.max(size.height, myRowHeight);
              }
            }
          }
        }
      } finally {
        myRowHeightIsComputing = false;
      }
    }

    if (myMinRowHeight == null) {
      myMinRowHeight = getFontMetrics(UIManager.getFont("Label.font")).getHeight();
    }

    return Math.max(myRowHeight, myMinRowHeight);
  }
 public Component getTableCellRendererComponent(
     JTable aTable,
     Object aNumberValue,
     boolean aIsSelected,
     boolean aHasFocus,
     int aRow,
     int aColumn) {
   /*
    * Implementation Note :
    * It is important that no "new" be present in this
    * implementation (excluding exceptions):
    * if the table is large, then a large number of objects would be
    * created during rendering.
    */
   if (aNumberValue == null) return this;
   Component renderer =
       super.getTableCellRendererComponent(
           aTable, aNumberValue, aIsSelected, aHasFocus, aRow, aColumn);
   Number value = (Number) aNumberValue;
   if (value.doubleValue() < 0) {
     renderer.setForeground(Color.red);
   } else {
     renderer.setForeground(fDarkGreen);
   }
   return this;
 }
 // Implementation of TableCellRenderer interface
 public Component getTableCellRendererComponent(
     JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
   TableCellRenderer rend = super.getCellRenderer(row, column);
   Component c =
       rend.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
   c.setBackground(getBack(isSelected, hasFocus, row, column));
   c.setForeground(getFore(isSelected, hasFocus, row, column));
   return c;
 }
 private int calcMaxContentColumnWidth(int columnIndex, int maxRowsToCheck) {
   int maxWidth = 0;
   for (int row = 0; row < maxRowsToCheck && row < getRowCount(); row++) {
     TableCellRenderer renderer = getCellRenderer(row, columnIndex);
     Component comp = prepareRenderer(renderer, row, columnIndex);
     maxWidth = Math.max(comp.getPreferredSize().width, maxWidth);
   }
   return maxWidth + UIUtil.DEFAULT_HGAP;
 }
  /**
   * This method gets the width of a cell, specified by a column and row number.
   *
   * @param row The column number.
   * @param column The row number.
   * @return The width of the cell data.
   */
  private int getCellDataWidth(int row, int column) {
    //  Inovke the renderer for the cell to calculate the preferred width

    TableCellRenderer cellRenderer = table.getCellRenderer(row, column);
    Component c = table.prepareRenderer(cellRenderer, row, column);
    int width = c.getPreferredSize().width + table.getIntercellSpacing().width;

    return width;
  }
 public Component getTableCellRendererComponent(
     JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
   Component component =
       myDelegate.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
   component.setEnabled(ElementsChooser.this.isEnabled());
   if (component instanceof JComponent) {
     ((JComponent) component).setBorder(null);
   }
   return component;
 }
 @Override
 public void mouseMoved(MouseEvent e) {
   Component component = e.getComponent();
   if (component != null) {
     if (getRootColumnOrNull(e) != null) {
       component.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
     } else {
       component.setCursor(null);
     }
   }
 }
 public void internalFrameClosed(InternalFrameEvent e) {
   Component cont = getParent();
   while ((cont != null) && (!(cont instanceof JInternalFrame))) {
     cont = cont.getParent();
   }
   if (cont != null) {
     if (!((JInternalFrame) cont).isClosed()) {
       refreshMe();
     }
   }
 }
Пример #15
0
 @Override
 public Component prepareRenderer(TableCellRenderer tcr, int row, int column) {
   Component c = super.prepareRenderer(tcr, row, column);
   if (isRowSelected(row)) {
     c.setForeground(getSelectionForeground());
     c.setBackground(getSelectionBackground());
   } else {
     c.setForeground(getForeground());
     c.setBackground(row % 2 == 0 ? EVEN_COLOR : getBackground());
   }
   return c;
 }
Пример #16
0
  @Override
  public Component prepareRenderer(TableCellRenderer renderer, int row, int column) {
    final Component result = super.prepareRenderer(renderer, row, column);
    final boolean selected =
        myExpandableItemsHandler.getExpandedItems().contains(new TableCell(row, column));

    // Fix GTK background
    if (UIUtil.isUnderGTKLookAndFeel()) {
      UIUtil.changeBackGround(this, UIUtil.getTreeTextBackground());
    }

    if (isTableDecorationSupported() && isStriped() && result instanceof JComponent) {
      final Color bg = row % 2 == 1 ? getBackground() : DECORATED_ROW_BG_COLOR;
      final JComponent c = (JComponent) result;
      final boolean cellSelected = isCellSelected(row, column);
      if (!cellSelected || (!hasFocus() && !getSelectionBackground().equals(c.getBackground()))) {
        c.setOpaque(true);
        c.setBackground(bg);
        for (Component child : c.getComponents()) {
          child.setBackground(bg);
        }
      }
    }

    if (!selected) return result;

    return new JComponent() {
      {
        add(result);
        setOpaque(false);
        setLayout(
            new AbstractLayoutManager() {
              @Override
              public Dimension preferredLayoutSize(Container parent) {
                return result.getPreferredSize();
              }

              @Override
              public void layoutContainer(Container parent) {
                Dimension size = parent.getSize();
                Insets i = parent.getInsets();
                Dimension pref = result.getPreferredSize();
                result.setBounds(
                    i.left,
                    i.top,
                    Math.max(pref.width, size.width - i.left - i.right),
                    size.height - i.top - i.bottom);
              }
            });
      }
    };
  }
  /*
   *  Calculated the width based on the column name
   */
  private int getColumnHeaderWidth(int column) {
    if (!isColumnHeaderIncluded) return 0;

    TableColumn tableColumn = table.getColumnModel().getColumn(column);
    Object value = tableColumn.getHeaderValue();
    TableCellRenderer renderer = tableColumn.getHeaderRenderer();

    if (renderer == null) {
      renderer = table.getTableHeader().getDefaultRenderer();
    }

    Component c = renderer.getTableCellRendererComponent(table, value, false, false, -1, column);
    return c.getPreferredSize().width;
  }
Пример #18
0
 // Overridden for performance reasons. ---->
 @Override
 public boolean isOpaque() {
   Color back = getBackground();
   Component p = getParent();
   if (Objects.nonNull(p)) {
     p = p.getParent();
   } // p should now be the JTable.
   boolean colorMatch =
       Objects.nonNull(back)
           && Objects.nonNull(p)
           && back.equals(p.getBackground())
           && p.isOpaque();
   return !colorMatch && super.isOpaque();
 }
Пример #19
0
  public void updateColumnSizes() {
    final JTableHeader header = getTableHeader();
    final TableCellRenderer defaultRenderer = header == null ? null : header.getDefaultRenderer();

    final RowSorter<? extends TableModel> sorter = getRowSorter();
    final List<? extends RowSorter.SortKey> current = sorter == null ? null : sorter.getSortKeys();
    ColumnInfo[] columns = getListTableModel().getColumnInfos();
    for (int i = 0; i < columns.length; i++) {
      final ColumnInfo columnInfo = columns[i];
      final TableColumn column = getColumnModel().getColumn(i);
      // hack to get sort arrow included into the renderer component
      if (sorter != null && columnInfo.isSortable()) {
        sorter.setSortKeys(
            Collections.singletonList(new RowSorter.SortKey(i, SortOrder.ASCENDING)));
      }

      final Component headerComponent =
          defaultRenderer == null
              ? null
              : defaultRenderer.getTableCellRendererComponent(
                  this, column.getHeaderValue(), false, false, 0, 0);

      if (sorter != null && columnInfo.isSortable()) {
        sorter.setSortKeys(current);
      }
      final Dimension headerSize =
          headerComponent == null ? new Dimension(0, 0) : headerComponent.getPreferredSize();
      final String maxStringValue;
      final String preferredValue;
      if (columnInfo.getWidth(this) > 0) {
        int width = columnInfo.getWidth(this);
        column.setMaxWidth(width);
        column.setPreferredWidth(width);
        column.setMinWidth(width);
      } else if ((maxStringValue = columnInfo.getMaxStringValue()) != null) {
        int width =
            getFontMetrics(getFont()).stringWidth(maxStringValue) + columnInfo.getAdditionalWidth();
        width = Math.max(width, headerSize.width);
        column.setPreferredWidth(width);
        column.setMaxWidth(width);
      } else if ((preferredValue = columnInfo.getPreferredStringValue()) != null) {
        int width =
            getFontMetrics(getFont()).stringWidth(preferredValue) + columnInfo.getAdditionalWidth();
        width = Math.max(width, headerSize.width);
        column.setPreferredWidth(width);
      }
    }
  }
Пример #20
0
    public void paintIcon(Component c, Graphics g, int x, int y) {
      Color color = c == null ? Color.GRAY : c.getBackground();
      // In a compound sort, make each succesive triangle 20%
      // smaller than the previous one.
      int dx = (int) (size / 2 * Math.pow(0.8, priority));
      int dy = descending ? dx : -dx;
      // Align icon (roughly) with font baseline.
      y = y + 5 * size / 6 + (descending ? -dy : 0);
      int shift = descending ? 1 : -1;
      g.translate(x, y);

      // Right diagonal.
      g.setColor(color.darker());
      g.drawLine(dx / 2, dy, 0, 0);
      g.drawLine(dx / 2, dy + shift, 0, shift);

      // Left diagonal.
      g.setColor(color.brighter());
      g.drawLine(dx / 2, dy, dx, 0);
      g.drawLine(dx / 2, dy + shift, dx, shift);

      // Horizontal line.
      if (descending) {
        g.setColor(color.darker().darker());
      } else {
        g.setColor(color.brighter().brighter());
      }
      g.drawLine(dx, 0, 0, 0);

      g.setColor(color);
      g.translate(-x, -y);
    }
 /**
  * Get the dimension of this ColumnGroup.
  *
  * @param table the table the header is being rendered in
  * @return the dimension of the ColumnGroup
  */
 public Dimension getSize(JTable table) {
   Component comp =
       renderer.getTableCellRendererComponent(table, getHeaderValue(), false, false, -1, -1);
   int height = comp.getPreferredSize().height;
   int width = 0;
   Iterator iter = v.iterator();
   while (iter.hasNext()) {
     Object obj = iter.next();
     if (obj instanceof TableColumn) {
       TableColumn aColumn = (TableColumn) obj;
       width += aColumn.getWidth();
     } else {
       width += ((ColumnGroup) obj).getSize(table).width;
     }
   }
   return new Dimension(width, height);
 }
  private VcsLogHighlighter.VcsCommitStyle getStyle(
      int row, int column, String text, boolean hasFocus, final boolean selected) {
    Component dummyRendererComponent =
        myDummyRenderer.getTableCellRendererComponent(this, text, selected, hasFocus, row, column);

    VisibleGraph<Integer> visibleGraph = getVisibleGraph();
    if (row < 0 || row >= visibleGraph.getVisibleCommitCount()) {
      LOG.error(
          "Visible graph has "
              + visibleGraph.getVisibleCommitCount()
              + " commits, yet we want row "
              + row);
      return VcsCommitStyleFactory.createStyle(
          dummyRendererComponent.getForeground(),
          dummyRendererComponent.getBackground(),
          VcsLogHighlighter.TextStyle.NORMAL);
    }

    final RowInfo<Integer> rowInfo = visibleGraph.getRowInfo(row);

    VcsLogHighlighter.VcsCommitStyle defaultStyle =
        VcsCommitStyleFactory.createStyle(
            rowInfo.getRowType() == RowType.UNMATCHED
                ? JBColor.GRAY
                : dummyRendererComponent.getForeground(),
            dummyRendererComponent.getBackground(),
            VcsLogHighlighter.TextStyle.NORMAL);

    List<VcsLogHighlighter.VcsCommitStyle> styles =
        ContainerUtil.map(
            myHighlighters,
            new Function<VcsLogHighlighter, VcsLogHighlighter.VcsCommitStyle>() {
              @Override
              public VcsLogHighlighter.VcsCommitStyle fun(VcsLogHighlighter highlighter) {
                return highlighter.getStyle(rowInfo.getCommit(), selected);
              }
            });

    return VcsCommitStyleFactory.combine(ContainerUtil.append(styles, defaultStyle));
  }
Пример #23
0
 protected void paintBackground(Graphics g, Rectangle cellRect, int col) {
   Component component = getHeaderRenderer(col);
   int x = cellRect.x;
   int y = cellRect.y;
   int w = cellRect.width;
   int h = cellRect.height;
   if (header.getBackground() instanceof ColorUIResource) {
     if ((col == rolloverCol) && (component != null) && component.isEnabled()) {
       JTattooUtilities.fillHorGradient(
           g, AbstractLookAndFeel.getTheme().getRolloverColors(), x, y, w, h);
     } else if (drawAllwaysActive() || JTattooUtilities.isFrameActive(header)) {
       JTattooUtilities.fillHorGradient(
           g, AbstractLookAndFeel.getTheme().getColHeaderColors(), x, y, w, h);
     } else {
       JTattooUtilities.fillHorGradient(
           g, AbstractLookAndFeel.getTheme().getInActiveColors(), x, y, w, h);
     }
   } else {
     g.setColor(header.getBackground());
     g.fillRect(x, y, w, h);
   }
 }
Пример #24
0
  public void updateColumnSizes() {
    final JTableHeader header = getTableHeader();
    final TableCellRenderer defaultRenderer = header == null ? null : header.getDefaultRenderer();

    ColumnInfo[] columns = getListTableModel().getColumnInfos();
    for (int i = 0; i < columns.length; i++) {
      final ColumnInfo columnInfo = columns[i];
      final TableColumn column = getColumnModel().getColumn(i);

      final Component headerComponent =
          defaultRenderer == null
              ? null
              : defaultRenderer.getTableCellRendererComponent(
                  this, column.getHeaderValue(), false, false, 0, 0);
      final Dimension headerSize =
          headerComponent == null ? new Dimension(0, 0) : headerComponent.getPreferredSize();
      final String maxStringValue;
      final String preferredValue;
      if (columnInfo.getWidth(this) > 0) {
        int width = columnInfo.getWidth(this);
        column.setMaxWidth(width);
        column.setPreferredWidth(width);
        column.setMinWidth(width);
      } else if ((maxStringValue = columnInfo.getMaxStringValue()) != null) {
        int width =
            getFontMetrics(getFont()).stringWidth(maxStringValue) + columnInfo.getAdditionalWidth();
        width = Math.max(width, headerSize.width);
        column.setPreferredWidth(width);
        column.setMaxWidth(width);
      } else if ((preferredValue = columnInfo.getPreferredStringValue()) != null) {
        int width =
            getFontMetrics(getFont()).stringWidth(preferredValue) + columnInfo.getAdditionalWidth();
        width = Math.max(width, headerSize.width);
        column.setPreferredWidth(width);
      }
    }
  }
Пример #25
0
 /**
  * *****************************************************************************************************
  */
 public Component getTableCellRendererComponent(
     JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int col) {
   String columnName = new ConvertImpl().removeHtmlTags(table.getModel().getColumnName(col));
   String sub = "";
   String sub2 = "";
   try {
     sub = columnName.substring(0, 9);
     sub2 = columnName.substring(0, 4);
   } catch (Exception e) {
   }
   Component comp =
       super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, col);
   setHorizontalAlignment(SwingConstants.CENTER);
   if (sub.equals("Time (ms)")
       || columnName.equals("GTS")
       || columnName.equals("LQI")
       || columnName.equals("RSSI")
       || columnName.equals("CRC")
       || columnName.equals("Header Length")
       || columnName.equals("Channel")
       || columnName.equals("Code")
       || columnName.equals("Cheksum")
       || sub.equals("MAC Heade")
       || columnName.equals("Type")) comp.setBackground(new Color(194, 223, 255));
   else if (columnName.equals("DispatchID")
       || columnName.equals("Length")
       || sub.equals("Frame con")
       || sub2.equals("Sequ")
       || sub.equals("Destinati")
       || sub2.equals("Sour")
       || sub.equals("Super fra")
       || columnName.equals("FCS")
       || sub2.equals("Dest")
       || columnName.equals("Dest.PAN")
       || sub2.equals("Src.")) comp.setBackground(new Color(240, 239, 239));
   else if (columnName.equals("Dispatch")
       || columnName.equals("Encoding")
       || sub.equals("Next head")
       || columnName.equals("Hop limit")
       || sub2.equals("6LoW")
       || columnName.equals("Context")
       || sub.equals("Traffic c")) comp.setBackground(new Color(204, 251, 93));
   else if (columnName.equals("Payload") || columnName.equals("Frame"))
     comp.setBackground(new Color(255, 200, 0));
   else comp.setBackground(Color.WHITE);
   return comp;
 }
Пример #26
0
 //        @Override
 //        public Component prepareEditor(TableCellEditor editor, int row, int column) {
 //            Component prepareEditor = super.prepareEditor(editor, row, column);
 //            customiseMinimumDimensions(prepareEditor.getMinimumSize(), row, column);
 //            return prepareEditor;
 //        }
 @Override
 public Component prepareRenderer(TableCellRenderer renderer, int row, int column) {
   Component prepareRenderer = super.prepareRenderer(renderer, row, column);
   customiseMinimumDimensions(prepareRenderer.getMinimumSize(), row, column);
   return prepareRenderer;
 }
  public void updateColumnSizes() {
    final JTableHeader header = getTableHeader();
    final TableCellRenderer defaultRenderer = header == null ? null : header.getDefaultRenderer();

    final RowSorter<? extends TableModel> sorter = getRowSorter();
    final List<? extends RowSorter.SortKey> current = sorter == null ? null : sorter.getSortKeys();
    ColumnInfo[] columns = getListTableModel().getColumnInfos();
    int[] sizeMode = new int[columns.length];
    int[] headers = new int[columns.length];
    int[] widths = new int[columns.length];
    int allColumnWidth = 0;
    int varCount = 0;

    // calculate
    for (int i = 0; i < columns.length; i++) {
      final ColumnInfo columnInfo = columns[i];
      final TableColumn column = getColumnModel().getColumn(i);
      // hack to get sort arrow included into the renderer component
      if (sorter != null && columnInfo.isSortable()) {
        sorter.setSortKeys(
            Collections.singletonList(new RowSorter.SortKey(i, SortOrder.ASCENDING)));
      }

      final Component headerComponent =
          defaultRenderer == null
              ? null
              : defaultRenderer.getTableCellRendererComponent(
                  this, column.getHeaderValue(), false, false, 0, 0);

      if (sorter != null && columnInfo.isSortable()) {
        sorter.setSortKeys(current);
      }
      if (headerComponent != null) {
        headers[i] = headerComponent.getPreferredSize().width;
      }
      final String maxStringValue;
      final String preferredValue;
      if (columnInfo.getWidth(this) > 0) {
        sizeMode[i] = 1;
        int width = columnInfo.getWidth(this);
        widths[i] = width;
      } else if ((maxStringValue = columnInfo.getMaxStringValue()) != null) {
        sizeMode[i] = 2;
        widths[i] =
            getFontMetrics(getFont()).stringWidth(maxStringValue) + columnInfo.getAdditionalWidth();
        varCount++;
      } else if ((preferredValue = columnInfo.getPreferredStringValue()) != null) {
        sizeMode[i] = 3;
        widths[i] =
            getFontMetrics(getFont()).stringWidth(preferredValue) + columnInfo.getAdditionalWidth();
        varCount++;
      }
      allColumnWidth += widths[i];
    }

    // apply: distribute available space between resizable columns
    //        and make sure that header will fit as well
    int viewWidth = getParent() != null ? getParent().getWidth() : getWidth();
    double gold = 0.5 * (3 - Math.sqrt(5));
    int addendum =
        varCount == 0 || viewWidth < allColumnWidth
            ? 0
            : (int)
                    ((allColumnWidth < gold * viewWidth
                            ? gold * viewWidth
                            : allColumnWidth < (1 - gold) * viewWidth
                                ? (1 - gold) * viewWidth
                                : viewWidth)
                        - allColumnWidth)
                / varCount;

    for (int i = 0; i < columns.length; i++) {
      TableColumn column = getColumnModel().getColumn(i);
      int width = widths[i];
      if (sizeMode[i] == 1) {
        column.setMaxWidth(width);
        column.setPreferredWidth(width);
        column.setMinWidth(width);
      } else if (sizeMode[i] == 2) {
        width = Math.max(width + addendum, headers[i]);
        column.setPreferredWidth(width);
        column.setMaxWidth(width);
      } else if (sizeMode[i] == 3) {
        width = Math.max(width + addendum, headers[i]);
        column.setPreferredWidth(width);
      }
    }
  }
Пример #28
0
  /**
   * Renders a table cell in the main JTable. As a TableCellRenderer, we have to implement this
   * method, but we use it to colour different types of matches in different ways. Remember that
   * this is run every time a cell is displayed on the screen, so it needs to be as fast as can be.
   *
   * @param table The table which needs rendering.
   * @param value The object which needs rendering. For now, this can only be a Name object, but
   *     later on we might colour different types of cells in different ways.
   * @param isSelected Is this cell selected, i.e. is the row selected?
   * @param hasFocus Is this cell focused, i.e. is this individual cell selected?
   * @param row The row coordinate of this cell.
   * @param column The column coordinate of this cell.
   * @return A component representing this cell.
   */
  @Override
  public Component getTableCellRendererComponent(
      JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
    // TODO: Check if we can get a saving out of this by just rendering a JLabel/JTextField
    // directly.
    Component c =
        defTableCellRenderer.getTableCellRendererComponent(
            table, value, isSelected, hasFocus, row, column);

    // Set all backgrounds to white.
    c.setBackground(Color.WHITE);

    if (value == null) {
      // Null values look null-ish.
      c.setBackground(COLOR_NULL);
      return c;

    } else if (hasFocus) {
      // ANY cell with focus should look focussed.
      c.setBackground(COLOR_FOCUS);
      return c;

    } else if (Name.class.isAssignableFrom(value.getClass())) {
      // Aha, a Name! Color it special.
      Name name = (Name) value;
      int str_length = name.toString().length();

      if (currentMatch == null) {
        // No current match? Then just colour blank cells blank,
        // and unmatched name colours special so people know that
        // they have been recognized as names.

        if (str_length == 0) {
          c.setBackground(COLOR_BLANK_CELL);
        } else {
          c.setBackground(COLOR_NAME_UNMATCHED);
        }
      } else {
        // So which RowIndex is the match against?
        RowIndex against = currentMatch.getAgainst();

        // System.err.println("Checking against: " + against);

        if (str_length == 0) {
          // Mark blank cells as such.
          c.setBackground(COLOR_BLANK_CELL);
        } else if (against.hasName(name)) {
          // Perfect match!
          c.setBackground(COLOR_NAME_FULL_MATCH);
        } else if (against.hasName(name.getGenus())) {
          // Genus-match.
          c.setBackground(COLOR_NAME_GENUS_MATCH);
        } else {
          // No match!
          c.setBackground(COLOR_NAME_NO_MATCH);
        }
      }

    } else {
      // Not a name? Note that Strings will NOT make it here: we don't
      // push Strings through this. So this is really just for later.
      c.setBackground(COLOR_NULL);
    }

    // If the row is selected, make it darker.
    if (isSelected) c.setBackground(c.getBackground().darker());

    return c;
  }