Ejemplo n.º 1
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;
  }
Ejemplo n.º 2
0
  private void fnHideColumn() {
    TableColumnModel tcm = this.tablePanel.getColumnModel();
    Object[] selected = this.cbList.getCheckBoxListSelectedValues();
    for (int i = 0; i < tcm.getColumnCount(); i++) {
      TableColumn tc = tcm.getColumn(i);
      String value = tc.getHeaderValue().toString();
      boolean matched = false;
      for (int j = 0; j < selected.length; j++) {
        if (value.equalsIgnoreCase(selected[j].toString())) {
          matched = true;
          break;
        }
      }
      if (!matched) {
        tc.setMinWidth(0);
        tc.setMaxWidth(0);
      } else {
        int width = this.model.getColumnWidth(value);
        tc.setMinWidth(width);

        tc.setWidth(width);
        tc.setPreferredWidth(width);
      }
    }
  }
Ejemplo n.º 3
0
  public void 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);
  }
Ejemplo n.º 4
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 Component getTableCellRendererComponent(
      JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
    setOpaque(true);
    setFont(plainFont);
    // setBorder(new EmptyBorder(10, 10, 10, 6));

    if (isSelected) {
      setForeground(table.getSelectionForeground());
      setBackground(table.getSelectionBackground());
    } else {
      setForeground(table.getForeground());
      setBackground(table.getBackground());
    }

    if (table.getModel() instanceof FeedTableModel) {
      FeedTableModel rsstm = (FeedTableModel) table.getModel();
      TableColumn col = table.getColumnModel().getColumn(column);
      if (!rsstm.isItemAtRowRead(row)) setFont(boldFont);
      if (col.getHeaderValue() == FeedTableModel.READ) {
        if (rsstm.isItemAtRowRead(row)) setIcon(readItemIcon);
        else setIcon(unreadItemIcon);
      } else setIcon(null);

    } else if (table.getModel() instanceof WeblogTableModel) {
      WeblogTableModel btm = (WeblogTableModel) table.getModel();
      if (column == 0) {
        // is the modified column on the TableModel null?
        if (btm.getValueAt(row, WeblogTableModel.MODIFIED_COL) == null) setIcon(postIcon);
        else setIcon(uPostIcon);
      } else setIcon(null);
    }

    if (value instanceof FeedItem) {
      setText(((FeedItem) value).getTitle());
      return this;
    } else if (value instanceof Boolean) {
      setText("");
      setHorizontalAlignment(SwingConstants.CENTER);
      return this;
    } else if (value instanceof Integer) {
      Integer val = (Integer) value;
      setHorizontalAlignment(SwingConstants.CENTER);
      setText(val.intValue() + "");
      return this;
    } else if (value instanceof Date) {
      Date d = (Date) value;
      setText(df.format(d));
      if ((table.getModel() instanceof WeblogTableModel) && (column == WeblogTableModel.DATE_COL)) {
        if (expireDate != null && d.before(expireDate)) setForeground(Color.red);
      }

      return this;
    }

    setHorizontalAlignment(SwingConstants.LEFT);
    // setToolTipText(value.toString());
    if (value == null) setText("");
    else setText(value.toString());
    return this;
  }
Ejemplo n.º 6
0
  private void packColumn(JTable table, int vColIndex, int margin) {
    //		table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
    DefaultTableColumnModel colModel = (DefaultTableColumnModel) table.getColumnModel();
    TableColumn col = colModel.getColumn(vColIndex);
    int width = 0;

    // obtiene la anchura de la cabecera de la columna
    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;
    width = 5;

    // Obtine la anchura maxima de la coluna de
    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, 0);
    }

    width += 2 * margin;

    // Configura el ancho
    col.setPreferredWidth(width);
  }
Ejemplo n.º 7
0
  /**
   * Calculates the optimal width for the header of the given table. The calculation is based on the
   * preferred width of the header renderer.
   *
   * @param table the table to calculate the column width
   * @param col the column to calculate the widths
   * @return the width, -1 if error
   */
  public static int calcHeaderWidth(JTable table, int col) {
    if (table == null) return -1;

    if (col < 0 || col > table.getColumnCount()) {
      System.out.println("invalid col " + col);
      return -1;
    }

    JTableHeader header = table.getTableHeader();
    TableCellRenderer defaultHeaderRenderer = null;
    if (header != null) defaultHeaderRenderer = header.getDefaultRenderer();
    TableColumnModel columns = table.getColumnModel();
    TableModel data = table.getModel();
    TableColumn column = columns.getColumn(col);
    int width = -1;
    TableCellRenderer h = column.getHeaderRenderer();
    if (h == null) h = defaultHeaderRenderer;
    if (h != null) {
      // Not explicitly impossible
      Component c =
          h.getTableCellRendererComponent(table, column.getHeaderValue(), false, false, -1, col);
      width = c.getPreferredSize().width + 5;
    }

    return width;
  }
      private Component getHeaderRenderer(int columnIndex) {
        TableColumn aColumn = header.getColumnModel().getColumn(columnIndex);
        TableCellRenderer renderer = aColumn.getHeaderRenderer();

        if (renderer == null) {
          renderer = header.getDefaultRenderer();
        }

        if (headerSelected == columnIndex) {
          headerSelected = -1;
          return renderer.getTableCellRendererComponent(
              header.getTable(), aColumn.getHeaderValue(), true, false, -1, columnIndex);
        } else {
          return renderer.getTableCellRendererComponent(
              header.getTable(), aColumn.getHeaderValue(), false, false, -1, columnIndex);
        }
      }
 private int getColumnHeaderWidth(JTable table, int colIndex) {
   TableColumn col = table.getColumnModel().getColumn(colIndex);
   TableCellRenderer renderer = col.getHeaderRenderer();
   if (renderer == null) renderer = table.getTableHeader().getDefaultRenderer();
   Component comp =
       renderer.getTableCellRendererComponent(table, col.getHeaderValue(), false, false, 0, 0);
   return comp.getPreferredSize().width;
 }
Ejemplo n.º 10
0
 private JLabel renderHeaderCell(int rowIndex, int columnIndex) {
   TableCellRenderer renderer = table.getTableHeader().getDefaultRenderer();
   int modelIndex = table.convertColumnIndexToModel(columnIndex);
   TableColumn tableColumn = table.getColumnModel().getColumn(modelIndex);
   Object cellValue = tableColumn.getHeaderValue();
   return (JLabel)
       renderer.getTableCellRendererComponent(
           table, cellValue, false, false, rowIndex, columnIndex);
 }
Ejemplo n.º 11
0
 protected Component getHeaderRenderer(int col) {
   if ((header == null) || (header.getTable() == null)) {
     return null;
   }
   TableColumn tabCol = header.getColumnModel().getColumn(col);
   TableCellRenderer renderer = tabCol.getHeaderRenderer();
   if (renderer == null) {
     renderer = header.getDefaultRenderer();
   }
   return renderer.getTableCellRendererComponent(
       header.getTable(), tabCol.getHeaderValue(), false, false, -1, col);
 }
Ejemplo n.º 12
0
  @Override
  public JComponent createContentPanel() {
    JPanel panel = new JPanel(new BorderLayout(10, 10));
    panel.setBorder(BorderFactory.createEmptyBorder(10, 10, 0, 10));

    JLabel label = new JLabel("Please select the column you want to shown.");

    label.setHorizontalAlignment(SwingConstants.LEFT);

    DefaultListModel listModel = new DefaultListModel();

    ArrayList<String> selected = new ArrayList();
    TableColumnModel tcm = this.tablePanel.getColumnModel();
    for (int i = 0; i < tcm.getColumnCount(); i++) {
      TableColumn tc = tcm.getColumn(i);
      listModel.addElement(tc.getHeaderValue());
      if (tc.getWidth() > 0) {
        selected.add(tc.getHeaderValue().toString());
      }
    }
    this.cbList = new CheckBoxList(listModel);
    this.cbList.setLayoutOrientation(JList.VERTICAL_WRAP);
    this.cbList.setSelectedObjects(selected.toArray());
    this.cbList.setClickInCheckBoxOnly(false);
    this.cbList.getCheckBoxListSelectionModel().setSelectionMode(2);

    JPanel topPanel = new JPanel(new BorderLayout(6, 6));
    topPanel.add(label, "North");
    topPanel.add(this.cbList, "Center");
    panel.add(topPanel, "First");

    this.labDesc = new JideLabel("");
    this.labDesc.setIcon(IconFactory.getImageIcon("exclamation.png"));
    this.labDesc.setVisible(false);
    panel.add(this.labDesc, "South");

    return panel;
  }
Ejemplo n.º 13
0
  private String getColumnNameOf(MouseEvent e) {
    // Warning: Apply coordinates to VIEW model !
    TableColumnModel columnModel = table.getColumnModel();

    int colnr = columnModel.getColumnIndexAtX(e.getX());

    if (colnr < 0) {
      return null;
    }

    TableColumn column = columnModel.getColumn(colnr);
    String name = (String) column.getHeaderValue();
    return name;
  }
  /*
   *  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;
  }
Ejemplo n.º 15
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);
      }
    }
  }
Ejemplo n.º 16
0
 /**
  * Method getColumn
  *
  * @param columnIndex
  * @return
  */
 public TableColumn getColumn(int columnIndex) {
   TableColumn tableColumn;
   try {
     tableColumn = super.getColumn(columnIndex);
   } catch (Exception ex) { // return an empty column if the columnIndex is not valid.
     return new TableColumn();
   }
   String headerValue = (String) tableColumn.getHeaderValue();
   if (headerValue == null) {
     return tableColumn;
   } else if (headerValue.equals("row")) { // $NON-NLS-1$
     tableColumn.setMaxWidth(labelColumnWidth);
     tableColumn.setMinWidth(labelColumnWidth);
     tableColumn.setResizable(true);
   }
   return tableColumn;
 }
Ejemplo n.º 17
0
  public void autoResizeColWidth() {

    int margin = 5;

    for (int i = 0; i < tabel.getColumnCount(); i++) {
      int vColIndex = i;
      DefaultTableColumnModel colModel = (DefaultTableColumnModel) tabel.getColumnModel();
      TableColumn col = colModel.getColumn(vColIndex);
      int width = 0;

      // Get width of column header
      TableCellRenderer renderer = col.getHeaderRenderer();

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

      Component comp =
          renderer.getTableCellRendererComponent(tabel, col.getHeaderValue(), false, false, 0, 0);

      width = comp.getPreferredSize().width;

      // Get maximum width of column data
      for (int r = 0; r < tabel.getRowCount(); r++) {
        renderer = tabel.getCellRenderer(r, vColIndex);
        comp =
            renderer.getTableCellRendererComponent(
                tabel, tabel.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);
    }

    ((DefaultTableCellRenderer) tabel.getTableHeader().getDefaultRenderer())
        .setHorizontalAlignment(SwingConstants.LEFT);

    // table.setAutoCreateRowSorter(true);
    tabel.getTableHeader().setReorderingAllowed(false);
  }
Ejemplo n.º 18
0
  public static void main(String args[]) {

    final Object rowData[][] = {
      {"1", "one", "I"},
      {"2", "two", "II"},
      {"3", "three", "III"}
    };
    final String columnNames[] = {"#", "English", "Roman"};

    final JTable table = new JTable(rowData, columnNames);
    JScrollPane scrollPane = new JScrollPane(table);

    JFrame frame = new JFrame("Resizing Table");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    frame.add(scrollPane, BorderLayout.CENTER);

    TableColumn tc = null;
    for (int i = 0; i < 3; i++) {

      tc = table.getColumnModel().getColumn(i);

      if (tc.getModelIndex() == 0) tc.setResizable(false);
      if (i == 2) {
        tc.setPreferredWidth(100); // sport column is bigger
      } else {
        tc.setPreferredWidth(50);
      }
      System.out.printf(
          "column [%s] header=[%s] modelIndex=[%d] resizable=[%b] minWidth=[%s] maxWidth=[%d] preferredWidth=[%d]\n",
          tc.getIdentifier(),
          tc.getHeaderValue(),
          tc.getModelIndex(),
          tc.getResizable(),
          tc.getMinWidth(),
          tc.getMaxWidth(),
          tc.getPreferredWidth());
    }

    frame.setSize(300, 150);
    frame.setVisible(true);
  }
Ejemplo n.º 19
0
  protected void setResultsData() {
    getTable().setModel(getTableModel());
    int maxScoreColWidth = 0;

    for (int x = 0; x < getTableModel().getColumnCount(); x++) {
      if (x != 1) {
        getTable()
            .getColumnModel()
            .getColumn(x)
            .setCellRenderer(new ResultsTableCellRenderer(false));
      }
      TableColumn column = getTable().getColumnModel().getColumn(x);
      Component comp;

      column.setHeaderRenderer(new ResultsTableCellRenderer(true));
      comp =
          column
              .getHeaderRenderer()
              .getTableCellRendererComponent(null, column.getHeaderValue(), false, false, 0, 0);
      int width = comp.getPreferredSize().width;

      for (int y = 0; y < getTableModel().getRowCount(); y++) {
        comp =
            getTable()
                .getDefaultRenderer(getTableModel().getColumnClass(x))
                .getTableCellRendererComponent(
                    getTable(), getTableModel().getValueAt(y, x), false, false, 0, x);
        if (comp.getPreferredSize().width > width) {
          width = comp.getPreferredSize().width;
        }
      }
      TableColumn col = getTable().getColumnModel().getColumn(x);

      col.setPreferredWidth(width);
      col.setMinWidth(width);
      col.setWidth(width);

      if (x >= 3 && width > maxScoreColWidth) {
        maxScoreColWidth = width;
      }
    }
  }
 public void packColumn(JTable table, int vColIndex, int margin) {
   TableModel model = table.getModel();
   DefaultTableColumnModel colModel = (DefaultTableColumnModel) table.getColumnModel();
   TableColumn col = colModel.getColumn(vColIndex);
   int width = 0; // Obtém a largura do cabeçalho da coluna
   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; // Obtém a largura maxima da coluna de dados
   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);
   }
   width += 2 * margin; // Configura a largura
   col.setPreferredWidth(width);
 }
Ejemplo n.º 21
0
    public void columnAdded(TableColumnModelEvent e) {
      // Gets index of columns added.
      int fromIndex = e.getFromIndex();
      int toIndex = e.getToIndex();

      for (int i = fromIndex; i <= toIndex; i++) {
        TableColumn col = table.getColumnModel().getColumn(i);
        // Sets the default renderer.
        col.setCellRenderer(tableCellRenderer);

        // Calculs & sets the preferred width.
        int colPreferredWidth =
            table
                    .getTableHeader()
                    .getFontMetrics(table.getTableHeader().getFont())
                    .stringWidth(col.getHeaderValue().toString())
                + 10;
        col.setPreferredWidth(colPreferredWidth);
      }

      adjustPreferredSize();
    }
Ejemplo n.º 22
0
  private void initColumnSizes() {
    this.rowHeight = 20;
    UpdatesModel model = (UpdatesModel) this.getModel();
    TableColumn column = null;
    Component comp = null;
    // Object[] longValues = model.longValues;
    TableCellRenderer headerRenderer = this.getTableHeader().getDefaultRenderer();

    for (int i = 0; i < model.getColumnCount(); i++) {
      int headerWidth = 0;
      int cellWidth = 0;
      column = this.getColumnModel().getColumn(i);

      comp =
          headerRenderer.getTableCellRendererComponent(
              null, column.getHeaderValue(), false, false, 0, 0);
      headerWidth = comp.getPreferredSize().width;

      for (int r = 0; r < model.getRowCount(); r++) {
        comp =
            this.getDefaultRenderer(model.getColumnClass(i))
                .getTableCellRendererComponent(this, getValueAt(r, i), false, false, 0, i);
        cellWidth = Math.max(comp.getPreferredSize().width, cellWidth);
      }
      if (DEBUG) {
        System.out.println(
            "Initializing width of column "
                + i
                + ". "
                + "headerWidth = "
                + headerWidth
                + "; cellWidth = "
                + cellWidth);
      }

      column.setPreferredWidth(Math.max(headerWidth, cellWidth));
    }
  }
Ejemplo n.º 23
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);
      }
    }
  }
 public int calcColumnWidths(JTableIbp table) {
   int panelsWidth = 0;
   JTableHeader header = table.getTableHeader();
   TableCellRenderer defaultHeaderRenderer = null;
   if (header != null) defaultHeaderRenderer = header.getDefaultRenderer();
   TableColumnModel columns = table.getColumnModel();
   // tableModel = table.getModel();
   int margin = columns.getColumnMargin(); // only JDK1.3
   int rowCount = table.getModel().getRowCount();
   for (int i = columns.getColumnCount() - 1; i >= 0; --i) {
     TableColumn column = columns.getColumn(i);
     int columnIndex = column.getModelIndex();
     int width = -1;
     TableCellRenderer h = column.getHeaderRenderer();
     if (h == null) h = defaultHeaderRenderer;
     if (h != null) // Not explicitly impossible
     {
       Component c =
           h.getTableCellRendererComponent(table, column.getHeaderValue(), false, false, -1, i);
       width = c.getPreferredSize().width;
     }
     for (int row = rowCount - 1; row >= 0; --row) {
       TableCellRenderer r = table.getCellRenderer(row, i);
       Component c =
           r.getTableCellRendererComponent(
               table, table.getModel().getValueAt(row, columnIndex), false, false, row, i);
       width = Math.max(width, c.getPreferredSize().width);
     }
     if (width >= 0) column.setPreferredWidth(width + margin); // <1.3: without
     // margin
     else ; // ???
     panelsWidth += column.getPreferredWidth();
   }
   panelsWidth = panelsWidth > (screenWidth - 30) ? screenWidth : panelsWidth;
   frameWidth = panelsWidth > (frameWidth - 30) ? (panelsWidth - 30) : frameWidth;
   return panelsWidth;
 }
  /*
   * This method picks good column sizes.
   * If all column heads are wider than the column's cells'
   * contents, then you can just use column.sizeWidthToFit().
   */
  private void initColumnSizes(JTable table) {
    MyTableModel model = (MyTableModel) table.getModel();
    TableColumn column = null;
    Component comp = null;
    int headerWidth = 0;
    int cellWidth = 0;
    Object[] longValues = model.longValues;
    TableCellRenderer headerRenderer = table.getTableHeader().getDefaultRenderer();

    for (int i = 0; i < 5; i++) {
      column = table.getColumnModel().getColumn(i);

      comp =
          headerRenderer.getTableCellRendererComponent(
              null, column.getHeaderValue(), false, false, 0, 0);
      headerWidth = comp.getPreferredSize().width;

      comp =
          table
              .getDefaultRenderer(model.getColumnClass(i))
              .getTableCellRendererComponent(table, longValues[i], false, false, 0, i);
      cellWidth = comp.getPreferredSize().width;

      if (DEBUG) {
        System.out.println(
            "Initializing width of column "
                + i
                + ". "
                + "headerWidth = "
                + headerWidth
                + "; cellWidth = "
                + cellWidth);
      }

      column.setPreferredWidth(Math.max(headerWidth, cellWidth));
    }
  }
Ejemplo n.º 26
0
 @Override
 public String getColumnName(int col) {
   switch (col) {
     case IDCOL:
       return Bundle.getMessage("FieldID");
     case ADDRESSCOL:
       return Bundle.getMessage("FieldDCCAddress");
     case DECODERCOL:
       return Bundle.getMessage("FieldDecoderModel");
     case MODELCOL:
       return Bundle.getMessage("FieldModel");
     case ROADNAMECOL:
       return Bundle.getMessage("FieldRoadName");
     case ROADNUMBERCOL:
       return Bundle.getMessage("FieldRoadNumber");
     case MFGCOL:
       return Bundle.getMessage("FieldManufacturer");
     case ICONCOL:
       return Bundle.getMessage("FieldIcon");
     case OWNERCOL:
       return Bundle.getMessage("FieldOwner");
     case DATEUPDATECOL:
       return Bundle.getMessage("FieldDateUpdated");
     case PROTOCOL:
       return Bundle.getMessage("FieldProtocol");
     default:
       break;
   }
   if (_tcm != null) {
     TableColumn tc = _tcm.getColumnByModelIndex(col);
     if (tc != null) {
       return (String) tc.getHeaderValue();
     }
   }
   return "<UNKNOWN>"; // NOI18N
 }
Ejemplo n.º 27
0
    private void resizeColumns() {
      int columnCount = getColumnCount();
      int rowCount = getRowCount();
      TableColumnModel columnModel = getColumnModel();
      for (int columnIndex = 0; columnIndex < columnCount; columnIndex++) {
        TableColumn column = columnModel.getColumn(columnIndex);
        int preferredWidth = column.getMinWidth();
        int maxWidth = column.getMaxWidth();

        // Header value with
        TableCellRenderer cellRenderer = column.getHeaderRenderer();
        if (cellRenderer == null) {
          cellRenderer = getTableHeader().getDefaultRenderer();
        }
        Object headerValue = column.getHeaderValue();
        Component comp =
            cellRenderer.getTableCellRendererComponent(
                this, headerValue, false, false, 0, columnIndex);
        int width = comp.getPreferredSize().width + getIntercellSpacing().width + 15;
        preferredWidth = Math.max(preferredWidth, width);

        // Row values' width
        for (int rowIndex = 0; rowIndex < rowCount; rowIndex++) {
          cellRenderer = getCellRenderer(rowIndex, columnIndex);
          comp = prepareRenderer(cellRenderer, rowIndex, columnIndex);
          width = comp.getPreferredSize().width + getIntercellSpacing().width + 15;
          preferredWidth = Math.max(preferredWidth, width);
          if (preferredWidth >= maxWidth) {
            preferredWidth = maxWidth;
            break;
          }
        }

        column.setPreferredWidth(preferredWidth);
      }
    }
Ejemplo n.º 28
0
package com.l2fprod.common.swing.table;
Ejemplo n.º 29
0
  public RosterTable(boolean editable, int selectionMode) {
    super();
    dataModel = new RosterTableModel(editable);
    sorter = new TableSorter(dataModel);
    dataTable = new JTable(sorter);
    sorter.setTableHeader(dataTable.getTableHeader());
    dataScroll = new JScrollPane(dataTable);

    // set initial sort
    TableSorter tmodel = ((TableSorter) dataTable.getModel());
    tmodel.setSortingStatus(RosterTableModel.ADDRESSCOL, TableSorter.ASCENDING);

    // Use a "Numeric, if not, Alphanumeric" comparator
    tmodel.setColumnComparator(String.class, new jmri.util.PreferNumericComparator());

    // allow reordering of the columns
    dataTable.getTableHeader().setReorderingAllowed(true);

    // have to shut off autoResizeMode to get horizontal scroll to work (JavaSwing p 541)
    dataTable.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);

    dataTable.setColumnModel(columnModel);
    dataModel.setColumnModel(columnModel);
    dataTable.createDefaultColumnsFromModel();
    dataTable.setAutoCreateColumnsFromModel(false);

    TableColumn tc = columnModel.getColumnByModelIndex(RosterTableModel.PROTOCOL);
    columnModel.setColumnVisible(tc, false);

    for (String s : Roster.instance().getAllAttributeKeys()) {
      if (!s.contains("RosterGroup")
          && !s.toLowerCase().startsWith("sys")
          && !s.toUpperCase().startsWith("VSD")) { // NOI18N
        String[] r = s.split("(?=\\p{Lu})"); // NOI18N
        StringBuilder sb = new StringBuilder();
        sb.append(r[0].trim());
        // System.out.println("'"+r[0]+",");
        for (int j = 1; j < r.length; j++) {
          // System.out.println("'"+r[j]+",");
          sb.append(" ");
          sb.append(r[j].trim());
        }
        TableColumn c = new TableColumn(dataModel.getColumnCount());
        c.setHeaderValue((sb.toString()).trim());
        dataTable.addColumn(c);
        dataModel.addColumn(c.getHeaderValue());
        columnModel.setColumnVisible(c, false);
      }
    }

    // resize columns as requested
    resetColumnWidths();

    // general GUI config
    setLayout(new BoxLayout(this, BoxLayout.Y_AXIS));

    // install items in GUI
    add(dataScroll);

    // set Viewport preferred size from size of table
    java.awt.Dimension dataTableSize = dataTable.getPreferredSize();
    // width is right, but if table is empty, it's not high
    // enough to reserve much space.
    dataTableSize.height = Math.max(dataTableSize.height, 400);
    dataTableSize.width = Math.max(dataTableSize.width, 400);
    dataScroll.getViewport().setPreferredSize(dataTableSize);

    dataTable.setSelectionMode(selectionMode);
    MouseListener mouseHeaderListener = new tableHeaderListener();
    dataTable.getTableHeader().addMouseListener(mouseHeaderListener);

    dataTable.setDefaultEditor(Object.class, new RosterCellEditor());

    dataTable
        .getSelectionModel()
        .addListSelectionListener(
            tableSelectionListener =
                new ListSelectionListener() {
                  @Override
                  public void valueChanged(ListSelectionEvent e) {
                    if (!e.getValueIsAdjusting()) {
                      selectedRosterEntries = null; // clear cached list of selections
                      if (dataTable.getSelectedRowCount() == 1) {
                        re =
                            Roster.instance()
                                .getEntryForId(
                                    sorter
                                        .getValueAt(
                                            dataTable.getSelectedRow(), RosterTableModel.IDCOL)
                                        .toString());
                      } else if (dataTable.getSelectedRowCount() > 1) {
                        re = null;
                      } // leave last selected item visible if no selection
                    } else if (e.getFirstIndex() == -1) {
                      // A reorder of the table might of occured therefore we are going to make sure
                      // that the selected item is still in view
                      moveTableViewToSelected();
                    }
                  }
                });
  }
  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);
      }
    }
  }