Java Code Examples for javax.swing.table.TableColumn#setPreferredWidth()

The following examples show how to use javax.swing.table.TableColumn#setPreferredWidth() . 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 File: ALTaskTextViewerPanel.java    From moa with GNU General Public License v3.0 6 votes vote down vote up
private void rescaleTableColumns()
{
	// iterate over all columns to resize them individually
	TableColumnModel columnModel = previewTable.getColumnModel();
	for(int columnIdx = 0; columnIdx < columnModel.getColumnCount(); ++columnIdx)
	{
		// get the current column
		TableColumn column = columnModel.getColumn(columnIdx);
		// get the renderer for the column header to calculate the preferred with for the header
		TableCellRenderer renderer = column.getHeaderRenderer();
		// check if the renderer is null
		if(renderer == null)
		{
			// if it is null use the default renderer for header
			renderer = previewTable.getTableHeader().getDefaultRenderer();
		}
		// create a cell to calculate its preferred size
		Component comp = renderer.getTableCellRendererComponent(previewTable, column.getHeaderValue(), false, false, 0, columnIdx);
		int width = comp.getPreferredSize().width;
		// set the maximum width which was calculated
		column.setPreferredWidth(width);
	}
}
 
Example 2
Source File: LogTable.java    From cacheonix-core with GNU Lesser General Public License v2.1 6 votes vote down vote up
public LogTable(final JTextArea detailTextArea) {

      init();

      _detailTextArea = detailTextArea;

      setModel(new FilteredLogTableModel());

      final Enumeration columns = getColumnModel().getColumns();
      int i = 0;
      while (columns.hasMoreElements()) {
         final TableColumn col = (TableColumn) columns.nextElement();
         col.setCellRenderer(new LogTableRowRenderer());
         col.setPreferredWidth(_colWidths[i]);

         _tableColumns[i] = col;
         i++;
      }

      final ListSelectionModel rowSM = getSelectionModel();
      rowSM.addListSelectionListener(new LogTableListSelectionListener(this));

      //setAutoResizeMode(JTable.AUTO_RESIZE_ALL_COLUMNS);
   }
 
Example 3
Source File: DisplayTable.java    From netbeans with Apache License 2.0 6 votes vote down vote up
private void setMyModel(Object[][] data, boolean canEdit) {
 
DisplayTableModel model = new DisplayTableModel(data, 
						canEdit, 
						editable > 2); 
if(sortable) {
    DisplayTableSorter sorter = new DisplayTableSorter(model); 
    setModel(sorter);
}
else {
    setModel(model);
}

// PENDING - the column size does not shrink the way it should 
TableColumnModel tcm = getColumnModel();
if (tcm.getColumnCount() > 0) {
    TableColumn column = tcm.getColumn(0);     
    column.setPreferredWidth(10);
    tcm.getColumn(2).setMaxWidth(5);
}
   }
 
Example 4
Source File: JVector.java    From knopflerfish.org with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
void setColWidth(int col, int w)
{
  final TableModel model = table.getModel();
  final TableCellRenderer headerRenderer =
    table.getTableHeader().getDefaultRenderer();

  if (col < model.getColumnCount()) {
    final TableColumn column = table.getColumnModel().getColumn(col);

    final Component headerComp =
      headerRenderer.getTableCellRendererComponent(null,
                                                   column.getHeaderValue(),
                                                   false, false, 0, 0);
    final int headerWidth = headerComp.getPreferredSize().width;

    w = Math.max(headerWidth, w);

    // totalWidth += w;

    column.setMinWidth(10);
    column.setMaxWidth(300);

    column.setPreferredWidth(w);
  }
}
 
Example 5
Source File: MainPanel.java    From java-swing-tips with MIT License 6 votes vote down vote up
@Override public void updateUI() {
  // [JDK-6788475] Changing to Nimbus LAF and back doesn't reset look and feel of JTable completely - Java Bug System
  // https://bugs.openjdk.java.net/browse/JDK-6788475
  // XXX: set dummy ColorUIResource
  setSelectionForeground(new ColorUIResource(Color.RED));
  setSelectionBackground(new ColorUIResource(Color.RED));
  setDefaultRenderer(Object.class, null);
  super.updateUI();

  putClientProperty("Table.isFileList", Boolean.TRUE);
  setCellSelectionEnabled(true);
  setIntercellSpacing(new Dimension());
  setShowGrid(false);
  setAutoCreateRowSorter(true);
  setFillsViewportHeight(true);

  TableCellRenderer r = new DefaultTableCellRenderer();
  setDefaultRenderer(Object.class, (table, value, isSelected, hasFocus, row, column) ->
      r.getTableCellRendererComponent(table, value, false, false, row, column));

  TableColumn col = getColumnModel().getColumn(0);
  col.setCellRenderer(new FileNameRenderer(this));
  col.setPreferredWidth(200);
  col = getColumnModel().getColumn(1);
  col.setPreferredWidth(300);
}
 
Example 6
Source File: LogTable.java    From cacheonix-core with GNU Lesser General Public License v2.1 6 votes vote down vote up
public LogTable(JTextArea detailTextArea) {
  super();

  init();

  _detailTextArea = detailTextArea;

  setModel(new FilteredLogTableModel());

  Enumeration columns = getColumnModel().getColumns();
  int i = 0;
  while (columns.hasMoreElements()) {
    TableColumn col = (TableColumn) columns.nextElement();
    col.setCellRenderer(new LogTableRowRenderer());
    col.setPreferredWidth(_colWidths[i]);

    _tableColumns[i] = col;
    i++;
  }

  ListSelectionModel rowSM = getSelectionModel();
  rowSM.addListSelectionListener(new LogTableListSelectionListener(this));

  //setAutoResizeMode(JTable.AUTO_RESIZE_ALL_COLUMNS);
}
 
Example 7
Source File: DateTimeBrowser.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
void setViewColumnsWidth(JTable jt) {
    /*
     * Resize column 0, 1
     */
    TableColumnModel colmodel = jt.getColumnModel();
    TableColumn col0 = colmodel.getColumn(0);
    col0.setPreferredWidth(200);
    TableColumn col1 = colmodel.getColumn(1);
    col1.setPreferredWidth(200);
    return;
}
 
Example 8
Source File: UnitTable.java    From netbeans with Apache License 2.0 5 votes vote down vote up
void setColumnsSize () {
    int columnCount = model.getColumnCount ();
    for (int i = 0; i < columnCount; i++) {
        TableColumn activeColumn = getColumnModel ().getColumn (i);
        activeColumn.setPreferredWidth (this.model.getPreferredWidth (getTableHeader (), i));
    }
}
 
Example 9
Source File: CustomizerSources.java    From netbeans with Apache License 2.0 5 votes vote down vote up
public void componentResized(ComponentEvent evt){
    double pw = table.getParent().getParent().getSize().getWidth();
    table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
    TableColumn column = table.getColumnModel().getColumn(0);
    column.setWidth( ((int)pw/2) - 1 );
    column.setPreferredWidth( ((int)pw/2) - 1 );
    column = table.getColumnModel().getColumn(1);
    column.setWidth( ((int)pw/2) - 1 );
    column.setPreferredWidth( ((int)pw/2) - 1 );
}
 
Example 10
Source File: MdbPropertiesPanelVisual.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private void updateTableUI() {
    TableColumnModel columnModel = propertiesTable.getColumnModel();
    columnModel.getColumn(0).setPreferredWidth(180);
    TableColumn columnTwo = columnModel.getColumn(1);
    columnTwo.setPreferredWidth(280);
    columnTwo.setCellEditor(createCellEditor(getActivationConfigProperties()));
    columnTwo.setCellRenderer(new ACPCellRenderer(getActivationConfigProperties()));
    propertiesTable.setSelectionModel(new NullSelectionModel());
}
 
Example 11
Source File: KeyBindingsPanel.java    From ghidra with Apache License 2.0 5 votes vote down vote up
private void createActionMap() {

		String longestName = "";

		actionsByFullName = KeyBindingUtils.getAllActionsByFullName(tool);
		Set<Entry<String, List<DockingActionIf>>> entries = actionsByFullName.entrySet();
		for (Entry<String, List<DockingActionIf>> entry : entries) {

			// pick one action, they are all conceptually the same
			List<DockingActionIf> actions = entry.getValue();
			DockingActionIf action = actions.get(0);
			tableActions.add(action);

			String actionName = entry.getKey();
			KeyStroke ks = options.getKeyStroke(actionName, null);
			keyStrokesByFullName.put(actionName, ks);
			addToKeyMap(ks, actionName);
			originalValues.put(actionName, ks);

			String shortName = action.getName();
			if (shortName.length() > longestName.length()) {
				longestName = shortName;
			}
		}

		Font f = actionTable.getFont();
		FontMetrics fm = actionTable.getFontMetrics(f);
		int maxWidth = 0;
		for (int i = 0; i < longestName.length(); i++) {
			char c = longestName.charAt(i);
			maxWidth += fm.charWidth(c);
		}
		TableColumn col = actionTable.getColumnModel().getColumn(ACTION_NAME);
		col.setPreferredWidth(maxWidth);
		tableModel.fireTableDataChanged();
	}
 
Example 12
Source File: PluginsPanel.java    From desktop with GNU General Public License v3.0 5 votes vote down vote up
private void initTable() {
    // Content Model & Renderer
    tblPlugins.setModel(new PluginsTableModel());
    //tblFolders.getC

    // Columns
    tblPlugins.setAutoResizeMode(JTable.AUTO_RESIZE_LAST_COLUMN);

    TableColumn colActive = tblPlugins.getColumnModel().getColumn(PluginsTableModel.COLUMN_INDEX_ACTIVE);
    colActive.setPreferredWidth(50);
    colActive.setMaxWidth(50);
    colActive.setResizable(false);

    TableColumn colRemote = tblPlugins.getColumnModel().getColumn(PluginsTableModel.COLUMN_INDEX_NAME);
    colRemote.setPreferredWidth(210);

    TableColumn colLocal = tblPlugins.getColumnModel().getColumn(PluginsTableModel.COLUMN_INDEX_VERSION);
    colLocal.setPreferredWidth(120);

    // Other stuff
    tblPlugins.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
    tblPlugins.setShowHorizontalLines(false);
    tblPlugins.setShowVerticalLines(false);
    tblPlugins.setBorder(BorderFactory.createEmptyBorder());

    // Listeners
    tblPlugins.getSelectionModel().addListSelectionListener(new ListSelectionListener() {

        @Override
        public void valueChanged(ListSelectionEvent e) {
            btnDelete.setEnabled(e.getFirstIndex() >= 0);
        }
    });
}
 
Example 13
Source File: Util.java    From shakey with Apache License 2.0 5 votes vote down vote up
/** Resize all columns in the table to fit widest row including header. */ 
public static void resizeColumns( JTable table) {
	if (table.getGraphics() == null) {
		return;
	}
	
	DefaultTableCellRenderer renderer = new DefaultTableCellRenderer();
	FontMetrics fm = table.getFontMetrics( renderer.getFont() );

	TableColumnModel mod = table.getColumnModel();
	for (int iCol = 0; iCol < mod.getColumnCount(); iCol++) {
		TableColumn col = mod.getColumn( iCol);
		
		int max = col.getPreferredWidth() - BUF;
		
		String header = table.getModel().getColumnName( iCol);
		if (header != null) {
			max = Math.max( max, fm.stringWidth( header) );
		}
		
		for (int iRow = 0; iRow < table.getModel().getRowCount(); iRow++) {
			Object obj = table.getModel().getValueAt(iRow, iCol);
			String str = obj == null ? "" : obj.toString();
			max = Math.max( max, fm.stringWidth( str) );
		}

		col.setPreferredWidth( max + BUF);
		col.setMaxWidth( MAX);
	}
	table.revalidate();
	table.repaint();
}
 
Example 14
Source File: TableUtil.java    From consulo with Apache License 2.0 5 votes vote down vote up
public static void setupCheckboxColumn(@Nonnull TableColumn column) {
  int checkboxWidth = new JCheckBox().getPreferredSize().width;
  column.setResizable(false);
  column.setPreferredWidth(checkboxWidth);
  column.setMaxWidth(checkboxWidth);
  column.setMinWidth(checkboxWidth);
}
 
Example 15
Source File: ExampleSourceConfigurationWizardDataTable.java    From rapidminer-studio with GNU Affero General Public License v3.0 5 votes vote down vote up
public void update() {
	((AbstractTableModel) getModel()).fireTableStructureChanged();
	TableColumnModel columnModel = getColumnModel();
	for (int i = 0; i < columnModel.getColumnCount(); i++) {
		TableColumn tableColumn = columnModel.getColumn(i);
		tableColumn.setPreferredWidth(120);
	}
}
 
Example 16
Source File: TableColumnsGeometryPersisterImpl.java    From pgptool with GNU General Public License v3.0 5 votes vote down vote up
@Override
public boolean restoreColumnsConfig() {
	Preconditions.checkState(table != null, "instance was detached, can't do much after that");
	ArrayList<Pair<Integer, Integer>> cc = configPairs.find(keyId, null);
	if (cc == null) {
		return false;
	}

	TableColumnModel cm = table.getColumnModel();

	for (int i = 0; i < cm.getColumnCount(); i++) {
		int desiredColumnModelIndex = cc.get(i).getLeft();
		if (cm.getColumn(i).getModelIndex() == desiredColumnModelIndex) {
			continue;
		}

		int desiredColumnPhysicalindex = getColumnPhysicalindexByModelIndex(cm, desiredColumnModelIndex);
		cm.moveColumn(desiredColumnPhysicalindex, i);
	}

	// xet sizes
	for (int i = 0; i < cm.getColumnCount(); i++) {
		TableColumn c = cm.getColumn(i);
		c.setPreferredWidth(cc.get(i).getRight());
	}

	prevColumnsConfig = cc;
	return true;
}
 
Example 17
Source File: ParallelSimDialog.java    From workcraft with MIT License 5 votes vote down vote up
private void createEventInfoPanel() {
    eventInfoPanel = new JPanel();

    String[] colNames = {"Name", "Label"};

    JTable table = new JTable(createData(), colNames);
    table.setEnabled(false);
    TableColumn firsetColumn = table.getColumnModel().getColumn(0);
    firsetColumn.setPreferredWidth(12);

    eventInfoPanel.setLayout(new BoxLayout(eventInfoPanel, BoxLayout.Y_AXIS));
    eventInfoPanel.setBorder(GuiUtils.getTitledBorder("Parallel execution:"));
    eventInfoPanel.add(table);
}
 
Example 18
Source File: QueryBuilderInputTable.java    From netbeans with Apache License 2.0 4 votes vote down vote up
public QueryBuilderInputTable(QueryBuilder queryBuilder) {

        super();

	Log.getLogger().entering("QueryBuilderInputTable", "constructor"); // NOI18N

        _queryBuilder = queryBuilder;

        QueryBuilderInputTableModel queryBuilderInputTableModel = new QueryBuilderInputTableModel();

        super.setModel( queryBuilderInputTableModel );

        TableColumn column = this.getColumnModel().getColumn(Column_COLUMN);
        column.setPreferredWidth(Column_COLUMN_WIDTH);

        column = this.getColumnModel().getColumn(Alias_COLUMN);
        column.setPreferredWidth(Alias_COLUMN_WIDTH);
        column.setCellEditor(new FocusCellEditor(new JTextField()));

        column = this.getColumnModel().getColumn(Table_COLUMN);
        column.setPreferredWidth(Table_COLUMN_WIDTH);

        column = this.getColumnModel().getColumn(SortType_COLUMN);
        column.setPreferredWidth(SortType_COLUMN_WIDTH);

        column = this.getColumnModel().getColumn(SortOrder_COLUMN);
        column.setPreferredWidth(SortOrder_COLUMN_WIDTH);

        column = this.getColumnModel().getColumn(Criteria_COLUMN);
        column.setPreferredWidth(Criteria_COLUMN_WIDTH);
        column.setCellEditor(new FocusCellEditor(new JTextField()));

        column = this.getColumnModel().getColumn(CriteriaOrder_COLUMN);
        column.setPreferredWidth(CriteriaOrder_COLUMN_WIDTH);

        this.getColumnModel().getColumn(0).setCellEditor(
            new FocusCellEditor(new JTextField()));

        final Object[] sortTypeItems = {
            "", 
            NbBundle.getMessage(QueryBuilderInputTable.class, "ASCENDING"), // NOI18N
            NbBundle.getMessage(QueryBuilderInputTable.class, "DESCENDING") // NOI18N
        }; 
        TableColumn sortTypeColumn = this.getColumnModel().getColumn(SortType_COLUMN);
        JComboBox sortTypeComboBox = new JComboBox(sortTypeItems);
        sortTypeColumn.setCellEditor(new DefaultCellEditor(sortTypeComboBox));
        sortTypeComboBox.addItemListener(this);

        final Object[] sortOrderItems = {""};       // NOI18N
        TableColumn sortOrderColumn = this.getColumnModel().getColumn(SortOrder_COLUMN);
        _sortOrderComboBox = new JComboBox(sortOrderItems);
        sortOrderColumn.setCellEditor(new DefaultCellEditor(_sortOrderComboBox));
        _sortOrderComboBox.addItemListener(this);

        final Object[] criteriaOrderItems = {""};       // NOI18N
        TableColumn criteriaOrderColumn = this.getColumnModel().getColumn(CriteriaOrder_COLUMN);
        _criteriaOrderComboBox = new JComboBox(criteriaOrderItems);
        criteriaOrderColumn.setCellEditor(new DefaultCellEditor(_criteriaOrderComboBox));
//        _criteriaOrderComboBox.addItemListener(this);

        this.setAutoResizeMode (JTable.AUTO_RESIZE_OFF);
        _inputTablePopup = createInputTablePopup();
        MouseListener inputTablePopupListener = new InputTablePopupListener();
        super.addMouseListener(inputTablePopupListener);
        this.setMinimumSize(new Dimension (200, 200) );
        this.setBackground(Color.white);
        this.getTableHeader().setReorderingAllowed (false);

        addKeyListener(this);

//        this.getModel().addTableModelListener(this);

// Listen for checkbox selections in output column; handled by tableChange event instead
//          TableColumn outputColumn = this.getColumnModel().getColumn(Output_COLUMN);
//          JCheckBox outputCheckBox = new JCheckBox();
//          outputColumn.setCellEditor(new DefaultCellEditor(outputCheckBox));
//          outputCheckBox.addItemListener(this);
    }
 
Example 19
Source File: Table.java    From netbeans with Apache License 2.0 4 votes vote down vote up
private void init() {
    setOpaque( false );
    getSelectionModel().clearSelection();
    getSelectionModel().setAnchorSelectionIndex(-1);
    getSelectionModel().setLeadSelectionIndex(-1);
    setAutoscrolls( false );
    setShowHorizontalLines(false);
    setShowVerticalLines( false);
    setAutoResizeMode( JTable.AUTO_RESIZE_OFF );
    setTableHeader( null );
    // Calc row height here so that TableModel can adjust number of columns.
    calcRowHeight(getOffscreenGraphics());

    //mouse click into the table performs the switching
    addMouseListener( new MouseAdapter() {
        @Override
        public void mousePressed( MouseEvent e ) {
            int row = rowAtPoint( e.getPoint() );
            int col = columnAtPoint( e.getPoint() );
            if( row >= 0 && col >= 0 ) {
                if( select( row, col ) ) {
                    performSwitching();
                }
            }
        }
    });

    //icon for top-level items with sub-items
    rightArrowLabel.setIcon( new ArrowIcon() );
    rightArrowLabel.setIconTextGap( 2 );
    rightArrowLabel.setHorizontalTextPosition( JLabel.LEFT );
    topItemPanel.setLayout( new BorderLayout(5, 0) );
    topItemPanel.add( rightArrowLabel, BorderLayout.EAST );
    topItemPanel.getAccessibleContext().setAccessibleDescription( NbBundle.getMessage(Table.class, "ACD_OTHER_EDITORS") );
    topItemPanel.setBorder( BorderFactory.createEmptyBorder( 0, 0, 0, 2) );

    //adjust column widths to accomodate the widest item in each column
    for( int col=0; col<getColumnCount(); col++ ) {
        if( getSwitcherModel().isTopItemColumn( col ) )
            adjustColumnWidths( col );
    }

    //include the width of vertical scrollbar if there are too many rows
    int maxRowCount = getSwitcherModel().getMaxRowCount();
    if( maxRowCount > MAX_VISIBLE_ROWS && getRowCount() <= MAX_VISIBLE_ROWS ) {
        JScrollPane scroll = new JScrollPane();
        scroll.setVerticalScrollBarPolicy( JScrollPane.VERTICAL_SCROLLBAR_ALWAYS );
        int scrollWidth = scroll.getVerticalScrollBar().getPreferredSize().width;
        TableColumn tc = getColumnModel().getColumn( getColumnCount()-1 );
        tc.setMaxWidth( tc.getMaxWidth() + scrollWidth );
        tc.setPreferredWidth( tc.getPreferredWidth() + scrollWidth );
        tc.setWidth( tc.getWidth() + scrollWidth );
    }
}
 
Example 20
Source File: AnimPlayList.java    From open-ig with 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;
  }