Java Code Examples for javax.swing.table.DefaultTableColumnModel

The following examples show how to use javax.swing.table.DefaultTableColumnModel. 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
public static void initializeTable(JTable table)
{
	table.setAutoCreateColumnsFromModel(false);
	JTableHeader header = table.getTableHeader();
	TableColumnModel columns = new DefaultTableColumnModel();
	TableCellRenderer headerRenderer = header.getDefaultRenderer();
	columns.addColumn(Utilities.createTableColumn(0, "in_level", headerRenderer, false));
	columns.addColumn(Utilities.createTableColumn(1, "in_class", headerRenderer, true));
	TableColumn remainCol = Utilities.createTableColumn(2, "in_iskRemain", headerRenderer, false);
	remainCol.setCellRenderer(new BoldNumberRenderer());
	columns.addColumn(remainCol);
	columns.addColumn(Utilities.createTableColumn(3, "in_gained", headerRenderer, false));
	table.setDefaultRenderer(Integer.class, new TableCellUtilities.AlignRenderer(SwingConstants.CENTER));
	table.setColumnModel(columns);
	table.setFocusable(false);
	header.setReorderingAllowed(false);
	header.setResizingAllowed(false);
}
 
Example 2
Source Project: zencash-swing-wallet-ui   Source File: AddressBookPanel.java    License: MIT License 6 votes vote down vote up
private JScrollPane buildTablePanel() {
      table = new JTable(new AddressBookTableModel(),new DefaultTableColumnModel());
      TableColumn nameColumn = new TableColumn(0);
      TableColumn addressColumn = new TableColumn(1);
      table.addColumn(nameColumn);
      table.addColumn(addressColumn);
      table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); // one at a time
      table.getSelectionModel().addListSelectionListener(new AddressListSelectionListener());
      table.addMouseListener(new AddressMouseListener());
      
      // TODO: isolate in utility
TableCellRenderer renderer = table.getCellRenderer(0, 0);
Component comp = renderer.getTableCellRendererComponent(table, "123", false, false, 0, 0);
table.setRowHeight(new Double(comp.getPreferredSize().getHeight()).intValue() + 2);
      
      JScrollPane scrollPane = new JScrollPane(table);
      return scrollPane;
  }
 
Example 3
/**
 * Overriding the default re-ordering functionality.<p>
 * Re-ordering allowed if both of the i.e <code>columnIndex,newIndex</code>
 * are outside the limit.
 *
 * @param table the target tmodel
 * @param lmt re-ordering limit
 */
public static void setReorderColumn(JTable table, final int lmt) {
    table.setColumnModel(new DefaultTableColumnModel() {
        private static final long serialVersionUID = 1L;

        @Override
        public void moveColumn(int columnIndex, int newIndex) {
            if (columnIndex <= lmt) {
                return;
            } else if (newIndex <= lmt) {
                return;
            }
            super.moveColumn(columnIndex, newIndex);
        }
    });
}
 
Example 4
Source Project: pcgen   Source File: EquipmentModel.java    License: GNU Lesser General Public License v2.1 6 votes vote down vote up
public static void initializeTreeTable(JTreeTable treeTable)
{
	treeTable.getTree().setRowHeight(0);
	treeTable.setFocusable(false);
	treeTable.getTree().putClientProperty("JTree.lineStyle", "Horizontal");
	normFont = treeTable.getFont();
	headerFont = FontManipulation.title(normFont);
	biggerFont = FontManipulation.title(FontManipulation.xxlarge(normFont));
	lessFont = FontManipulation.less(normFont);
	treeTable.setAutoCreateColumnsFromModel(false);
	{
		DefaultTableColumnModel model = new DefaultTableColumnModel();
		CellRenderer renderer = new CellRenderer();
		TableColumn column = new TableColumn(0);
		column.setResizable(true);
		model.addColumn(column);
		model.addColumn(createFixedColumn(1, 75, renderer));
		model.addColumn(createFixedColumn(2, 75, renderer));
		model.addColumn(createFixedColumn(3, 50, renderer));
		model.addColumn(createFixedColumn(4, 50, renderer));
		treeTable.setAutoResizeMode(JTable.AUTO_RESIZE_ALL_COLUMNS);
		treeTable.setColumnModel(model);
		treeTable.getTableHeader().setResizingAllowed(false);
	}
	treeTable.setTreeCellRenderer(new TreeRenderer());
}
 
Example 5
public static void initializeTable(JTable classLevelTable)
{
	JTableHeader tableHeader = classLevelTable.getTableHeader();
	tableHeader.setResizingAllowed(false);
	tableHeader.setReorderingAllowed(false);
	TableColumnModel columnModel = new DefaultTableColumnModel();
	TableCellRenderer headerRenderer = tableHeader.getDefaultRenderer();
	columnModel.addColumn(Utilities.createTableColumn(0, "Level", headerRenderer, false));
	columnModel.addColumn(Utilities.createTableColumn(1, "HP", headerRenderer, false));
	columnModel.addColumn(Utilities.createTableColumn(2, "Class (All Levels In Class)", headerRenderer, true));
	classLevelTable.setColumnModel(columnModel);
	classLevelTable.setAutoCreateColumnsFromModel(false);
	classLevelTable.setAutoResizeMode(JTable.AUTO_RESIZE_LAST_COLUMN);
	classLevelTable.setFocusable(false);
	classLevelTable.setCellSelectionEnabled(false);
	classLevelTable.setRowHeight(20);
}
 
Example 6
Source Project: bigtable-sql   Source File: PluginSummaryTable.java    License: Apache License 2.0 6 votes vote down vote up
public PluginSummaryTable(PluginInfo[] pluginInfo, PluginStatus[] pluginStatus)
{
	super(new MyTableModel(pluginInfo, pluginStatus));

	setSelectionMode(ListSelectionModel.SINGLE_INTERVAL_SELECTION);
	getTableHeader().setResizingAllowed(true);
	getTableHeader().setReorderingAllowed(true);
	setAutoCreateColumnsFromModel(false);
	setAutoResizeMode(AUTO_RESIZE_LAST_COLUMN);

	final TableColumnModel tcm = new DefaultTableColumnModel();
	for (int i = 0; i < s_columnWidths.length; ++i)
	{
		final TableColumn col = new TableColumn(i, s_columnWidths[i]);
		col.setHeaderValue(s_hdgs[i]);
		tcm.addColumn(col);
	}
	setColumnModel(tcm);
}
 
Example 7
Source Project: bigtable-sql   Source File: UpdateSummaryTable.java    License: Apache License 2.0 6 votes vote down vote up
public UpdateSummaryTable(List<ArtifactStatus> artifactStatus, 
                           UpdateSummaryTableModel model) {
    super(model);
    _model = model;
    _artifacts = artifactStatus;
    setSelectionMode(ListSelectionModel.SINGLE_INTERVAL_SELECTION);
    getTableHeader().setResizingAllowed(true);
    getTableHeader().setReorderingAllowed(true);
    setAutoCreateColumnsFromModel(false);
    setAutoResizeMode(AUTO_RESIZE_LAST_COLUMN);

    final TableColumnModel tcm = new DefaultTableColumnModel();
    JComboBox _actionComboBox = new JComboBox();
for (int i = 0; i < model.getColumnCount(); ++i) {
       final TableColumn col = new TableColumn(i, model.getColumnWidth(i));
       col.setHeaderValue(model.getColumnName(i));
       if (i == 3) {
          col.setCellEditor(new DefaultCellEditor(initCbo(_actionComboBox)));
       }
       tcm.addColumn(col);
    }
    setColumnModel(tcm);
    initPopup();
 }
 
Example 8
public static void initializeTable(JTable table)
{
	table.setAutoCreateColumnsFromModel(false);
	JTableHeader header = table.getTableHeader();
	TableColumnModel columns = new DefaultTableColumnModel();
	TableCellRenderer headerRenderer = header.getDefaultRenderer();
	columns.addColumn(Utilities.createTableColumn(0, "in_level", headerRenderer, false));
	columns.addColumn(Utilities.createTableColumn(1, "in_class", headerRenderer, true));
	TableColumn remainCol = Utilities.createTableColumn(2, "in_iskRemain", headerRenderer, false);
	remainCol.setCellRenderer(new BoldNumberRenderer());
	columns.addColumn(remainCol);
	columns.addColumn(Utilities.createTableColumn(3, "in_gained", headerRenderer, false));
	table.setDefaultRenderer(Integer.class, new TableCellUtilities.AlignRenderer(SwingConstants.CENTER));
	table.setColumnModel(columns);
	table.setFocusable(false);
	header.setReorderingAllowed(false);
	header.setResizingAllowed(false);
}
 
Example 9
Source Project: pcgen   Source File: EquipmentModel.java    License: GNU Lesser General Public License v2.1 6 votes vote down vote up
public static void initializeTreeTable(JTreeTable treeTable)
{
	treeTable.getTree().setRowHeight(0);
	treeTable.setFocusable(false);
	treeTable.getTree().putClientProperty("JTree.lineStyle", "Horizontal");
	normFont = treeTable.getFont();
	headerFont = FontManipulation.title(normFont);
	biggerFont = FontManipulation.title(FontManipulation.xxlarge(normFont));
	lessFont = FontManipulation.less(normFont);
	treeTable.setAutoCreateColumnsFromModel(false);
	{
		DefaultTableColumnModel model = new DefaultTableColumnModel();
		CellRenderer renderer = new CellRenderer();
		TableColumn column = new TableColumn(0);
		column.setResizable(true);
		model.addColumn(column);
		model.addColumn(createFixedColumn(1, 75, renderer));
		model.addColumn(createFixedColumn(2, 75, renderer));
		model.addColumn(createFixedColumn(3, 50, renderer));
		model.addColumn(createFixedColumn(4, 50, renderer));
		treeTable.setAutoResizeMode(JTable.AUTO_RESIZE_ALL_COLUMNS);
		treeTable.setColumnModel(model);
		treeTable.getTableHeader().setResizingAllowed(false);
	}
	treeTable.setTreeCellRenderer(new TreeRenderer());
}
 
Example 10
public static void initializeTable(JTable classLevelTable)
{
	JTableHeader tableHeader = classLevelTable.getTableHeader();
	tableHeader.setResizingAllowed(false);
	tableHeader.setReorderingAllowed(false);
	TableColumnModel columnModel = new DefaultTableColumnModel();
	TableCellRenderer headerRenderer = tableHeader.getDefaultRenderer();
	columnModel.addColumn(Utilities.createTableColumn(0, "Level", headerRenderer, false));
	columnModel.addColumn(Utilities.createTableColumn(1, "HP", headerRenderer, false));
	columnModel.addColumn(Utilities.createTableColumn(2, "Class (All Levels In Class)", headerRenderer, true));
	classLevelTable.setColumnModel(columnModel);
	classLevelTable.setAutoCreateColumnsFromModel(false);
	classLevelTable.setAutoResizeMode(JTable.AUTO_RESIZE_LAST_COLUMN);
	classLevelTable.setFocusable(false);
	classLevelTable.setCellSelectionEnabled(false);
	classLevelTable.setRowHeight(20);
}
 
Example 11
Source Project: nmonvisualizer   Source File: ByDataSetTable.java    License: Apache License 2.0 6 votes vote down vote up
@Override
protected JTableHeader createDefaultTableHeader() {
    return new JTableHeader(getColumnModel()) {
        private static final long serialVersionUID = -9130260383688373828L;

        @Override
        public String getToolTipText(MouseEvent event) {
            super.getToolTipText(event);

            int column = getTable().convertColumnIndexToModel(
                    ((DefaultTableColumnModel) getTable().getColumnModel()).getColumnIndexAtX(event.getX()));

            // skip tooltips on Data Type and Metric columns
            if (column > 1) {
                return ((ByDataSetTableModel) getTable().getModel()).getColumnName(column);
            }
            else {
                return null;
            }
        }
    };
}
 
Example 12
Source Project: netbeans   Source File: DataViewBuilders.java    License: Apache License 2.0 5 votes vote down vote up
protected void setupInstance(DefaultTableColumnModel instance) {
    super.setupInstance(instance);
    
    for (TableColumnBuilder builder : tableColumns)
        instance.addColumn(builder.createInstance());
    instance.setColumnMargin(columnMargin); 
}
 
Example 13
Source Project: hush-swing-wallet-ui   Source File: AddressBookPanel.java    License: MIT License 5 votes vote down vote up
private JTable buildTable() {
    final JTable table = new JTable(new AddressBookTableModel(), new DefaultTableColumnModel());
    table.addColumn(new TableColumn(0)); // name column
    table.addColumn(new TableColumn(1)); // address column
    table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); // one at a time
    table.getSelectionModel().addListSelectionListener(new AddressListSelectionListener());
    table.addMouseListener(new AddressMouseListener());
    return table;
}
 
Example 14
Source Project: visualvm   Source File: DataViewBuilders.java    License: GNU General Public License v2.0 5 votes vote down vote up
protected void setupInstance(DefaultTableColumnModel instance) {
    super.setupInstance(instance);
    
    for (TableColumnBuilder builder : tableColumns)
        instance.addColumn(builder.createInstance());
    instance.setColumnMargin(columnMargin); 
}
 
Example 15
/**
 * Initialise a tree table that will be backed by an AbilityTreeTableModel.
 * @param treeTable The tree table to be initialized.
 */
public static void initializeTreeTable(JTreeTable treeTable)
{
	treeTable.getTree().putClientProperty("JTree.lineStyle", "Horizontal"); //$NON-NLS-1$ //$NON-NLS-2$
	treeTable.setAutoCreateColumnsFromModel(false);
	DefaultTableColumnModel model = new DefaultTableColumnModel();
	TableCellRenderer headerRenderer = treeTable.getTableHeader().getDefaultRenderer();
	model.addColumn(Utilities.createTableColumn(0, "in_featSelectedAbilities", headerRenderer, true)); //$NON-NLS-1$
	model.addColumn(Utilities.createTableColumn(1, "in_featChoices", //$NON-NLS-1$
		headerRenderer, true));
	treeTable.setAutoResizeMode(JTable.AUTO_RESIZE_ALL_COLUMNS);
	treeTable.setColumnModel(model);
	treeTable.setDefaultRenderer(String.class, new TableCellUtilities.AlignRenderer(SwingConstants.LEFT, true));
}
 
Example 16
Source Project: bigtable-sql   Source File: OverviewCtrl.java    License: Apache License 2.0 5 votes vote down vote up
private void initScaleTable(DataScale[] scales, List<Object[]> rows, ColumnDisplayDefinition[] columnDefinitions, boolean keepFormerParent, CallDepthComboModel callDepth)
{
   DataScaleTableModel dataScaleTableModel = new DataScaleTableModel(scales, callDepth);
   DataScaleTable dataScaleTable = new DataScaleTable(dataScaleTableModel, rows, columnDefinitions);

   TableColumnModel tcm = new DefaultTableColumnModel();
   dataScaleTable.setColumnModel(tcm);

   for (int i = 0; i < DataScaleTableModel.getColumnNames().length; i++)
   {
      TableColumn col = new TableColumn(i);
      col.setHeaderValue(DataScaleTableModel.getColumnNames()[i]);
      if (DataScaleTableModel.COL_NAME_COLUMN.equals(DataScaleTableModel.getColumnNames()[i]))
      {
         col.setPreferredWidth(DataScaleTableColumnWidthsPersister.getColumnWidthForColName(DataScaleTableModel.COL_NAME_COLUMN));
      }
      else if (DataScaleTableModel.COL_NAME_DATA.equals(DataScaleTableModel.getColumnNames()[i]))
      {
         col.setPreferredWidth(DataScaleTableColumnWidthsPersister.getColumnWidthForColName(DataScaleTableModel.COL_NAME_DATA));
      }
      tcm.addColumn(col);
   }

   _overviewHolder.setOverview(dataScaleTable, keepFormerParent);
   initGui();

}
 
Example 17
Source Project: java-swing-tips   Source File: MainPanel.java    License: MIT License 5 votes vote down vote up
@SuppressWarnings("PMD.AvoidInstantiatingObjectsInLoops")
@Override protected void initialize(Class<?> type, Object oldInstance, Object newInstance, Encoder encoder) {
  super.initialize(type, oldInstance, newInstance, encoder);
  DefaultTableColumnModel m = (DefaultTableColumnModel) oldInstance;
  for (int col = 0; col < m.getColumnCount(); col++) {
    Object[] o = {m.getColumn(col)};
    encoder.writeStatement(new Statement(oldInstance, "addColumn", o));
  }
}
 
Example 18
/**
 * Initialise a tree table that will be backed by an AbilityTreeTableModel.
 * @param treeTable The tree table to be initialized.
 */
public static void initializeTreeTable(JTreeTable treeTable)
{
	treeTable.getTree().putClientProperty("JTree.lineStyle", "Horizontal"); //$NON-NLS-1$ //$NON-NLS-2$
	treeTable.setAutoCreateColumnsFromModel(false);
	DefaultTableColumnModel model = new DefaultTableColumnModel();
	TableCellRenderer headerRenderer = treeTable.getTableHeader().getDefaultRenderer();
	model.addColumn(Utilities.createTableColumn(0, "in_featSelectedAbilities", headerRenderer, true)); //$NON-NLS-1$
	model.addColumn(Utilities.createTableColumn(1, "in_featChoices", //$NON-NLS-1$
		headerRenderer, true));
	treeTable.setAutoResizeMode(JTable.AUTO_RESIZE_ALL_COLUMNS);
	treeTable.setColumnModel(model);
	treeTable.setDefaultRenderer(String.class, new TableCellUtilities.AlignRenderer(SwingConstants.LEFT, true));
}
 
Example 19
public TableColumnModel getColumnModel() {
    final TableColumnModel columnModel = new DefaultTableColumnModel();
    for (TableColumn aColumnList : columnList) {
        columnModel.addColumn(aColumnList);
    }
    return columnModel;
}
 
Example 20
Source Project: snap-desktop   Source File: AOITableModel.java    License: GNU General Public License v3.0 5 votes vote down vote up
public TableColumnModel getColumnModel() {
    final TableColumnModel columnModel = new DefaultTableColumnModel();
    for (TableColumn aColumnList : columnList) {
        columnModel.addColumn(aColumnList);
    }
    return columnModel;
}
 
Example 21
Source Project: weblaf   Source File: SwingUtils.java    License: GNU General Public License v3.0 5 votes vote down vote up
/**
 * Packs table column at the specified index to its preferred width.
 *
 * @param table  table to process
 * @param col    column index
 * @param margin column side margin
 */
public static void packColumnWidth ( @NotNull final JTable table, final int col, final int margin )
{
    final DefaultTableColumnModel columnModel = ( DefaultTableColumnModel ) table.getColumnModel ();
    final TableColumn column = columnModel.getColumn ( col );
    int width;

    // Header renderer
    TableCellRenderer renderer = column.getHeaderRenderer ();
    if ( renderer == null )
    {
        renderer = table.getTableHeader ().getDefaultRenderer ();
    }

    // Header width
    Component rendererComponent = renderer.getTableCellRendererComponent ( table, column.getHeaderValue (), false, false, 0, 0 );
    width = rendererComponent.getPreferredSize ().width;

    // Cells width
    for ( int r = 0; r < table.getRowCount (); r++ )
    {
        renderer = table.getCellRenderer ( r, col );
        rendererComponent = renderer.getTableCellRendererComponent ( table, table.getValueAt ( r, col ), false, false, r, col );
        width = Math.max ( width, rendererComponent.getPreferredSize ().width );
    }

    // Margin
    width += 2 * margin;

    // Final values
    column.setPreferredWidth ( width );
    column.setWidth ( width );
}
 
Example 22
Source Project: netbeans   Source File: DataViewBuilders.java    License: Apache License 2.0 4 votes vote down vote up
static TableColumnModelBuilder fromField(Instance instance, String field, Heap heap) {
    Object model = instance.getValueOfField(field);
    if (!(model instanceof Instance)) return null;
    if (!DetailsUtils.isSubclassOf((Instance)model, DefaultTableColumnModel.class.getName())) return null;
    return new TableColumnModelBuilder((Instance)model, heap);
}
 
Example 23
Source Project: netbeans   Source File: DataViewBuilders.java    License: Apache License 2.0 4 votes vote down vote up
protected DefaultTableColumnModel createInstanceImpl() {
    return new DefaultTableColumnModel();
}
 
Example 24
Source Project: visualvm   Source File: DataViewBuilders.java    License: GNU General Public License v2.0 4 votes vote down vote up
static TableColumnModelBuilder fromField(Instance instance, String field, Heap heap) {
    Object model = instance.getValueOfField(field);
    if (!(model instanceof Instance)) return null;
    if (!DetailsUtils.isSubclassOf((Instance)model, DefaultTableColumnModel.class.getName())) return null;
    return new TableColumnModelBuilder((Instance)model, heap);
}
 
Example 25
Source Project: visualvm   Source File: DataViewBuilders.java    License: GNU General Public License v2.0 4 votes vote down vote up
protected DefaultTableColumnModel createInstanceImpl() {
    return new DefaultTableColumnModel();
}
 
Example 26
Source Project: AndroidDBvieweR   Source File: TableEditor.java    License: Apache License 2.0 4 votes vote down vote up
public void adjustTable(Component tableContainer, JTable table) {
        table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
        DefaultTableColumnModel defColumnModel = (DefaultTableColumnModel) table.getColumnModel();
        int columnCount = table.getColumnCount();
        int[] columnWidths = new int[columnCount];
        int totalWidth = 0;
        for (int columnIndex = 0; columnIndex < columnCount; columnIndex++) {
            TableColumn tableColumn = defColumnModel.getColumn(columnIndex);
            TableCellRenderer headerRenderer = tableColumn.getHeaderRenderer();
            if (headerRenderer == null) {
                headerRenderer = table.getTableHeader().getDefaultRenderer();
            }
            int minWidth = tableColumn.getMinWidth();
            int headerWidth = headerRenderer.getTableCellRendererComponent(table, tableColumn.getHeaderValue(), false, false, -1, columnIndex).getPreferredSize().width;
            
            int finalColumnWidth = Math.max(minWidth, headerWidth);
            for (int rowIndex = 0; rowIndex < table.getRowCount(); rowIndex++) {
                int rowWidth = table.prepareRenderer(table.getCellRenderer(rowIndex, columnIndex), rowIndex, columnIndex).getPreferredSize().width;
                finalColumnWidth = Math.max(rowWidth, finalColumnWidth);
//                Object cellValue = table.getValueAt(rowIndex, columnIndex);
//                try {
//                    long longValue = (Long) cellValue;
//                    cellTextField.setHorizontalAlignment(JTextField.RIGHT);
//                } catch (Exception e0) {
//                    try {
//                        double doubleValue = (Double) cellValue;
//                        cellTextField.setHorizontalAlignment(JTextField.RIGHT);
//                    } catch (Exception e1) {
//                        try {
//                            boolean doubleValue = (Boolean) cellValue;
//                            cellTextField.setHorizontalAlignment(JTextField.CENTER);
//                        } catch (Exception e2) {
//                            cellTextField.setHorizontalAlignment(JTextField.LEADING);
//                        }
//                    }
//                }
            }
            columnWidths[columnIndex] = finalColumnWidth;
            totalWidth += columnWidths[columnIndex];
        }
        int containerWidth = tableContainer.getWidth();
        if (totalWidth < containerWidth) {
            TableColumnModel columnModel = table.getColumnModel();
            int rest = containerWidth - totalWidth;
            int additionalWidth = rest / columnCount;
            int extraWidth = rest % columnCount;
            int maxWidthColumnIndex = 0;
            int maxColumnWidth = 0;
            for (int columnIndex = 0; columnIndex < columnCount; columnIndex++) {
                int columnWidth = columnWidths[columnIndex];
                if (maxColumnWidth < columnWidth) {
                    maxColumnWidth = columnWidth;
                    maxWidthColumnIndex = columnIndex;
                }
            }
            for (int columnIndex = 0; columnIndex < columnCount; columnIndex++) {
                columnModel.getColumn(columnIndex).setPreferredWidth(columnWidths[columnIndex] + additionalWidth + (columnIndex == maxWidthColumnIndex ? extraWidth : 0));
            }
        }
    }
 
Example 27
Source Project: open-ig   Source File: GUIUtils.java    License: GNU Lesser General Public License v3.0 4 votes vote down vote up
/**
	 * Resizes the table columns based on the column and data preferred widths.
	 * @param table the original table
	 * @param model the data model
	 * @return the table itself
	 */
    public static JTable autoResizeColWidth(JTable table, AbstractTableModel model) {
        table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
        table.setModel(model);
 
        int margin = 5;
 
        for (int i = 0; i < table.getColumnCount(); i++) {
            int                     vColIndex = i;
            DefaultTableColumnModel colModel  = (DefaultTableColumnModel) table.getColumnModel();
            TableColumn             col       = colModel.getColumn(vColIndex);
            int                     width;
 
            // 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);
        }
 
        ((DefaultTableCellRenderer) table.getTableHeader().getDefaultRenderer()).setHorizontalAlignment(
            SwingConstants.LEFT);
 
        // table.setAutoCreateRowSorter(true);
//        table.getTableHeader().setReorderingAllowed(false);
 
//        for (int i = 0; i < table.getColumnCount(); i++) {
//            TableColumn column = table.getColumnModel().getColumn(i);
// 
//            column.setCellRenderer(new DefaultTableColour());
//        }
 
        return table;
    }
 
Example 28
Source Project: open-ig   Source File: AnimPlayList.java    License: GNU Lesser General Public License v3.0 4 votes vote down vote up
/**
* Resizes the table columns based on the column and data preferred widths.
* @param table the original table
* @param model the data model
* @return the table itself
*/
  public static JTable autoResizeColWidth(JTable table, AbstractTableModel model) {
      table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
      table.setModel(model);
 
      int margin = 5;
 
      for (int i = 0; i < table.getColumnCount(); i++) {
          int                     vColIndex = i;
          DefaultTableColumnModel colModel  = (DefaultTableColumnModel) table.getColumnModel();
          TableColumn             col       = colModel.getColumn(vColIndex);
          int                     width;
 
          // 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);
      }
 
      ((DefaultTableCellRenderer) table.getTableHeader().getDefaultRenderer()).setHorizontalAlignment(
          SwingConstants.LEFT);
 
      return table;
  }
 
Example 29
Source Project: pcgen   Source File: StatTableModel.java    License: GNU Lesser General Public License v2.1 4 votes vote down vote up
public static void initializeTable(JTable statsTable)
{
	JTableHeader tableHeader = statsTable.getTableHeader();
	tableHeader.setResizingAllowed(false);
	tableHeader.setReorderingAllowed(false);

	statsTable.setAutoCreateColumnsFromModel(false);
	DefaultTableColumnModel columnModel = new DefaultTableColumnModel();
	{
		TableColumn column =
				Utilities.createTableColumn(ABILITY_NAME, "Ability", new AbilityHeaderCellRenderer(), true);
		column.setIdentifier(ABILITY_COLUMN_ID);
		columnModel.addColumn(column);

		String htmlText = "<html><div align=\"center\">Final<br>Score</div></html>";
		column = Utilities.createTableColumn(FINAL_ABILITY_SCORE, htmlText, new FixedHeaderCellRenderer(htmlText),
			false);
		column.setCellRenderer(new ValueRenderer());
		columnModel.addColumn(column);

		TableCellRenderer renderer = new ModRenderer();
		htmlText = "<html><div align=\"center\">Ability<br>Mod</div></html>";
		column = Utilities.createTableColumn(ABILITY_MOD, htmlText, new FixedHeaderCellRenderer(htmlText), false);
		column.setCellRenderer(renderer);
		columnModel.addColumn(column);

		htmlText = "<html><div align=\"center\">Editable<br>Score</div></html>";
		column = Utilities.createTableColumn(EDITABLE_SCORE, htmlText, new FixedHeaderCellRenderer(htmlText),
			false);
		column.setIdentifier(EDITABLE_COLUMN_ID);
		columnModel.addColumn(column);

		htmlText = "<html><div align=\"center\">Race<br>Adj</div></html>";
		column = Utilities.createTableColumn(RACE_ADJ, htmlText, new FixedHeaderCellRenderer(htmlText), false);
		column.setCellRenderer(renderer);
		columnModel.addColumn(column);

		htmlText = "<html><div align=\"center\">Misc<br>Adj</div></html>";
		column = Utilities.createTableColumn(MISC_ADJ, htmlText, new FixedHeaderCellRenderer(htmlText), false);
		column.setCellRenderer(renderer);
		columnModel.addColumn(column);
	}
	statsTable.setColumnModel(columnModel);
	statsTable.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
	statsTable.setShowVerticalLines(false);
	statsTable.setCellSelectionEnabled(false);
	statsTable.setFocusable(false);
	// XXX this should be calculated relative to font size and the size of a jspinner
	statsTable.setRowHeight(27);
	statsTable.setOpaque(false);
	tableHeader.setFont(FontManipulation.title(statsTable.getFont()));
	FontManipulation.large(statsTable);
}
 
Example 30
Source Project: java-swing-tips   Source File: MainPanel.java    License: MIT License 4 votes vote down vote up
private MainPanel() {
  super(new BorderLayout());
  String[] columnNames = {"A", "B"};
  Object[][] data = {
    {"aaa", "ccccccc"}, {"bbb", "☀☁☂☃"}
  };
  JTable table = new JTable(new DefaultTableModel(data, columnNames));
  table.setAutoCreateRowSorter(true);
  table.getTableHeader().setComponentPopupMenu(new TableHeaderPopupMenu());

  JTextArea textArea = new JTextArea();

  JSplitPane sp = new JSplitPane(JSplitPane.VERTICAL_SPLIT);
  sp.setResizeWeight(.5);
  sp.setTopComponent(new JScrollPane(table));
  sp.setBottomComponent(new JScrollPane(textArea));

  JButton encButton = new JButton("XMLEncoder");
  encButton.addActionListener(e -> {
    try {
      File file = File.createTempFile("output", ".xml");
      // try (XMLEncoder xe = new XMLEncoder(new BufferedOutputStream(new FileOutputStream(file)))) {
      try (XMLEncoder xe = new XMLEncoder(new BufferedOutputStream(Files.newOutputStream(file.toPath())))) {
        String[] constructorPropertyNames = {"column", "sortOrder"};
        xe.setPersistenceDelegate(RowSorter.SortKey.class, new DefaultPersistenceDelegate(constructorPropertyNames));
        xe.writeObject(table.getRowSorter().getSortKeys());

        xe.setPersistenceDelegate(DefaultTableModel.class, new DefaultTableModelPersistenceDelegate());
        xe.writeObject(table.getModel());

        xe.setPersistenceDelegate(DefaultTableColumnModel.class, new DefaultTableColumnModelPersistenceDelegate());
        xe.writeObject(table.getColumnModel());
      }
      try (Reader r = Files.newBufferedReader(file.toPath(), StandardCharsets.UTF_8)) {
        textArea.read(r, "temp");
      }
    } catch (IOException ex) {
      ex.printStackTrace();
      textArea.setText(ex.getMessage());
    }
  });

  JButton decButton = new JButton("XMLDecoder");
  decButton.addActionListener(e -> {
    String text = textArea.getText();
    if (text.isEmpty()) {
      return;
    }
    byte[] bytes = text.getBytes(StandardCharsets.UTF_8);
    try (XMLDecoder xd = new XMLDecoder(new BufferedInputStream(new ByteArrayInputStream(bytes)))) {
      @SuppressWarnings("unchecked")
      List<? extends RowSorter.SortKey> keys = (List<? extends RowSorter.SortKey>) xd.readObject();
      DefaultTableModel model = (DefaultTableModel) xd.readObject();
      table.setModel(model);
      table.setAutoCreateRowSorter(true);
      table.getRowSorter().setSortKeys(keys);
      DefaultTableColumnModel cm = (DefaultTableColumnModel) xd.readObject();
      table.setColumnModel(cm);
    }
  });

  JButton clearButton = new JButton("clear");
  clearButton.addActionListener(e -> table.setModel(new DefaultTableModel()));

  JPanel p = new JPanel();
  p.add(encButton);
  p.add(decButton);
  p.add(clearButton);
  add(sp);
  add(p, BorderLayout.SOUTH);
  setPreferredSize(new Dimension(320, 240));
}