private void fillColumns() { // remove all columns. this.tableColumns.removeAllElements(); FunctionalGroup g = controller.getSelectedFunctionalGroup(); if (g != null) { Collection<String> stages = g.getStageNames(); // Sort the stage names alphabetically ArrayList<String> stage_names = new ArrayList<String>(); for (String s : stages) { stage_names.add(s); } Collections.sort(stage_names); int modelIndex = 1; for (String s : stage_names) { TableColumn c = new TableColumn(modelIndex); c.setHeaderValue(s); this.addColumn(c); modelIndex++; } } }
public HexTable(ViewerHexTableModel model) { super(model); this.model = model; enableEvents(AWTEvent.KEY_EVENT_MASK); setAutoResizeMode(JTable.AUTO_RESIZE_OFF); setShowGrid(false); setIntercellSpacing(ZERO_DIMENSION); alternateCellColor = getBackground(); offsetColor = getForeground(); asciiDumpColor = getForeground(); setCellSelectionEnabled(true); setSelectionMode(ListSelectionModel.SINGLE_INTERVAL_SELECTION); setDefaultEditor(Object.class, cellEditor); setDefaultRenderer(Object.class, cellRenderer); for (int i = getColumnModel().getColumnCount() - 1; i >= 0; i--) { TableColumn col = getColumnModel().getColumn(i); col.setHeaderRenderer(headerRenderer); } getTableHeader().setReorderingAllowed(false); setShowGrid(false); setFont(getFont()); }
protected void makeGantt() { gantt_ = new GanttTable(makeTableModel(model_)); // System.out.println("model rows:"+model.getTableModel().getRowCount()); TableColumnModel columnModel = gantt_.getColumnModel(1); TableColumn column = columnModel.getColumn(0); // Enable drag and drop TableCellEditor editor = gantt_.getDefaultEditor(1, AbstractDrawingState.class); column.setCellEditor(editor); gantt_ .getDrawingContext() .put(ContextConstants.EDITING_AXIS, ContextResources.OTHER_PROPERTY, GanttTable.TIME_AXIS); gantt_ .getDrawingContext() .put( ContextConstants.EDITING_MODE, ContextResources.OTHER_PROPERTY, EditorDrawingModule.MOVE_RESIZE_EDITOR); // Display timeline at the top column.setHeaderValue(GanttEntryHelper.createCalendar()); gantt_.setTimeRange(start_.getTime(), end_.getTime()); gantt_.addMouseMotionListener(this); /* TODO: Disable row selection? JTable activityTable = gantt_.getTableComponent(1); activityTable.setRowSelectionAllowed(false); activityTable.setColumnSelectionAllowed(false); activityTable.setCellSelectionEnabled(false); */ }
/** Sets the default editors. */ protected void setDefaultEditors() { TableColumnModel model = TABLE.getColumnModel(); TableColumn tc = model.getColumn(LibraryPlaylistsTableDataLine.STARRED_IDX); tc.setCellEditor(new PlaylistItemStarEditor()); TABLE.addMouseMotionListener( new MouseMotionAdapter() { int currentCellColumn = -1; int currentCellRow = -1; @Override public void mouseMoved(MouseEvent e) { Point hit = e.getPoint(); int hitColumn = TABLE.columnAtPoint(hit); int hitRow = TABLE.rowAtPoint(hit); if (currentCellRow != hitRow || currentCellColumn != hitColumn) { if (TABLE.getCellRenderer(hitRow, hitColumn) instanceof PlaylistItemStarRenderer) { TABLE.editCellAt(hitRow, hitColumn); } currentCellColumn = hitColumn; currentCellRow = hitRow; } } }); tc = model.getColumn(LibraryPlaylistsTableDataLine.TITLE_IDX); tc.setCellEditor(new LibraryNameHolderEditor()); }
private static int preferredWidth(JTable table, int col) { TableColumn tableColumn = table.getColumnModel().getColumn(col); int width = (int) table .getTableHeader() .getDefaultRenderer() .getTableCellRendererComponent( table, tableColumn.getIdentifier(), false, false, -1, col) .getPreferredSize() .getWidth(); if (table.getRowCount() != 0) { int from = 0, to = 0; Rectangle rect = table.getVisibleRect(); from = table.rowAtPoint(rect.getLocation()); to = table.rowAtPoint(new Point((int) rect.getMaxX(), (int) rect.getMaxY())) + 1; for (int row = from; row < to; row++) { int preferedWidth = (int) table .getCellRenderer(row, col) .getTableCellRendererComponent( table, table.getValueAt(row, col), false, false, row, col) .getPreferredSize() .getWidth(); width = Math.max(width, preferedWidth); } } return width + table.getIntercellSpacing().width; }
private JTable getTableForCache(final CacheAccess<String, BufferedImageCacheEntry> cache) { final DefaultTableModel tableModel = new DefaultTableModel( new String[][] {{tr("Loading data"), tr("Please wait"), ""}}, new String[] {"Cache name", "Object Count", "Clear"}) { @Override public boolean isCellEditable(int row, int column) { return column == 2; } }; backgroundUpdateModel(cache, tableModel); final JTable ret = new JTable(tableModel); ButtonColumn buttonColumn = new ButtonColumn( new AbstractAction() { @Override public void actionPerformed(ActionEvent e) { int row = ret.convertRowIndexToModel(ret.getEditingRow()); tableModel.setValueAt("0", row, 1); cache.remove(ret.getValueAt(row, 0) + ":"); } }); TableColumn tableColumn = ret.getColumnModel().getColumn(2); tableColumn.setCellRenderer(buttonColumn); tableColumn.setCellEditor(buttonColumn); return ret; }
/** * Set column width in the JTable. * * @param width The width value. */ private static void setColumnWidth(int width) { TableColumn column = null; for (int i = 0; i < table.getColumnCount(); i++) { column = table.getColumnModel().getColumn(i); column.setPreferredWidth(width); } }
/** * @see org.tramper.gui.viewer.Body#displayDocument(org.tramper.doc.SimpleDocument, * org.tramper.doc.Target, int) */ public void displayDocument(SimpleDocument doc, Target target, int documentPart) { if (!(doc instanceof Feed)) { throw new RuntimeException(doc.getTitle() + " is not a Feed"); } document = (Feed) doc; this.target = target; feedTable.setModel(document); TableRowSorter<TableModel> tableSorter = new TableRowSorter<TableModel>(document); feedTable.setRowSorter(tableSorter); long indexModel = document.getIndex(); int indexView = feedTable.convertColumnIndexToView((int) indexModel); feedTable.changeSelection(indexView, 0, false, false); TableColumnModel model = feedTable.getColumnModel(); ListTableCellRenderer linkCellRenderer = new ListTableCellRenderer(); ListTableCellEditor linkCellEditor = new ListTableCellEditor(); TableColumn descColumn = model.getColumn(2); descColumn.setCellRenderer(linkCellRenderer); descColumn.setCellEditor(linkCellEditor); DateTableCellRenderer dateCellRenderer = new DateTableCellRenderer(); descColumn = model.getColumn(3); descColumn.setCellRenderer(dateCellRenderer); descColumn = model.getColumn(4); descColumn.setCellRenderer(dateCellRenderer); this.initColumnSizes(feedTable); }
public StatisticsTableColumnModel() { TableCellRenderer renderer = new StatisticsInfoRenderer(); TableColumn col = null; // column 0 - Paste col = new TableColumn(0); col.setHeaderValue(tr("Paste ...")); col.setResizable(true); col.setCellRenderer(renderer); addColumn(col); // column 1 - From col = new TableColumn(1); col.setHeaderValue(tr("From ...")); col.setResizable(true); col.setCellRenderer(renderer); addColumn(col); // column 2 - To col = new TableColumn(2); col.setHeaderValue(tr("To ...")); col.setResizable(true); col.setCellRenderer(renderer); addColumn(col); }
/** function that creates History table */ private void prepareUI() { for (int i = 0; i < 8; i++) { TableColumn column = tblTransactions.getColumnModel().getColumn(i); column.setHeaderRenderer(new PlainTableHeaderRenderer()); if (i == 1 || i == 2) { column.setWidth(250); column.setMinWidth(250); column.setPreferredWidth(250); } } tblTransactions.getTableHeader().setFont(Fonts.DEFAULT_HEADING_FONT); tblTransactions.getTableHeader().setForeground(Color.BLACK); tblTransactions.getTableHeader().setBackground(Colors.TABLE_HEADER_BG_COLOR); tblTransactions.getTableHeader().setOpaque(true); scrollPane.setColumnHeader( new JViewport() { @Override public Dimension getPreferredSize() { Dimension d = super.getPreferredSize(); d.height = 25; return d; } }); scrollPane.getHorizontalScrollBar().setUI(new XScrollbarUI()); scrollPane.getVerticalScrollBar().setUI(new XScrollbarUI()); tblTransactions.setRowHeight(25); tblTransactions.setDefaultRenderer(Object.class, new PlainTabelCellRenderer()); }
private void createArchiveTreeTable() { List l = ivcn.localFindAll(); treeTable = new JXTreeTable(studyList); treeTable.setHorizontalScrollEnabled(true); treeTable.setRootVisible(false); treeTable.setShowsRootHandles(true); treeTable.setShowHorizontalLines(true); treeTable.setShowVerticalLines(true); treeTable.setColumnMargin(1); treeTable.setColumnControlVisible(false); treeTable.setRolloverEnabled(true); treeTable.setScrollsOnExpand(true); treeTable.setTreeCellRenderer(new TreeTableCellRenderer()); treeTable.setAutoCreateColumnsFromModel(false); treeTable.setColumnFactory( new ColumnFactory() { public void configureColumnWidths(JXTable table, TableColumnExt columnExt) {} }); // treeTable.setAutoResizeMode(JTable.AUTO_RESIZE_SUBSEQUENT_COLUMNS); ListSelectionModel lsm = treeTable.getSelectionModel(); lsm.addListSelectionListener(this); CompoundHighlighter cp = new CompoundHighlighter(); cp.addHighlighter(new AlternateRowHighlighter(ROW_COLOR1, ROW_COLOR2, Color.white)); cp.addHighlighter(new HierarchicalColumnHighlighter(COL_COLOR1, Color.white)); treeTable.setHighlighters(cp); for (int i = 0; i < ARCHIVE_COLUMN_WIDTH.length; i++) { TableColumn column = treeTable.getColumnModel().getColumn(i); column.setPreferredWidth(ARCHIVE_COLUMN_WIDTH[i]); column.setHeaderRenderer(new TableHeaderRenderer(Color.black)); } }
private void jComboBox1ActionPerformed( java.awt.event.ActionEvent evt) { // GEN-FIRST:event_jComboBox1ActionPerformed // crset1.setConnectionSource(pConnDB); // crset1.execute("select description from st_stock_item where department = // '"+jComboBox1.getSelectedItem().toString()+"' order by description"); cmbox2 = new javax.swing.JComboBox(); cmbox3 = new javax.swing.JComboBox(); cmbox2.setModel( com.afrisoftech.lib.ComboBoxModel.ComboBoxModel( connectDB, "select description from st_stock_item where department = '" + jComboBox1.getSelectedItem().toString() + "' order by description")); javax.swing.table.TableColumn seditor = this.jTable1.getColumn("Item Description"); seditor.setCellEditor(new javax.swing.DefaultCellEditor(cmbox2)); cmbox2.addActionListener( new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { cmbox2ActionPerformed(evt); } }); // Add your handling code here: } // GEN-LAST:event_jComboBox1ActionPerformed
public void setMetricsResults(MetricDisplaySpecification displaySpecification, MetricsRun run) { final MetricCategory[] categories = MetricCategory.values(); for (final MetricCategory category : categories) { final JTable table = tables.get(category); final String type = MetricsCategoryNameUtil.getShortNameForCategory(category); final MetricTableSpecification tableSpecification = displaySpecification.getSpecification(category); final MetricsResult results = run.getResultsForCategory(category); final MetricTableModel model = new MetricTableModel(results, type, tableSpecification); table.setModel(model); final Container tab = table.getParent().getParent(); if (model.getRowCount() == 0) { tabbedPane.remove(tab); continue; } final String longName = MetricsCategoryNameUtil.getLongNameForCategory(category); tabbedPane.add(tab, longName); final MyColumnListener columnListener = new MyColumnListener(tableSpecification, table); final TableColumnModel columnModel = table.getColumnModel(); columnModel.addColumnModelListener(columnListener); final int columnCount = columnModel.getColumnCount(); for (int i = 0; i < columnCount; i++) { final TableColumn column = columnModel.getColumn(i); column.addPropertyChangeListener(columnListener); } setRenderers(table, type); setColumnWidths(table, tableSpecification); } }
public EmptyColumns() { super(); this.tableColumns.removeAllElements(); TableColumn c = new TableColumn(); c.setHeaderValue(""); this.addColumn(c); }
public void packColumn(JTable table, int vColIndex, int margin) { DefaultTableColumnModel colModel = (DefaultTableColumnModel) table.getColumnModel(); TableColumn col = colModel.getColumn(vColIndex); int width = 0; // Get width of column header TableCellRenderer renderer = col.getHeaderRenderer(); if (renderer == null) { renderer = table.getTableHeader().getDefaultRenderer(); } Component comp = renderer.getTableCellRendererComponent(table, col.getHeaderValue(), false, false, 0, 0); width = comp.getPreferredSize().width; // Get maximum width of column data for (int r = 0; r < table.getRowCount(); r++) { renderer = table.getCellRenderer(r, vColIndex); comp = renderer.getTableCellRendererComponent( table, table.getValueAt(r, vColIndex), false, false, r, vColIndex); width = Math.max(width, comp.getPreferredSize().width); } // Add margin width += 2 * margin; // Set the width col.setPreferredWidth(width); }
private void formWindowOpened( java.awt.event.WindowEvent evt) { // GEN-FIRST:event_formWindowOpened // TODO add your handling code here: jTable1.setAutoResizeMode(jTable1.AUTO_RESIZE_OFF); TableColumn columna4 = jTable1.getColumn("Descripción"); columna4.setPreferredWidth(350); TableColumn columna2 = jTable1.getColumn("Tipo de Postgrado"); columna2.setPreferredWidth(250); jTable1.addMouseListener( new MouseAdapter() { public void mouseClicked(MouseEvent e) { CursoPControl g = new CursoPControl(); jTable1.setRowSelectionInterval( jTable1.rowAtPoint(e.getPoint()), jTable1.rowAtPoint(e.getPoint())); CursoPostgrado usu1 = cursoPostgradoList.get(jTable1.rowAtPoint(e.getPoint())); // CursoPostgrado usu = em.find(CursoPostgrado.class, usu1.getIdPostgrado()); CursoPostgrado usu = g.buscarCursoPId(usu1.getIdPostgrado()); jTextField1.setText(usu.getTipoPostgrado()); jTextArea1.setText(usu.getDescripcionPostgrado()); } }); } // GEN-LAST:event_formWindowOpened
@Override public Rectangle getCellRect(int row, int column, boolean includeSpacing) { Rectangle cellFrame; TableColumn aColumn; cellFrame = new Rectangle(); cellFrame.height = getRowHeight(row) + rowMargin; cellFrame.y = 0; for (int i = 0; i < row; i++) { cellFrame.y += getRowHeight(i) + rowMargin; } int index = 0; int columnMargin = getColumnModel().getColumnMargin(); Enumeration enumeration = getColumnModel().getColumns(); while (enumeration.hasMoreElements()) { aColumn = (TableColumn) enumeration.nextElement(); cellFrame.width = aColumn.getWidth() + columnMargin; if (index == column) { break; } cellFrame.x += cellFrame.width; index++; } if (!(includeSpacing)) { Dimension spacing = getIntercellSpacing(); cellFrame.setBounds( cellFrame.x + spacing.width / 2, cellFrame.y + spacing.height / 2, cellFrame.width - spacing.width, cellFrame.height - spacing.height); } return cellFrame; }
private void jButtonConsultarActionPerformed( java.awt.event.ActionEvent evt) { // GEN-FIRST:event_jButtonConsultarActionPerformed // <editor-fold defaultstate="collapsed" desc="jButtonConsultarActionPerformed()"> String busqueda; try { busqueda = jTFCodigo1.getText(); } catch (NullPointerException e) { busqueda = ""; } Object libros[][] = controladorLibro.consultarLibros(busqueda); TableModel myModel = new javax.swing.table.DefaultTableModel( libros, new String[] {"Identificacion", "Titulo", "Subtitulo"}) { boolean[] canEdit = new boolean[] {false, false, false}; public boolean isCellEditable(int rowIndex, int columnIndex) { return canEdit[columnIndex]; } }; jTableResultados.setModel(myModel); jTableResultados.setRowSorter(new TableRowSorter(myModel)); // Setting the colum width TableColumn column = null; for (int i = 0; i < 3; i++) { column = jTableResultados.getColumnModel().getColumn(i); if (i == 1 || i == 2) { column.setPreferredWidth(300); } else { column.setPreferredWidth(110); } } // </editor-fold> } // GEN-LAST:event_jButtonConsultarActionPerformed
private void recargarFecha(ArrayList<Vencimientos> list) { Object[][] dato = new Object[list.size()][4]; int f = 0; for (Vencimientos a : list) { dato[f][0] = a.getCodigo(); dato[f][1] = a.getDescripcion(); dato[f][2] = a.getCantidadminima(); dato[f][3] = a.getCantidad(); f++; } tablaAgotados.setModel( new javax.swing.table.DefaultTableModel( dato, new String[] {"Codigo", "Descripcion", "Cantidad Minima", "Cantidad Bodega"}) { @Override public boolean isCellEditable(int row, int column) { return false; } }); TableColumn columna1 = tablaAgotados.getColumn("Codigo"); columna1.setPreferredWidth(4); TableColumn columna2 = tablaAgotados.getColumn("Descripcion"); columna2.setPreferredWidth(200); }
public void init(TableColumn column) { DateCellRenderer cellRenderer = new DateCellRenderer(getRaplaLocale()); cellRenderer.setSubstractDayWhenFullDay(true); column.setCellRenderer(cellRenderer); column.setMaxWidth(175); column.setPreferredWidth(175); }
public Component getTableCellRendererComponent( JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) { setOpaque(true); setFont(plainFont); // setBorder(new EmptyBorder(10, 10, 10, 6)); if (isSelected) { setForeground(table.getSelectionForeground()); setBackground(table.getSelectionBackground()); } else { setForeground(table.getForeground()); setBackground(table.getBackground()); } if (table.getModel() instanceof FeedTableModel) { FeedTableModel rsstm = (FeedTableModel) table.getModel(); TableColumn col = table.getColumnModel().getColumn(column); if (!rsstm.isItemAtRowRead(row)) setFont(boldFont); if (col.getHeaderValue() == FeedTableModel.READ) { if (rsstm.isItemAtRowRead(row)) setIcon(readItemIcon); else setIcon(unreadItemIcon); } else setIcon(null); } else if (table.getModel() instanceof WeblogTableModel) { WeblogTableModel btm = (WeblogTableModel) table.getModel(); if (column == 0) { // is the modified column on the TableModel null? if (btm.getValueAt(row, WeblogTableModel.MODIFIED_COL) == null) setIcon(postIcon); else setIcon(uPostIcon); } else setIcon(null); } if (value instanceof FeedItem) { setText(((FeedItem) value).getTitle()); return this; } else if (value instanceof Boolean) { setText(""); setHorizontalAlignment(SwingConstants.CENTER); return this; } else if (value instanceof Integer) { Integer val = (Integer) value; setHorizontalAlignment(SwingConstants.CENTER); setText(val.intValue() + ""); return this; } else if (value instanceof Date) { Date d = (Date) value; setText(df.format(d)); if ((table.getModel() instanceof WeblogTableModel) && (column == WeblogTableModel.DATE_COL)) { if (expireDate != null && d.before(expireDate)) setForeground(Color.red); } return this; } setHorizontalAlignment(SwingConstants.LEFT); // setToolTipText(value.toString()); if (value == null) setText(""); else setText(value.toString()); return this; }
public TableCellRenderFrame() { setSize(DEFAULT_WIDTH, DEFAULT_HEIGHT); TableModel model = new PlanetTableModel(); JTable table = new JTable(model); table.setRowSelectionAllowed(false); // set up renderers and editors table.setDefaultRenderer(Color.class, new ColorTableCellRenderer()); table.setDefaultEditor(Color.class, new ColorTableCellEditor()); JComboBox<Integer> moonCombo = new JComboBox<>(); for (int i = 0; i <= 20; i++) moonCombo.addItem(i); TableColumnModel columnModel = table.getColumnModel(); TableColumn moonColumn = columnModel.getColumn(PlanetTableModel.MOONS_COLUMN); moonColumn.setCellEditor(new DefaultCellEditor(moonCombo)); moonColumn.setHeaderRenderer(table.getDefaultRenderer(ImageIcon.class)); moonColumn.setHeaderValue(new ImageIcon(getClass().getResource("Moons.gif"))); // show table table.setRowHeight(100); add(new JScrollPane(table), BorderLayout.CENTER); }
private void packColumn(JTable table, int vColIndex, int margin) { // table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF); DefaultTableColumnModel colModel = (DefaultTableColumnModel) table.getColumnModel(); TableColumn col = colModel.getColumn(vColIndex); int width = 0; // obtiene la anchura de la cabecera de la columna TableCellRenderer renderer = col.getHeaderRenderer(); if (renderer == null) { renderer = table.getTableHeader().getDefaultRenderer(); } Component comp = renderer.getTableCellRendererComponent(table, col.getHeaderValue(), false, false, 0, 0); // width = comp.getPreferredSize().width; width = 5; // Obtine la anchura maxima de la coluna de for (int r = 0; r < table.getRowCount(); r++) { renderer = table.getCellRenderer(r, vColIndex); comp = renderer.getTableCellRendererComponent( table, table.getValueAt(r, vColIndex), false, false, r, vColIndex); width = Math.max(width, 0); } width += 2 * margin; // Configura el ancho col.setPreferredWidth(width); }
private void packColumns(int inMargin) { TableModel model = this.table.getModel(); DefaultTableColumnModel columnModel = (DefaultTableColumnModel) table.getColumnModel(); for (int col = 0; col < this.table.getColumnCount(); col++) { TableColumn column = columnModel.getColumn(col); int width = 0; // determine widest row in column for (int row = 0; row < this.table.getRowCount(); row++) { TableCellRenderer renderer = this.table.getCellRenderer(row, col); Component component = renderer.getTableCellRendererComponent( this.table, this.table.getValueAt(row, col), false, false, row, col); width = Math.max(width, component.getPreferredSize().width); } // add the margin width += 2 * inMargin; column.setPreferredWidth(width); } }
public static void pack(JTable table) { if (!table.isShowing() || table.getColumnCount() == 0) return; int width[] = new int[table.getColumnCount()]; int total = 0; for (int col = 0; col < width.length; col++) { width[col] = preferredWidth(table, col); total += width[col]; } int extra = table.getVisibleRect().width - total; if (extra > 0) { int bonus = extra / table.getColumnCount(); for (int i = 0; i < width.length; i++) { width[i] += bonus; } extra -= bonus * table.getColumnCount(); width[width.length - 1] += extra; } TableColumnModel columnModel = table.getColumnModel(); for (int col = 0; col < width.length; col++) { TableColumn tableColumn = columnModel.getColumn(col); table.getTableHeader().setResizingColumn(tableColumn); tableColumn.setWidth(width[col]); } }
private int getHeaderHeight() { if ((header == null) || (header.getTable() == null)) { return 0; } int height = 0; boolean accomodatedDefault = false; TableColumnModel columnModel = header.getColumnModel(); for (int column = 0; column < columnModel.getColumnCount(); column++) { TableColumn aColumn = columnModel.getColumn(column); boolean isDefault = (aColumn.getHeaderRenderer() == null); if (!isDefault || !accomodatedDefault) { Component comp = getHeaderRenderer(column); int rendererHeight = comp.getPreferredSize().height; height = Math.max(height, rendererHeight); // Configuring the header renderer to calculate its preferred size // is expensive. Optimise this by assuming the default renderer // always has the same height as the first non-zero height that // it returns for a non-null/non-empty value. if (isDefault && rendererHeight > 0) { Object headerValue = aColumn.getHeaderValue(); if (headerValue != null) { headerValue = headerValue.toString(); if (headerValue != null && !headerValue.equals("")) { accomodatedDefault = true; } } } } } return height + 2; }
/** * Calculates the optimal width for the header of the given table. The calculation is based on the * preferred width of the header renderer. * * @param table the table to calculate the column width * @param col the column to calculate the widths * @return the width, -1 if error */ public static int calcHeaderWidth(JTable table, int col) { if (table == null) return -1; if (col < 0 || col > table.getColumnCount()) { System.out.println("invalid col " + col); return -1; } JTableHeader header = table.getTableHeader(); TableCellRenderer defaultHeaderRenderer = null; if (header != null) defaultHeaderRenderer = header.getDefaultRenderer(); TableColumnModel columns = table.getColumnModel(); TableModel data = table.getModel(); TableColumn column = columns.getColumn(col); int width = -1; TableCellRenderer h = column.getHeaderRenderer(); if (h == null) h = defaultHeaderRenderer; if (h != null) { // Not explicitly impossible Component c = h.getTableCellRendererComponent(table, column.getHeaderValue(), false, false, -1, col); width = c.getPreferredSize().width + 5; } return width; }
/** * auto fit table columns width * * @version 1.0 * @author dinglinhui */ public void FitTableColumns(JTable myTable) { JTableHeader header = myTable.getTableHeader(); int rowCount = myTable.getRowCount(); Enumeration columns = myTable.getColumnModel().getColumns(); while (columns.hasMoreElements()) { TableColumn column = (TableColumn) columns.nextElement(); int col = header.getColumnModel().getColumnIndex(column.getIdentifier()); int width = (int) myTable .getTableHeader() .getDefaultRenderer() .getTableCellRendererComponent( myTable, column.getIdentifier(), false, false, -1, col) .getPreferredSize() .getWidth(); for (int row = 0; row < rowCount; row++) { int preferedWidth = (int) myTable .getCellRenderer(row, col) .getTableCellRendererComponent( myTable, myTable.getValueAt(row, col), false, false, row, col) .getPreferredSize() .getWidth(); width = Math.max(width, preferedWidth); } header.setResizingColumn(column); // 此行很重要 column.setWidth(width + myTable.getIntercellSpacing().width); } }
/** Creates a new instance of AbstractDatatypeTableColummModel */ public AbstractDatatypeTableColummModel() { super(); for (int i = 0; i < COLHEADS.length; ++i) { TableColumn col = new TableColumn(i, COLHEADWIDTHS[i]); col.setHeaderValue(COLHEADS[i]); col.setMinWidth(COLHEADWIDTHS[i]); addColumn(col); } this.setColumnSelectionAllowed(false); // this.addColumnModelListener( new TableColumnModelListener() { // public void columnSelectionChanged(ListSelectionEvent e) { } // public void columnMarginChanged(ChangeEvent e) { // System.out.println("COLUMN WIDTH : "+ // getColumn(0).getWidth()+" "+ // getColumn(1).getWidth()+" "+ // getColumn(2).getWidth()+" "+ // getColumn(3).getWidth()+" "+ // getColumn(4).getWidth()); // } // public void columnRemoved(TableColumnModelEvent e) { } // public void columnAdded(TableColumnModelEvent e) { } // public void columnMoved(TableColumnModelEvent e) { } // }); }
public LeagueTable() { model = new DefaultTableModel(); model.setColumnIdentifiers( new String[] { "Team Name", "Points", "Goal Diff", "Wins", "Draws", "Loses", "Played", "League Verdict" }); table = new JTable(model) { @Override public boolean isCellEditable(int row, int column) { return false; } }; JScrollPane pane = new JScrollPane( table, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED); pane.setPreferredSize(INITIAL_SIZE); setVisible(true); setLayout(new FlowLayout()); TableColumn colVerdict = table.getColumnModel().getColumn(7); colVerdict.setPreferredWidth(290); add(pane); }