Java Code Examples for javax.swing.table.TableModel#getColumnCount()

The following examples show how to use javax.swing.table.TableModel#getColumnCount() . 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: TableExpandableItemsHandler.java    From consulo with Apache License 2.0 6 votes vote down vote up
public Pair<Component, Rectangle> getCellRendererAndBounds(TableCell key) {
  Rectangle cellRect = getCellRect(key);

  int modelColumnIndex = myComponent.convertColumnIndexToModel(key.column);
  final int modelRowIndex = myComponent.convertRowIndexToModel(key.row);
  TableModel model = myComponent.getModel();
  if (key.row < 0 || key.row >= model.getRowCount() || key.column < 0 || key.column >= model.getColumnCount()) {
    return null;
  }

  Component renderer = myComponent
    .getCellRenderer(key.row, key.column)
    .getTableCellRendererComponent(myComponent,
                                   model.getValueAt(modelRowIndex, modelColumnIndex),
                                   myComponent.getSelectionModel().isSelectedIndex(key.row),
                                   myComponent.hasFocus(),
                                   key.row, key.column);
  cellRect.width = renderer.getPreferredSize().width;

  return Pair.create(renderer, cellRect);
}
 
Example 2
Source File: AbstractDemoFrame.java    From pentaho-reporting with GNU Lesser General Public License v2.1 6 votes vote down vote up
protected JComponent createDefaultTable(final TableModel data)
{
  final JTable table = new JTable(data);
  table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);

  for (int columnIndex = 0; columnIndex < data
      .getColumnCount(); columnIndex++)
  {
    final TableColumn column = table.getColumnModel().getColumn(columnIndex);
    column.setMinWidth(50);
    final Class c = data.getColumnClass(columnIndex);
    if (c.equals(Number.class))
    {
      column.setCellRenderer(new NumberCellRenderer());
    }
  }

  return new JScrollPane
      (table, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,
          JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
}
 
Example 3
Source File: ListDetailPane.java    From ApkToolPlus with Apache License 2.0 6 votes vote down vote up
public void show(TreePath treePath) {
    CodeGenerator cg = new CodeGenerator();
    currentMethodIndex = cg.getMethodIndex(treePath);
    
    TableModel tableModel = getTableModel(treePath);
 
      table.setModel(tableModel);
   

   createTableColumnModel(table, tableModel);
    ((JLabel) table.getDefaultRenderer(Number.class))
            .setVerticalAlignment(JLabel.TOP);
    ((JLabel) table.getDefaultRenderer(String.class))
            .setVerticalAlignment(JLabel.TOP);
    table.setDefaultRenderer(Link.class, new LinkRenderer());
    if (tableModel.getColumnCount() > 6) {
        ButtonColumn bc = new ButtonColumn(table, 6);
     }
    
}
 
Example 4
Source File: ComputedParameterValues.java    From pentaho-reporting with GNU Lesser General Public License v2.1 6 votes vote down vote up
private TableDataRow( final TableModel data, final String valueColumn ) {
  if ( data == null ) {
    throw new NullPointerException();
  }
  this.data = data;
  this.columnNames = new String[data.getColumnCount()];
  this.nameindex = new HashMap<String, Integer>();
  this.valueColumn = valueColumn;
  for ( int i = 0; i < columnNames.length; i++ ) {
    final String name = data.getColumnName( i );
    columnNames[i] = name;
    nameindex.put( name, IntegerCache.getInteger( i ) );
  }

  this.currentRow = -1;
}
 
Example 5
Source File: AddDataFactoryAction.java    From pentaho-reporting with GNU Lesser General Public License v2.1 6 votes vote down vote up
private static boolean isLegacyDefaultDataFactory( final DataFactory dataFactory ) {
  final String[] queryNames = dataFactory.getQueryNames();
  if ( queryNames.length == 0 ) {
    return true;
  }

  if ( queryNames.length != 1 ) {
    return false;
  }
  if ( "default".equals( queryNames[ 0 ] ) ) {
    try {
      // check for legacy-built-in defaults and selectively ignore them ..
      final TableModel tableModel = dataFactory.queryData( "default", null );
      if ( tableModel.getRowCount() == 0 && tableModel.getColumnCount() == 0 ) {
        return true;
      }
    } catch ( final Exception e ) {
      return false;
    }
  }
  return false;
}
 
Example 6
Source File: CreateTableDialog.java    From netbeans with Apache License 2.0 5 votes vote down vote up
public DataTable(TableModel model) {
    super(model);
    setSurrendersFocusOnKeystroke(true);
    TableColumnModel cmodel = getColumnModel();
    int i;
    int ccount = model.getColumnCount();
    int columnWidth;
    int preferredWidth;
    String columnName;
    int width = 0;
    for (i = 0; i < ccount; i++) {
        TableColumn col = cmodel.getColumn(i);
        Map cmap = ColumnItem.getColumnProperty(i);
        col.setIdentifier(cmap.get("name")); //NOI18N
        columnName = NbBundle.getMessage (CreateTableDialog.class, "CreateTable_" + i); //NOI18N
        columnWidth = (new Double(getFontMetrics(getFont()).getStringBounds(columnName, getGraphics()).getWidth())).intValue() + 20;
        if (cmap.containsKey("width")) { // NOI18N
            if (((Integer)cmap.get("width")).intValue() < columnWidth)
                col.setPreferredWidth(columnWidth);
            else
                col.setPreferredWidth(((Integer)cmap.get("width")).intValue()); // NOI18N
            preferredWidth = col.getPreferredWidth();
        }
        if (cmap.containsKey("minwidth")) // NOI18N
            if (((Integer)cmap.get("minwidth")).intValue() < columnWidth)
                col.setMinWidth(columnWidth);
            else
                col.setMinWidth(((Integer)cmap.get("minwidth")).intValue()); // NOI18N
        //				if (cmap.containsKey("alignment")) {}
        //				if (cmap.containsKey("tip")) ((JComponent)col.getCellRenderer()).setToolTipText((String)cmap.get("tip"));
        if (i < 7) { // the first 7 columns should be visible
            width += col.getPreferredWidth();
        }
    }
    width = Math.min(Math.max(width, 380), Toolkit.getDefaultToolkit().getScreenSize().width - 100);
    setPreferredScrollableViewportSize(new Dimension(width, 150));
}
 
Example 7
Source File: SwingExtensions.java    From groovy with Apache License 2.0 5 votes vote down vote up
/**
 * Support the subscript operator for TableModel.
 *
 * @param self  a TableModel
 * @param index the index of the row to get
 * @return the row at the given index
 * @since 1.6.4
 */
public static Object[] getAt(TableModel self, int index) {
    int cols = self.getColumnCount();
    Object[] rowData = new Object[cols];
    for (int col = 0; col < cols; col++) {
        rowData[col] = self.getValueAt(index, col);
    }
    return rowData;
}
 
Example 8
Source File: ProfilerTable.java    From netbeans with Apache License 2.0 5 votes vote down vote up
public void createDefaultColumnsFromModel() {
    TableModel m = getModel();
    if (m != null) {
        // Remove any current columns
        ProfilerColumnModel cm = _getColumnModel();
        while (cm.getColumnCount() > 0)
            cm.removeColumn(cm.getColumn(0));

        // Create new columns from the data model info
        for (int i = 0; i < m.getColumnCount(); i++)
            addColumn(cm.createTableColumn(i));
    }
}
 
Example 9
Source File: TableModelComparator.java    From openjdk-8 with GNU General Public License v2.0 5 votes vote down vote up
public TableModelComparator(TableModel model) {
    this.model = model;

    // XXX - Should actually listen for column changes and resize
    columns = new int[model.getColumnCount()];
    columns[0] = -1;
}
 
Example 10
Source File: ExtendedJTable.java    From rapidminer-studio with GNU Affero General Public License v3.0 5 votes vote down vote up
@Override
public void setModel(final TableModel model) {
	boolean shouldSort = this.sortable && checkIfSortable(model);

	if (shouldSort) {
		this.tableSorter = new ExtendedJTableSorterModel(model);
		this.tableSorter.setTableHeader(getTableHeader());
		super.setModel(this.tableSorter);
	} else {
		super.setModel(model);
		this.tableSorter = null;
	}

	originalOrder = new String[model.getColumnCount()];
	for (int c = 0; c < model.getColumnCount(); c++) {
		originalOrder[c] = model.getColumnName(c);
	}

	// initializing arrays for cell renderer settings
	cutOnLineBreaks = new boolean[model.getColumnCount()];
	maximalTextLengths = new int[model.getColumnCount()];
	Arrays.fill(maximalTextLengths, Integer.MAX_VALUE);

	model.addTableModelListener(new TableModelListener() {

		@Override
		public void tableChanged(final TableModelEvent e) {
			int oldLength = cutOnLineBreaks.length;
			if (oldLength != model.getColumnCount()) {
				cutOnLineBreaks = Arrays.copyOf(cutOnLineBreaks, model.getColumnCount());
				maximalTextLengths = Arrays.copyOf(maximalTextLengths, model.getColumnCount());
				if (oldLength < cutOnLineBreaks.length) {
					Arrays.fill(cutOnLineBreaks, oldLength, cutOnLineBreaks.length, false);
					Arrays.fill(maximalTextLengths, oldLength, cutOnLineBreaks.length, Integer.MAX_VALUE);
				}
			}
		}
	});
}
 
Example 11
Source File: MainPanel.java    From java-swing-tips with MIT License 5 votes vote down vote up
private static JTable makeTable(TableModel model) {
  return new JTable(model) {
    @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));
      super.updateUI();
      updateRenderer();
      JCheckBox checkBox = makeBooleanEditor(this);
      setDefaultEditor(Boolean.class, new DefaultCellEditor(checkBox));
    }

    private void updateRenderer() {
      TableModel m = getModel();
      for (int i = 0; i < m.getColumnCount(); i++) {
        TableCellRenderer r = getDefaultRenderer(m.getColumnClass(i));
        if (r instanceof Component) {
          SwingUtilities.updateComponentTreeUI((Component) r);
        }
      }
    }

    @Override public Component prepareEditor(TableCellEditor editor, int row, int column) {
      Component c = super.prepareEditor(editor, row, column);
      if (c instanceof JCheckBox) {
        JCheckBox b = (JCheckBox) c;
        b.setBackground(getSelectionBackground());
        b.setBorderPainted(true);
      }
      return c;
    }
  };
}
 
Example 12
Source File: JTableCellJavaElement.java    From marathonv5 with Apache License 2.0 5 votes vote down vote up
private void validateRowCol() {
    JTable table = (JTable) parent.getComponent();
    try {
        int row = table.convertRowIndexToModel(viewRow);
        int col = table.convertColumnIndexToModel(viewCol);
        TableModel model = table.getModel();
        if (row >= 0 && row < model.getRowCount() && col >= 0 && col < model.getColumnCount()) {
            return;
        }
    } catch (IndexOutOfBoundsException e) {
    }
    throw new NoSuchElementException("Invalid row/col for JTable: (" + viewRow + ", " + viewCol + ")", null);
}
 
Example 13
Source File: Util.java    From hortonmachine with GNU General Public License v3.0 5 votes vote down vote up
static int findColumn(TableModel model, String name) {
    for (int i = 0; i<model.getColumnCount(); i++) {
        if (name.equals(model.getColumnName(i))) {
            return i;
        }
    }
    return -1;
}
 
Example 14
Source File: TableModelComparator.java    From jdk8u60 with GNU General Public License v2.0 5 votes vote down vote up
public TableModelComparator(TableModel model) {
    this.model = model;

    // XXX - Should actually listen for column changes and resize
    columns = new int[model.getColumnCount()];
    columns[0] = -1;
}
 
Example 15
Source File: CachableTableModel.java    From pentaho-reporting with GNU Lesser General Public License v2.1 5 votes vote down vote up
protected void initDefaultMetaData( final TableModel model ) {
  for ( int i = 0; i < model.getColumnCount(); i++ ) {
    final String columnName = model.getColumnName( i );
    final Class columnType = model.getColumnClass( i );
    final DefaultDataAttributes attributes = new DefaultDataAttributes();
    attributes.setMetaAttribute( MetaAttributeNames.Core.NAMESPACE, MetaAttributeNames.Core.NAME,
                                 DefaultConceptQueryMapper.INSTANCE, columnName );
    attributes.setMetaAttribute( MetaAttributeNames.Core.NAMESPACE, MetaAttributeNames.Core.TYPE,
                                 DefaultConceptQueryMapper.INSTANCE, columnType );
    columnAttributes.add( attributes );
  }
  tableAttributes = EmptyDataAttributes.INSTANCE;
}
 
Example 16
Source File: TableModelInfo.java    From pentaho-reporting with GNU Lesser General Public License v2.1 5 votes vote down vote up
public static void printTableCellAttributes( final TableModel mod, final PrintStream out ) {
  if ( mod instanceof MetaTableModel == false ) {
    out.println( "TableModel has no meta-data." );
    return;
  }

  final MetaTableModel metaTableModel = (MetaTableModel) mod;
  if ( metaTableModel.isCellDataAttributesSupported() == false ) {
    out.println( "TableModel has no cell-meta-data." );
    return;
  }

  final DataAttributeContext attributeContext =
      new DefaultDataAttributeContext( new GenericOutputProcessorMetaData(), Locale.US );

  out.println( "Tablemodel contains " + mod.getRowCount() + " rows." ); //$NON-NLS-1$ //$NON-NLS-2$
  out.println( "Checking the attributes inside" ); //$NON-NLS-1$
  for ( int rows = 0; rows < mod.getRowCount(); rows++ ) {
    for ( int i = 0; i < mod.getColumnCount(); i++ ) {
      final DataAttributes cellAttributes = metaTableModel.getCellDataAttributes( rows, i );
      final String[] columnAttributeDomains = cellAttributes.getMetaAttributeDomains();
      Arrays.sort( columnAttributeDomains );
      for ( int attrDomainIdx = 0; attrDomainIdx < columnAttributeDomains.length; attrDomainIdx++ ) {
        final String colAttrDomain = columnAttributeDomains[attrDomainIdx];
        final String[] attributeNames = cellAttributes.getMetaAttributeNames( colAttrDomain );
        Arrays.sort( attributeNames );
        for ( int j = 0; j < attributeNames.length; j++ ) {
          final String attributeName = attributeNames[j];
          final Object o =
              cellAttributes.getMetaAttribute( colAttrDomain, attributeName, Object.class, attributeContext );

          out.println( "CellAttribute(" + rows + ", " + i + ") [" + colAttrDomain + ':' + attributeName + "]="
              + format( o ) );
        }
      }
    }
  }
}
 
Example 17
Source File: TableModelComparator.java    From openjdk-8-source with GNU General Public License v2.0 5 votes vote down vote up
public TableModelComparator(TableModel model) {
    this.model = model;

    // XXX - Should actually listen for column changes and resize
    columns = new int[model.getColumnCount()];
    columns[0] = -1;
}
 
Example 18
Source File: CachableTableModel.java    From pentaho-reporting with GNU Lesser General Public License v2.1 5 votes vote down vote up
protected void initData( final TableModel model ) {
  cellValues =
    new GenericObjectTable<Object>( Math.max( 1, model.getRowCount() ), Math.max( 1, model.getColumnCount() ) );
  for ( int row = 0; row < model.getRowCount(); row += 1 ) {
    for ( int columns = 0; columns < model.getColumnCount(); columns += 1 ) {
      cellValues.setObject( row, columns, model.getValueAt( row, columns ) );
    }
  }
}
 
Example 19
Source File: StructureTable.java    From netcdf-java with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
private void export() {
  String filename = fileChooser.chooseFilename();
  if (filename == null)
    return;
  try {
    PrintWriter pw = new PrintWriter(new File(filename), StandardCharsets.UTF_8.name());

    TableModel model = jtable.getModel();
    for (int col = 0; col < model.getColumnCount(); col++) {
      if (col > 0)
        pw.print(",");
      pw.print(model.getColumnName(col));
    }
    pw.println();

    for (int row = 0; row < model.getRowCount(); row++) {
      for (int col = 0; col < model.getColumnCount(); col++) {
        if (col > 0)
          pw.print(",");
        pw.print(model.getValueAt(row, col));
      }
      pw.println();
    }
    pw.close();
    JOptionPane.showMessageDialog(this, "File successfully written");
  } catch (IOException ioe) {
    JOptionPane.showMessageDialog(this, "ERROR: " + ioe.getMessage());
    ioe.printStackTrace();
  }

}
 
Example 20
Source File: TableProperties.java    From mars-sim with GNU General Public License v3.0 4 votes vote down vote up
/**
     * Constructs a MonitorPropsDialog class.
     * @param title The name of the specified model
     * @param table the table to configure
     * @param desktop the main desktop.
     */
    public TableProperties(String title, JTable table,
                              MainDesktopPane desktop) {

        // Use JInternalFrame constructor
        super(title + " Properties", false, true);

        // Initialize data members
        this.model = table.getColumnModel();

        // Prepare content pane
        JPanel mainPane = new JPanel();
        mainPane.setLayout(new BorderLayout());
        mainPane.setBorder(MainDesktopPane.newEmptyBorder());
        setContentPane(mainPane);

        // Create column pane
        JPanel columnPane = new JPanel(new GridLayout(0, 1));
        columnPane.setBorder(new MarsPanelBorder());

        // Create a checkbox for each column in the model
        TableModel dataModel = table.getModel();
        for(int i = 0; i < dataModel.getColumnCount(); i++) {
            String name = dataModel.getColumnName(i);
            JCheckBox column = new JCheckBox(name);
            column.setSelected(false);

            column.addActionListener(
            	new ActionListener() {
                    public void actionPerformed(ActionEvent event) {
                        columnSelected(event);
                    }
                }
            );
            columnButtons.add(column);
            columnPane.add(column);
        }

        // Selected if column is visible
        Enumeration<?> en = model.getColumns();
        while(en.hasMoreElements()) {
            int selected = ((TableColumn)en.nextElement()).getModelIndex();
            JCheckBox columnButton = columnButtons.get(selected);
            columnButton.setSelected(true);
        }

        mainPane.add(columnPane, BorderLayout.CENTER);
        
        setDefaultCloseOperation(WindowConstants.HIDE_ON_CLOSE);
        
        pack();
        
        desktop.add(this);
        
//        // Add to its own tab pane
//        if (desktop.getMainScene() != null)
//        	desktop.add(this);
//        	//desktop.getMainScene().getDesktops().get(0).add(this);
//        else 
//        	desktop.add(this);
    }