Java Code Examples for javax.swing.table.TableColumnModel

The following examples show how to use javax.swing.table.TableColumnModel. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source Project: MooTool   Source File: HttpRequestForm.java    License: MIT License 6 votes vote down vote up
/**
 * 初始化HeaderTable
 */
public static void initHeaderTable() {
    JTable paramTable = getInstance().getHeaderTable();
    paramTable.setRowHeight(36);
    String[] headerNames = {"Name", "Value", ""};
    DefaultTableModel model = new DefaultTableModel(null, headerNames);
    paramTable.setModel(model);
    paramTable.updateUI();
    DefaultTableCellRenderer hr = (DefaultTableCellRenderer) paramTable.getTableHeader().getDefaultRenderer();
    // 表头列名居左
    hr.setHorizontalAlignment(DefaultTableCellRenderer.LEFT);

    TableColumnModel tableColumnModel = paramTable.getColumnModel();
    tableColumnModel.getColumn(headerNames.length - 1).
            setCellRenderer(new TableInCellButtonColumn(paramTable, headerNames.length - 1));
    tableColumnModel.getColumn(headerNames.length - 1).
            setCellEditor(new TableInCellButtonColumn(paramTable, headerNames.length - 1));

    // 设置列宽
    tableColumnModel.getColumn(headerNames.length - 1).setPreferredWidth(46);
    tableColumnModel.getColumn(headerNames.length - 1).setMaxWidth(46);
}
 
Example 2
Source Project: MooTool   Source File: HttpRequestForm.java    License: MIT License 6 votes vote down vote up
/**
 * 初始化CookieTable
 */
public static void initCookieTable() {
    JTable paramTable = getInstance().getCookieTable();
    paramTable.setRowHeight(36);
    String[] headerNames = {"Name", "Value", "Domain", "Path", "Expiry", ""};
    DefaultTableModel model = new DefaultTableModel(null, headerNames);
    paramTable.setModel(model);
    paramTable.updateUI();
    DefaultTableCellRenderer hr = (DefaultTableCellRenderer) paramTable.getTableHeader().getDefaultRenderer();
    // 表头列名居左
    hr.setHorizontalAlignment(DefaultTableCellRenderer.LEFT);

    TableColumnModel tableColumnModel = paramTable.getColumnModel();
    tableColumnModel.getColumn(headerNames.length - 1).
            setCellRenderer(new TableInCellButtonColumn(paramTable, headerNames.length - 1));
    tableColumnModel.getColumn(headerNames.length - 1).
            setCellEditor(new TableInCellButtonColumn(paramTable, headerNames.length - 1));

    // 设置列宽
    tableColumnModel.getColumn(headerNames.length - 1).setPreferredWidth(46);
    tableColumnModel.getColumn(headerNames.length - 1).setMaxWidth(46);
}
 
Example 3
Source Project: WePush   Source File: MpTemplateMsgForm.java    License: MIT License 6 votes vote down vote up
/**
 * 填充模板参数表Table(从数据库读取)
 *
 * @param msgId
 */
public static void fillTemplateDataTable(Integer msgId) {
    // 模板消息Data表
    List<TTemplateData> templateDataList = templateDataMapper.selectByMsgTypeAndMsgId(MessageTypeEnum.MP_TEMPLATE_CODE, msgId);
    String[] headerNames = {"Name", "Value", "Color", "操作"};
    Object[][] cellData = new String[templateDataList.size()][headerNames.length];
    for (int i = 0; i < templateDataList.size(); i++) {
        TTemplateData tTemplateData = templateDataList.get(i);
        cellData[i][0] = tTemplateData.getName();
        cellData[i][1] = tTemplateData.getValue();
        cellData[i][2] = tTemplateData.getColor();
    }
    DefaultTableModel model = new DefaultTableModel(cellData, headerNames);
    getInstance().getTemplateMsgDataTable().setModel(model);
    TableColumnModel tableColumnModel = getInstance().getTemplateMsgDataTable().getColumnModel();
    tableColumnModel.getColumn(headerNames.length - 1).
            setCellRenderer(new TableInCellButtonColumn(getInstance().getTemplateMsgDataTable(), headerNames.length - 1));
    tableColumnModel.getColumn(headerNames.length - 1).
            setCellEditor(new TableInCellButtonColumn(getInstance().getTemplateMsgDataTable(), headerNames.length - 1));

    // 设置列宽
    tableColumnModel.getColumn(3).setPreferredWidth(getInstance().getTemplateMsgDataAddButton().getWidth());
    tableColumnModel.getColumn(3).setMaxWidth(getInstance().getTemplateMsgDataAddButton().getWidth());
}
 
Example 4
Source Project: visualvm   Source File: SampledResultsPanel.java    License: GNU General Public License v2.0 6 votes vote down vote up
private void setColumnsData() {
    barRenderer = getBarCellRenderer();

    TableColumnModel colModel = resTable.getColumnModel();
    colModel.getColumn(0).setPreferredWidth(minNamesColumnWidth);

    int index;

    for (int i = 0; i < colModel.getColumnCount(); i++) {
        index = resTableModel.getRealColumn(i);

        if (index == 0) {
            colModel.getColumn(i).setPreferredWidth(minNamesColumnWidth);
        } else {
            colModel.getColumn(i).setPreferredWidth(columnWidths[index - 1]);
        }

        if (index == 1) {
            colModel.getColumn(i).setCellRenderer(barRenderer);
        } else {
            colModel.getColumn(i).setCellRenderer(columnRenderers[index]);
        }
    }
}
 
Example 5
public void mouseClicked(MouseEvent evt) {
    // XXX Benchmark sort performance
    //long start = System.currentTimeMillis();
    CommonUI.setWaitCursor(SwingUtilities.getRoot(table));

    TableColumnModel columnModel = table.getColumnModel();
    int viewColumn = columnModel.getColumnIndexAtX(evt.getX());
    int column = table.convertColumnIndexToModel(viewColumn);
    if (evt.getClickCount() == 1 && column != -1) {
        // Reverse the sorting direction.
        model.sortByColumn(column, !model.isAscending());
    }

    // XXX Benchmark performance
    //      System.out.println("Sort time: " +
    //         (System.currentTimeMillis() - start));
    CommonUI.setDefaultCursor(SwingUtilities.getRoot(table));
}
 
Example 6
Source Project: java-swing-tips   Source File: MainPanel.java    License: MIT License 6 votes vote down vote up
private MainPanel() {
  super(new BorderLayout());

  JTable table = new JTable(new DefaultTableModel(8, 6)) {
    @Override protected TableColumnModel createDefaultColumnModel() {
      return new SortableTableColumnModel();
    }
  };
  table.setAutoCreateRowSorter(true);

  JButton b = new JButton("restore TableColumn order");
  b.addActionListener(e -> {
    TableColumnModel m = table.getColumnModel();
    // TEST: sortTableColumn(m);
    if (m instanceof SortableTableColumnModel) {
      ((SortableTableColumnModel) m).restoreColumnOrder();
    }
  });
  add(new JScrollPane(table));
  add(b, BorderLayout.SOUTH);
  setPreferredSize(new Dimension(320, 240));
}
 
Example 7
Source Project: darklaf   Source File: DarkTableHeaderUI.java    License: MIT License 6 votes vote down vote up
public void paintSingleCell(final Graphics2D g, final int h, final TableColumnModel cm,
                            final int cMax, final Color borderColor,
                            final TableColumn draggedColumn,
                            final Rectangle cellRect, final int column) {
    TableColumn aColumn;
    int columnWidth;
    aColumn = cm.getColumn(column);
    columnWidth = aColumn.getWidth();
    cellRect.width = columnWidth;
    if (aColumn != draggedColumn) {
        paintCell(g, cellRect, column);
    }
    cellRect.x += columnWidth;
    if (column != cMax) {
        g.setColor(borderColor);
        g.fillRect(cellRect.x - 1, 0, 1, h);
    }
}
 
Example 8
Source Project: netbeans   Source File: JTreeTable.java    License: Apache License 2.0 6 votes vote down vote up
public void updateTreeTableHeader() {
    TableColumnModel tableColumnModel = getColumnModel();
    int n = tableColumnModel.getColumnCount();

    for (int i = 0; i < n; i++) {
        tableColumnModel.getColumn(i).setHeaderRenderer(headerRenderer);
    }

    if (tableHeader != getTableHeader()) {
        if (tableHeader != null) {
            tableHeader.removeMouseListener(headerListener);
        }

        if (tableHeader != null) {
            tableHeader.removeMouseMotionListener(headerListener);
        }

        tableHeader = getTableHeader();
        tableHeader.addMouseListener(headerListener);
        tableHeader.addMouseMotionListener(headerListener);
        updateTreeTable();
    }
}
 
Example 9
@Override
public void mouseClicked(final MouseEvent e) {
    final JTableHeader h = (JTableHeader) e.getSource();
    final TableColumnModel columnModel = h.getColumnModel();
    final int viewColumnIndex = columnModel.getColumnIndexAtX(e.getX());
    final int columnIndex = columnModel.getColumn(viewColumnIndex).getModelIndex();
    if (columnIndex != -1) {
        int direction = getSortingDirection(columnIndex);
        if (!e.isControlDown()) {
            clearSortingDirections();
            _tableHeader.repaint();
        }
        // Cycle the sorting states through {NOT_SORTED, ASCENDING, DESCENDING} or
        // {NOT_SORTED, DESCENDING, ASCENDING} depending on whether shift is pressed.
        direction += (e.isShiftDown() ? -1 : 1);
        direction = (direction + 4) % 3 - 1; // signed mod, returning {-1, 0, 1}
        setDirectionForColumn(columnIndex, direction);
        doSortBy = false;
        initViewToModel();
        fireTableDataChanged();
    }
}
 
Example 10
Source Project: dragonwell8_jdk   Source File: TableSorter.java    License: GNU General Public License v2.0 6 votes vote down vote up
public void addMouseListenerToHeaderInTable(JTable table) {
    final TableSorter sorter = this;
    final JTable tableView = table;
    tableView.setColumnSelectionAllowed(false);
    MouseAdapter listMouseListener = new MouseAdapter() {

        @Override
        public void mouseClicked(MouseEvent e) {
            TableColumnModel columnModel = tableView.getColumnModel();
            int viewColumn = columnModel.getColumnIndexAtX(e.getX());
            int column = tableView.convertColumnIndexToModel(viewColumn);
            if (e.getClickCount() == 1 && column != -1) {
                System.out.println("Sorting ...");
                int shiftPressed = e.getModifiers() & InputEvent.SHIFT_MASK;
                boolean ascending = (shiftPressed == 0);
                sorter.sortByColumn(column, ascending);
            }
        }
    };
    JTableHeader th = tableView.getTableHeader();
    th.addMouseListener(listMouseListener);
}
 
Example 11
Source Project: WePush   Source File: MaTemplateMsgForm.java    License: MIT License 6 votes vote down vote up
/**
 * 初始化模板消息数据table
 */
public static void initTemplateDataTable() {
    JTable msgDataTable = getInstance().getTemplateMsgDataTable();
    String[] headerNames = {"Name", "Value", "Color", "操作"};
    DefaultTableModel model = new DefaultTableModel(null, headerNames);
    msgDataTable.setModel(model);
    msgDataTable.updateUI();
    DefaultTableCellRenderer hr = (DefaultTableCellRenderer) msgDataTable.getTableHeader().getDefaultRenderer();
    // 表头列名居左
    hr.setHorizontalAlignment(DefaultTableCellRenderer.LEFT);

    TableColumnModel tableColumnModel = msgDataTable.getColumnModel();
    tableColumnModel.getColumn(headerNames.length - 1).
            setCellRenderer(new TableInCellButtonColumn(msgDataTable, headerNames.length - 1));
    tableColumnModel.getColumn(headerNames.length - 1).
            setCellEditor(new TableInCellButtonColumn(msgDataTable, headerNames.length - 1));

    // 设置列宽
    tableColumnModel.getColumn(3).setPreferredWidth(46);
    tableColumnModel.getColumn(3).setMaxWidth(46);
}
 
Example 12
Source Project: netbeans   Source File: DetailsPanel.java    License: Apache License 2.0 6 votes vote down vote up
private void paintVerticalLines(Graphics g) {
    int height = getHeight();
    int viewHeight = view.getHeight();
    if (viewHeight >= height) return;

    g.setColor(background);
    g.fillRect(0, viewHeight, getWidth(), getHeight() - viewHeight);

    int cellX = 0;
    int cellWidth;
    TableColumnModel model = view.getColumnModel();
    int columnCount = model.getColumnCount();
    
    g.setColor(DetailsTable.DEFAULT_GRID_COLOR);
    for (int i = 0; i < columnCount; i++) {
        cellWidth = model.getColumn(i).getWidth();
        cellX += cellWidth;
        g.drawLine(cellX - 1, viewHeight, cellX - 1, height);
    }
}
 
Example 13
Source Project: visualvm   Source File: SortableTableModel.java    License: GNU General Public License v2.0 6 votes vote down vote up
/**
 * Assigns this SortableTableModel to the JTable and sets the custom renderer for the selectable table header.
 * @param table The JTable to set this table model to
 */
public void setTable(JTable table) {
    TableColumnModel tableModel = table.getColumnModel();
    int n = tableModel.getColumnCount();

    for (int i = 0; i < n; i++) {
        tableModel.getColumn(i).setHeaderRenderer(headerRenderer);
    }

    if (tableHeader != table.getTableHeader()) {
        if (tableHeader != null) {
            tableHeader.removeMouseListener(headerListener);
            tableHeader.removeMouseMotionListener(headerListener);
            lastFocusedColumn = -1;
        }

        tableHeader = table.getTableHeader();
        tableHeader.setReorderingAllowed(false);
        tableHeader.addMouseListener(headerListener);
        tableHeader.addMouseMotionListener(headerListener);
    }
}
 
Example 14
Source Project: java-swing-tips   Source File: MainPanel.java    License: MIT License 6 votes vote down vote up
private MainPanel() {
  super(new BorderLayout());
  URL[] icons = {getIconUrl("wi0062-16.png"), getIconUrl("wi0063-16.png"), getIconUrl("wi0064-16.png")};
  String[] columnNames = {"Column1", "Column2", "Column3"};
  JTable table = new JTable(new DefaultTableModel(columnNames, 8));
  TableColumnModel m = table.getColumnModel();
  for (int i = 0; i < m.getColumnCount(); i++) {
    // m.getColumn(i).setHeaderRenderer(new IconColumnHeaderRenderer());
    // m.getColumn(i).setHeaderRenderer(new HtmlIconHeaderRenderer());
    // m.getColumn(i).setHeaderValue(String.format("<html><table><td><img src='%s'/></td>%s", icons[i], columnNames[i]));
    String hv = String.format("<html><table cellpadding='0' cellspacing='0'><td><img src='%s'/></td>&nbsp;%s", icons[i], columnNames[i]);
    m.getColumn(i).setHeaderValue(hv);
  }
  table.setAutoCreateRowSorter(true);
  add(new JScrollPane(table));

  JMenuBar mb = new JMenuBar();
  mb.add(LookAndFeelUtil.createLookAndFeelMenu());
  SwingUtilities.invokeLater(() -> getRootPane().setJMenuBar(mb));

  setPreferredSize(new Dimension(320, 240));
}
 
Example 15
Source Project: ghidra   Source File: GTableWidget.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Sets the column preferred widths.  If you give less widths then there are columns, then
 * the widths will be applied in order, with the remaining columns going untouched.
 * <p>
 * Note: this method needs to be called after building your columns. So, call this after
 * making any calls to {@link #addColumn(AbstractDynamicTableColumn)}.
 * <p>
 * <b>WARNING!</b>  If you set the widths to a size that is smaller than the total display,
 * then the table model will apply the extra space equally across your columns, resulting
 * in sizes that you did not set.  So, the best way to use this method is to set the
 * actual preferred size for your small columns and then set a very large size (400 or so)
 * for your columns that can be any size.
 * <p>
 *
 * @param widths the widths to apply
 */
public void setColumnPreferredWidths(int... widths) {
	int columnCount = table.getColumnCount();
	int n = Math.min(widths.length, columnCount);
	TableColumnModel model = table.getColumnModel();
	for (int i = 0; i < n; i++) {
		TableColumn column = model.getColumn(i);
		int width = widths[i];
		if (width == 75) {
			// Horrible Code: we have special knowledge that a value of 75 is the default
			// column size, which we use in TableColumnModelState to signal that we can
			// override the size.  So, if the user sets that value, then change it to
			// override our algorithm.
			width = 76;
		}
		column.setWidth(width);
		column.setPreferredWidth(widths[i]);
	}
}
 
Example 16
Source Project: Digital   Source File: StatsDialog.java    License: GNU General Public License v3.0 6 votes vote down vote up
/**
 * Creates a new instance
 *
 * @param frame the parent frame
 * @param model the table model
 */
public StatsDialog(Frame frame, TableModel model) {
    super(frame, Lang.get("menu_stats"));
    setDefaultCloseOperation(DISPOSE_ON_CLOSE);

    final JTable table = new JTable(model);
    getContentPane().add(new JScrollPane(table));
    final TableColumnModel columnModel = table.getColumnModel();
    final int fontSize = Screen.getInstance().getFontSize();
    columnModel.getColumn(0).setPreferredWidth(fontSize * 35);
    columnModel.getColumn(1).setPreferredWidth(fontSize * 6);
    columnModel.getColumn(2).setPreferredWidth(fontSize * 6);
    columnModel.getColumn(3).setPreferredWidth(fontSize * 8);
    table.setPreferredScrollableViewportSize(new Dimension(fontSize * 55, fontSize * 40));

    pack();
    setLocationRelativeTo(frame);
}
 
Example 17
public void mouseClicked(MouseEvent evt) {
    // XXX Benchmark sort performance
    //long start = System.currentTimeMillis();
    CommonUI.setWaitCursor(SwingUtilities.getRoot(table));

    TableColumnModel columnModel = table.getColumnModel();
    int viewColumn = columnModel.getColumnIndexAtX(evt.getX());
    int column = table.convertColumnIndexToModel(viewColumn);
    if (evt.getClickCount() == 1 && column != -1) {
        // Reverse the sorting direction.
        model.sortByColumn(column, !model.isAscending());
    }

    // XXX Benchmark performance
    //      System.out.println("Sort time: " +
    //         (System.currentTimeMillis() - start));
    CommonUI.setDefaultCursor(SwingUtilities.getRoot(table));
}
 
Example 18
Source Project: java-swing-tips   Source File: SortableTableModel.java    License: MIT License 6 votes vote down vote up
@Override public void mousePressed(MouseEvent e) {
  JTableHeader h = (JTableHeader) e.getComponent();
  TableColumnModel columnModel = h.getColumnModel();
  int viewColumn = columnModel.getColumnIndexAtX(e.getX());
  if (viewColumn < 0) {
    return;
  }
  TableCellRenderer tcr = h.getDefaultRenderer();
  int column = columnModel.getColumn(viewColumn).getModelIndex();
  if (column != -1 && tcr instanceof SortButtonRenderer) {
    SortButtonRenderer sbr = (SortButtonRenderer) tcr;
    sbr.setPressedColumn(column);
    sbr.setSelectedColumn(column);
    h.repaint();
    JTable table = h.getTable();
    if (table.isEditing()) {
      table.getCellEditor().stopCellEditing();
    }
    SortableTableModel model = (SortableTableModel) table.getModel();
    model.sortByColumn(column, SortButtonRenderer.DOWN == sbr.getState(column));
  }
}
 
Example 19
Source Project: visualvm   Source File: ProfilerTable.java    License: GNU General Public License v2.0 6 votes vote down vote up
Component getRenderer(TableCellRenderer renderer, int row, int column, boolean sized) {
        isCustomRendering = true;
        try {
            Component comp = prepareRenderer(renderer, row, column);
//            comp.setSize(comp.getPreferredSize().width, getRowHeight());
            if (sized) {
                comp.setSize(comp.getPreferredSize().width, getRowHeight());
                if (!isLeadingAlign(comp)) {
                    TableColumnModel m = getColumnModel();
                    int x = -comp.getWidth();
                    int c = m.getColumn(column).getWidth();
                    int _column = convertColumnIndexToModel(column);
                    if (isScrollableColumn(_column)) {
                        x += Math.max(c, getColumnPreferredWidth(_column));
                    } else {
                        x += c;
                    }
                    comp.move(x - m.getColumnMargin(), 0);
                }
            }
            
            return comp;
        } finally {
            isCustomRendering = false;
        }
    }
 
Example 20
Source Project: openjdk-8-source   Source File: TableSorter.java    License: GNU General Public License v2.0 6 votes vote down vote up
public void addMouseListenerToHeaderInTable(JTable table) {
    final TableSorter sorter = this;
    final JTable tableView = table;
    tableView.setColumnSelectionAllowed(false);
    MouseAdapter listMouseListener = new MouseAdapter() {

        @Override
        public void mouseClicked(MouseEvent e) {
            TableColumnModel columnModel = tableView.getColumnModel();
            int viewColumn = columnModel.getColumnIndexAtX(e.getX());
            int column = tableView.convertColumnIndexToModel(viewColumn);
            if (e.getClickCount() == 1 && column != -1) {
                System.out.println("Sorting ...");
                int shiftPressed = e.getModifiers() & InputEvent.SHIFT_MASK;
                boolean ascending = (shiftPressed == 0);
                sorter.sortByColumn(column, ascending);
            }
        }
    };
    JTableHeader th = tableView.getTableHeader();
    th.addMouseListener(listMouseListener);
}
 
Example 21
Source Project: netbeans   Source File: DiffTreeTable.java    License: Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
private void setupColumns() {
    ResourceBundle loc = NbBundle.getBundle(DiffTreeTable.class);
    setPropertyColumns(RevisionNode.COLUMN_NAME_PATH, loc.getString("LBL_DiffTree_Column_Path"),
            RevisionNode.COLUMN_NAME_DATE, loc.getString("LBL_DiffTree_Column_Time"),
            RevisionNode.COLUMN_NAME_USERNAME, loc.getString("LBL_DiffTree_Column_Username"),
            RevisionNode.COLUMN_NAME_MESSAGE, loc.getString("LBL_DiffTree_Column_Message"));
    setPropertyColumnDescription(RevisionNode.COLUMN_NAME_PATH, loc.getString("LBL_DiffTree_Column_Path_Desc"));
    setPropertyColumnDescription(RevisionNode.COLUMN_NAME_DATE, loc.getString("LBL_DiffTree_Column_Time_Desc"));
    setPropertyColumnDescription(RevisionNode.COLUMN_NAME_USERNAME, loc.getString("LBL_DiffTree_Column_Username_Desc"));
    setPropertyColumnDescription(RevisionNode.COLUMN_NAME_MESSAGE, loc.getString("LBL_DiffTree_Column_Message_Desc"));
    TableColumnModel model = getOutline().getColumnModel();
    if (model instanceof ETableColumnModel) {
        ((ETableColumnModel) model).setColumnHidden(model.getColumn(1), true);
    }
    TableColumn column = getOutline().getColumn(loc.getString("LBL_DiffTree_Column_Message"));
    column.setCellRenderer(new MessageRenderer(getOutline().getDefaultRenderer(String.class)));
    setDefaultColumnSizes();
}
 
Example 22
public void setView(List columns) {
  TableColumnModel model = getColumnModel();

  // Remove all the columns:
  for (int f = 0; f < _numCols; f++) {
    model.removeColumn(_tableColumns[f]);
  }
  Iterator selectedColumns = columns.iterator();
  Vector columnNameAndNumber = getColumnNameAndNumber();
  while (selectedColumns.hasNext()) {
    // add the column to the view
    model.addColumn(_tableColumns[columnNameAndNumber.indexOf(selectedColumns.next())]);
  }

  //SWING BUG:
  sizeColumnsToFit(-1);
}
 
Example 23
Source Project: chipster   Source File: EditableHeader.java    License: MIT License 6 votes vote down vote up
protected void recreateTableColumn(TableColumnModel columnModel) {
	int n = columnModel.getColumnCount();
	EditableHeaderTableColumn[] newCols = new EditableHeaderTableColumn[n];
	TableColumn[] oldCols = new TableColumn[n];
	for (int i=0;i<n;i++) {
		oldCols[i] = columnModel.getColumn(i);
		newCols[i] = new EditableHeaderTableColumn();
		newCols[i].copyValues(oldCols[i]);
	}
	for (int i=0;i<n;i++) {
		columnModel.removeColumn(oldCols[i]);
	}
	for (int i=0;i<n;i++) {
		columnModel.addColumn(newCols[i]);
	}
}
 
Example 24
/**
 * This method resizes the columns
 */
private void resizeColumnWidth(JTable table) {
  final TableColumnModel columnModel = table.getColumnModel();
  for (int column = 0; column < table.getColumnCount(); column++) {
    Object headerValue = columnModel.getColumn(column).getHeaderValue();
    TableCellRenderer headerRenderer = columnModel.getColumn(column).getHeaderRenderer();
    if (headerRenderer == null) {
      headerRenderer = table.getTableHeader().getDefaultRenderer();
    }
    Component headerComp =
        headerRenderer.getTableCellRendererComponent(table, headerValue, false, false, 0, column);
    int width = 30; // Min width
    width = Math.max(width, headerComp.getPreferredSize().width + 10);
    for (int row = 0; row < table.getRowCount(); row++) {
      TableCellRenderer renderer = table.getCellRenderer(row, column);
      Component comp = table.prepareRenderer(renderer, row, column);
      width = Math.max(comp.getPreferredSize().width + 10, width);
    }
    columnModel.getColumn(column).setPreferredWidth(width);
  }
}
 
Example 25
Source Project: netbeans   Source File: MappingTable.java    License: Apache License 2.0 6 votes vote down vote up
MappingTable(String filterName, List<FilterMappingData> filterMappings) {
    super();
    this.setModel(new MappingTableModel(filterName, filterMappings));

    TableColumnModel tcm = this.getColumnModel();

    // The filter name - this one is never editable
    tcm.getColumn(0).setPreferredWidth(72);

    // The pattern or servlet that we match to
    // This editor depends on whether the value of the other is
    // URL or Servlet
    tcm.getColumn(1).setPreferredWidth(72);
    this.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
    //setColors(false);
    setIntercellSpacing(new Dimension(margin, margin));
}
 
Example 26
Source Project: Logisim   Source File: TableSorter.java    License: GNU General Public License v3.0 6 votes vote down vote up
@Override
public void mouseClicked(MouseEvent e) {
	JTableHeader h = (JTableHeader) e.getSource();
	TableColumnModel columnModel = h.getColumnModel();
	int viewColumn = columnModel.getColumnIndexAtX(e.getX());
	int column = columnModel.getColumn(viewColumn).getModelIndex();
	if (column != -1) {
		int status = getSortingStatus(column);
		if (!e.isControlDown()) {
			cancelSorting();
		}
		// Cycle the sorting states through {NOT_SORTED, ASCENDING,
		// DESCENDING} or
		// {NOT_SORTED, DESCENDING, ASCENDING} depending on whether
		// shift is pressed.
		status = status + (e.isShiftDown() ? -1 : 1);
		status = (status + 4) % 3 - 1; // signed mod, returning {-1, 0,
										// 1}
		setSortingStatus(column, status);
	}
}
 
Example 27
Source Project: netbeans   Source File: PropertiesTable.java    License: Apache License 2.0 6 votes vote down vote up
private void setDefaultColumnSize() {
    int width = table.getWidth();
    TableColumnModel columnModel = table.getColumnModel();
    if (columns == null || columnModel == null)
        return;
    if (columnModel.getColumnCount() != columns.length)
        return;
    for (int i = 0; i < columns.length; i++) {
        String col = columns[i];                                
        sorter.setColumnComparator(i, null);                    
        if (col.equals(PropertiesTableModel.COLUMN_NAME_NAME)) {
            columnModel.getColumn(i).setPreferredWidth(width * 20 / 100);
        } else if (col.equals(PropertiesTableModel.COLUMN_NAME_VALUE)) {
            columnModel.getColumn(i).setPreferredWidth(width * 40 / 100);
        }
    }
}
 
Example 28
Source Project: netbeans   Source File: LivenessResultsPanel.java    License: Apache License 2.0 6 votes vote down vote up
private void setColumnsData() {
    barRenderer = getBarCellRenderer();

    TableColumnModel colModel = resTable.getColumnModel();
    colModel.getColumn(0).setPreferredWidth(minNamesColumnWidth);

    int index;

    for (int i = 0; i < colModel.getColumnCount(); i++) {
        index = resTableModel.getRealColumn(i);

        if (index == 0) {
            colModel.getColumn(i).setPreferredWidth(minNamesColumnWidth);
        } else {
            colModel.getColumn(i).setPreferredWidth(columnWidths[index - 1]);
        }

        if (index == 1) {
            colModel.getColumn(i).setCellRenderer(barRenderer);
        } else {
            colModel.getColumn(i).setCellRenderer(columnRenderers[index]);
        }
    }
}
 
Example 29
private ArrayList<Pair<Integer, Integer>> buildCurConfig() {
	TableColumnModel cm = table.getColumnModel();
	ArrayList<Pair<Integer, Integer>> columnsConfig = new ArrayList<>(cm.getColumnCount());
	for (int i = 0; i < cm.getColumnCount(); i++) {
		TableColumn c = cm.getColumn(i);
		columnsConfig.add(Pair.of(c.getModelIndex(), c.getWidth()));
	}
	return columnsConfig;
}
 
Example 30
Source Project: visualvm   Source File: SampledLivePanel.java    License: GNU General Public License v2.0 5 votes vote down vote up
private void setColumnsData() {
    TableColumnModel colModel = resTable.getColumnModel();
    for (int i = 0; i < resTableModel.getColumnCount(); i++) {
        int index = resTableModel.getRealColumn(i);
        if (index != 0)
            colModel.getColumn(i).setPreferredWidth(columnWidths[index - 1]);
        colModel.getColumn(i).setCellRenderer(columnRenderers[index]);
    }
}