List of usage examples for javax.swing JTable setAutoResizeMode
@BeanProperty(enumerationValues = { "JTable.AUTO_RESIZE_OFF", "JTable.AUTO_RESIZE_NEXT_COLUMN", "JTable.AUTO_RESIZE_SUBSEQUENT_COLUMNS", "JTable.AUTO_RESIZE_LAST_COLUMN", "JTable.AUTO_RESIZE_ALL_COLUMNS" }, description = "Whether the columns should adjust themselves automatically.") public void setAutoResizeMode(int mode)
From source file:Visuals.PieChart.java
public JPanel addCharts() { ChartPanel piePanel = drawPieChart(); piePanel.setDomainZoomable(true);//from w w w . j a va 2 s.c om JPanel thisPiePanel = new JPanel(); String[][] finalRisks = new String[riskCount][4]; for (int i = 0; i < riskCount; i++) { finalRisks[i][0] = risks[i][0]; finalRisks[i][1] = risks[i][1]; finalRisks[i][2] = risks[i][2]; finalRisks[i][3] = risks[i][3]; } JTable table = new JTable(finalRisks, columns); //table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF); TableRowSorter<TableModel> sorter = new TableRowSorter<>(table.getModel()); table.setRowSorter(sorter); List<RowSorter.SortKey> sortKeys = new ArrayList<>(); int columnIndexToSort = 2; sortKeys.add(new RowSorter.SortKey(columnIndexToSort, SortOrder.ASCENDING)); sorter.setSortKeys(sortKeys); sorter.sort(); TableColumn tcol = table.getColumnModel().getColumn(2); table.removeColumn(tcol); table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF); table.getColumnModel().getColumn(1).setPreferredWidth(600); table.getColumnModel().getColumn(2).setPreferredWidth(600); JLabel right = new JLabel( " "); thisPiePanel.add(right, BorderLayout.EAST); table.setShowHorizontalLines(true); table.setRowHeight(40); JScrollPane tableScrollPane = new JScrollPane(table, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED); Dimension d = table.getPreferredSize(); tableScrollPane .setPreferredSize(new Dimension((d.width - 400), (table.getRowHeight() + 1) * (riskCount + 1))); table.setEnabled(false); thisPiePanel.setLayout(new BorderLayout()); if (riskCount == 0) { thisPiePanel.add(piePanel, BorderLayout.CENTER); } else { thisPiePanel.add(right, BorderLayout.EAST); thisPiePanel.add(piePanel, BorderLayout.CENTER); thisPiePanel.add(tableScrollPane, BorderLayout.SOUTH); } thisPiePanel.setBorder(BorderFactory.createLineBorder(Color.BLACK, 1)); return thisPiePanel; }
From source file:modnlp.capte.AlignmentInterfaceWS.java
public JTable autoResizeColWidth(JTable table, DefaultTableModel model) { table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF); table.setModel(model);//www . j a va2 s .c om 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 = 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); } ((DefaultTableCellRenderer) table.getTableHeader().getDefaultRenderer()) .setHorizontalAlignment(SwingConstants.LEFT); // table.setAutoCreateRowSorter(true); table.getTableHeader().setReorderingAllowed(false); return table; }
From source file:coolmap.application.widget.impl.WidgetUserGroup.java
private void init() { table.getTableHeader().setReorderingAllowed(false); table.setAutoCreateRowSorter(true);/*from w ww .j a v a2 s.co m*/ table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF); table.setDefaultRenderer(Object.class, new DefaultTableCellRenderer() { @Override public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) { JLabel label = (JLabel) super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column); if (isSelected) { return label; } if (column == 1) { try { label.setBackground( nodeColor.get(table.getModel().getValueAt(table.convertRowIndexToModel(row), 0))); } catch (Exception e) { } } else { label.setBackground(UI.colorWhite); } return label; } }); //Need a search box as well. // getContentPane().setLayout(new BorderLayout()); // getContentPane().add(new JScrollPane(table), BorderLayout.CENTER); JToolBar t = new JToolBar(); getContentPane().add(t, BorderLayout.NORTH); t.setFloatable(false); try { //also add an action to add group nodes JMenuItem item = new JMenuItem("selected row nodes"); item.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { CoolMapObject o = CoolMapMaster.getActiveCoolMapObject(); if (o == null) { return; } ArrayList<Range<Integer>> selected = o.getCoolMapView().getSelectedRows(); ArrayList<VNode> selectedNodes = new ArrayList<>(); for (Range<Integer> r : selected) { for (int i = r.lowerEndpoint(); i < r.upperEndpoint(); i++) { selectedNodes.add(o.getViewNodeRow(i)); } } createNewGroup(selectedNodes); //create a group } }); WidgetMaster.getViewport().addPopupMenuItem("Create group", item, false); item = new JMenuItem("selected column nodes"); item.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { CoolMapObject o = CoolMapMaster.getActiveCoolMapObject(); if (o == null) { return; } ArrayList<Range<Integer>> selected = o.getCoolMapView().getSelectedColumns(); ArrayList<VNode> selectedNodes = new ArrayList<>(); for (Range<Integer> r : selected) { for (int i = r.lowerEndpoint(); i < r.upperEndpoint(); i++) { selectedNodes.add(o.getViewNodeColumn(i)); } } createNewGroup(selectedNodes); } }); WidgetMaster.getViewport().addPopupMenuItem("Create group", item, false); } catch (Exception e) { // //Error handling. } }
From source file:com.vgi.mafscaling.OpenLoop.java
private void createRunTables(JPanel dataRunPanel) { GridBagConstraints gbc_run = new GridBagConstraints(); gbc_run.anchor = GridBagConstraints.PAGE_START; gbc_run.insets = new Insets(0, 2, 0, 2); for (int i = 0; i < RunCount; ++i) { runTables[i] = new JTable(); JTable table = runTables[i]; table.getTableHeader().setReorderingAllowed(false); table.setModel(new DefaultTableModel(RunRowsCount, 3)); table.setColumnSelectionAllowed(true); table.setCellSelectionEnabled(true); table.setBorder(new LineBorder(new Color(0, 0, 0))); table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF); table.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION); table.getColumnModel().getColumn(0) .setHeaderValue("<html><center>Engine<br>Speed<br>(RPM)<br></center></html>"); table.getColumnModel().getColumn(1) .setHeaderValue("<html><center>MAF<br>Sensor<br>Voltage<br></center></html>"); table.getColumnModel().getColumn(2) .setHeaderValue("<html><center>AFR<br>Error<br>%<br></center></html>"); Utils.initializeTable(table, ColumnWidth); excelAdapter.addTable(table, true, false); gbc_run.gridx = i;// ww w . j av a 2 s .com gbc_run.gridy = 0; dataRunPanel.add(table.getTableHeader(), gbc_run); gbc_run.gridy = 1; dataRunPanel.add(table, gbc_run); } }
From source file:edu.ku.brc.specify.tasks.subpane.ESResultsTablePanel.java
/** * @param table// ww w . j av a 2 s . com * @param model */ protected void autoResizeColWidth(final JTable table, final DefaultTableModel model) { table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF); table.setModel(model); int margin = 5; DefaultTableColumnModel colModel = (DefaultTableColumnModel) table.getColumnModel(); int preferredWidthTotal = 0; int renderedWidthTotal = 0; int[] colWidths = new int[table.getColumnCount()]; int[] strWidths = new int[table.getColumnCount()]; for (int i = 0; i < table.getColumnCount(); i++) { int vColIndex = i; TableColumn col = colModel.getColumn(vColIndex); int width = 0; TableCellRenderer headerRenderer = col.getHeaderRenderer(); if (headerRenderer instanceof JLabel) { ((JLabel) headerRenderer).setHorizontalAlignment(SwingConstants.CENTER); } // Get width of column header TableCellRenderer renderer = col.getCellRenderer(); 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 int strWidth = 0; boolean isString = model.getColumnClass(i) == String.class; for (int r = 0; r < table.getRowCount(); r++) { renderer = table.getCellRenderer(r, vColIndex); Object objVal = table.getValueAt(r, vColIndex); if (isString && objVal != null) { strWidth = Math.max(strWidth, ((String) objVal).length()); } comp = renderer.getTableCellRendererComponent(table, objVal, false, false, r, vColIndex); width = Math.max(width, comp.getPreferredSize().width); } // Add margin width += 2 * margin; preferredWidthTotal += col.getPreferredWidth(); colWidths[i] = width; strWidths[i] = strWidth; renderedWidthTotal += width; } if (renderedWidthTotal > preferredWidthTotal) { for (int i = 0; i < table.getColumnCount(); i++) { TableColumn col = colModel.getColumn(i); TableCellRenderer renderer = col.getCellRenderer(); if (renderer != null) { ((JLabel) renderer).setHorizontalAlignment( strWidths[i] > 20 ? SwingConstants.LEFT : SwingConstants.CENTER); //((JLabel)renderer).setHorizontalAlignment(SwingConstants.LEFT); } if (model.getColumnCount() > 3 && renderedWidthTotal > preferredWidthTotal) { col.setPreferredWidth(colWidths[i]); } } } ((DefaultTableCellRenderer) table.getTableHeader().getDefaultRenderer()) .setHorizontalAlignment(SwingConstants.LEFT); // table.setAutoCreateRowSorter(true); table.getTableHeader().setReorderingAllowed(false); }
From source file:edu.ku.brc.specify.plugins.sgr.SGRResultsDisplay.java
private JTable createTable(DefaultTableModel resultsTableModel, final List<List<Color>> rowColors) { JTable table = new JTable(resultsTableModel) { public Component prepareRenderer(TableCellRenderer renderer, int rowIndex, int colIndex) { Component c = super.prepareRenderer(renderer, rowIndex, colIndex); final Color bgColor = isCellSelected(rowIndex, colIndex) ? getSelectionBackground() : rowColors.get(rowIndex).get(colIndex); c.setBackground(bgColor);/*from ww w . j av a 2 s . com*/ return c; } }; DefaultTableCellRenderer tcr = getTableCellRenderer();//model.getRowInfoList()); for (int i = 0; i < resultsTableModel.getColumnCount(); i++) { if (resultsTableModel.getColumnClass(i) != Boolean.class) { table.setDefaultRenderer(resultsTableModel.getColumnClass(i), tcr); } } table.setCellSelectionEnabled(true); table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF); UIHelper.makeTableHeadersCentered(table, false); table.setDefaultRenderer(String.class, new BiColorTableCellRenderer(false)); table.setRowHeight(ROW_HEIGHT); autoResizeColWidth(table, resultsTableModel); return table; }
From source file:com.github.lindenb.jvarkit.tools.bamviewgui.BamFileRef.java
BamInternalFrame(BamFileRef ref) { super(ref.bamFile.getName(), true, false, true, true); this.ref = ref; JPanel mainPane = new JPanel(new BorderLayout(5, 5)); setContentPane(mainPane);//from w w w . ja v a 2s.c o m JTabbedPane tabbedPane = new JTabbedPane(); mainPane.add(tabbedPane, BorderLayout.CENTER); JPanel pane = new JPanel(new BorderLayout(5, 5)); tabbedPane.addTab("BAM", pane); this.tableModel = new BamTableModel(); this.jTable = createTable(tableModel); this.jTable.setAutoResizeMode(JTable.AUTO_RESIZE_ALL_COLUMNS); this.jTable.getSelectionModel().setSelectionMode(ListSelectionModel.SINGLE_SELECTION); JScrollPane scroll1 = new JScrollPane(this.jTable); this.infoTableModel = new FlagTableModel(); JTable tInfo = createTable(this.infoTableModel); this.genotypeTableModel = new SAMTagAndValueModel(); JTable tGen = createTable(this.genotypeTableModel); this.groupTableModel = new ReadGroupTableModel(); JTable tGrp = createTable(this.groupTableModel); JPanel splitH = new JPanel(new GridLayout(1, 0, 5, 5)); splitH.add(new JScrollPane(tInfo)); splitH.add(new JScrollPane(tGen)); splitH.add(new JScrollPane(tGrp)); JSplitPane splitVert = new JSplitPane(JSplitPane.VERTICAL_SPLIT, scroll1, splitH); this.jTable.getSelectionModel().addListSelectionListener(new ListSelectionListener() { @Override public void valueChanged(ListSelectionEvent e) { if (e.getValueIsAdjusting()) return; int row = jTable.getSelectedRow(); SAMRecord ctx; if (row == -1 || (ctx = tableModel.getElementAt(row)) == null) { infoTableModel.setContext(null); genotypeTableModel.setContext(null); groupTableModel.setContext(null); } else { infoTableModel.setContext(ctx); genotypeTableModel.setContext(ctx); groupTableModel.setContext(ctx); } } }); pane.add(splitVert); //header as text pane = new JPanel(new BorderLayout(5, 5)); tabbedPane.addTab("Header", pane); JTextArea area = new JTextArea(String.valueOf(ref.header.getTextHeader())); area.setCaretPosition(0); area.setEditable(false); pane.add(new JScrollPane(area), BorderLayout.CENTER); //dict pane = new JPanel(new BorderLayout(5, 5)); tabbedPane.addTab("Reference", pane); JTable dictTable = createTable(new SAMSequenceDictionaryTableModel(ref.header.getSequenceDictionary())); dictTable.setAutoResizeMode(JTable.AUTO_RESIZE_OFF); pane.add(new JScrollPane(dictTable), BorderLayout.CENTER); this.selList = new ListSelectionListener() { @Override public void valueChanged(ListSelectionEvent e) { if (e.getValueIsAdjusting()) return; listSelectionChanged(); } }; this.addInternalFrameListener(new InternalFrameAdapter() { @Override public void internalFrameActivated(InternalFrameEvent e) { jTable.getSelectionModel().addListSelectionListener(selList); } @Override public void internalFrameDeactivated(InternalFrameEvent e) { jTable.getSelectionModel().removeListSelectionListener(selList); } }); }
From source file:RowHeaderTable.java
public RowHeaderTable() { super("Row Header Test"); setSize(300, 200);//from w w w . ja va2 s . c o m setDefaultCloseOperation(EXIT_ON_CLOSE); TableModel tm = new AbstractTableModel() { String data[] = { "", "a", "b", "c", "d", "e" }; String headers[] = { "Row #", "Column 1", "Column 2", "Column 3", "Column 4", "Column 5" }; public int getColumnCount() { return data.length; } public int getRowCount() { return 1000; } public String getColumnName(int col) { return headers[col]; } // Synthesize some entries using the data values & the row # public Object getValueAt(int row, int col) { return data[col] + row; } }; // Create a column model for the main table. This model ignores the // first // column added, and sets a minimum width of 150 pixels for all others. TableColumnModel cm = new DefaultTableColumnModel() { boolean first = true; public void addColumn(TableColumn tc) { // Drop the first column . . . that'll be the row header if (first) { first = false; return; } tc.setMinWidth(150); // just for looks, really... super.addColumn(tc); } }; // Create a column model that will serve as our row header table. This // model picks a maximum width and only stores the first column. TableColumnModel rowHeaderModel = new DefaultTableColumnModel() { boolean first = true; public void addColumn(TableColumn tc) { if (first) { tc.setMaxWidth(tc.getPreferredWidth()); super.addColumn(tc); first = false; } // Drop the rest of the columns . . . this is the header column // only } }; JTable jt = new JTable(tm, cm); // Set up the header column and get it hooked up to everything JTable headerColumn = new JTable(tm, rowHeaderModel); jt.createDefaultColumnsFromModel(); headerColumn.createDefaultColumnsFromModel(); // Make sure that selections between the main table and the header stay // in sync (by sharing the same model) jt.setSelectionModel(headerColumn.getSelectionModel()); // Make the header column look pretty //headerColumn.setBorder(BorderFactory.createEtchedBorder()); headerColumn.setBackground(Color.lightGray); headerColumn.setColumnSelectionAllowed(false); headerColumn.setCellSelectionEnabled(false); // Put it in a viewport that we can control a bit JViewport jv = new JViewport(); jv.setView(headerColumn); jv.setPreferredSize(headerColumn.getMaximumSize()); // With out shutting off autoResizeMode, our tables won't scroll // correctly (horizontally, anyway) jt.setAutoResizeMode(JTable.AUTO_RESIZE_OFF); // We have to manually attach the row headers, but after that, the // scroll // pane keeps them in sync JScrollPane jsp = new JScrollPane(jt); jsp.setRowHeader(jv); jsp.setCorner(ScrollPaneConstants.UPPER_LEFT_CORNER, headerColumn.getTableHeader()); getContentPane().add(jsp, BorderLayout.CENTER); }
From source file:edu.ku.brc.specify.tasks.subpane.wb.DataImportDialog.java
/** * Parses the given import xls file according to the users selection and creates/updates the * Preview table, showing the user how the import options effect the way the data will be * imported into the spreadsheet./*from www . ja va 2s.com*/ * * @param table - the table to display the data * @return JTable - the table to display the data */ private JTable setXLSTableData(final JTable table) { int numRows = 0; int numCols = 0; String[] headers = {}; Vector<Vector<String>> tableDataVector = new Vector<Vector<String>>(); Vector<String> rowData = new Vector<String>(); Vector<String> headerVector = new Vector<String>(); DateWrapper scrDateFormat = AppPrefsCache.getDateWrapper("ui", "formatting", "scrdateformat"); try { log.debug("setXLSTableData - file - " + configXLS.getFile().toString()); InputStream input = new FileInputStream(configXLS.getFile()); POIFSFileSystem fs = new POIFSFileSystem(input); HSSFWorkbook workBook = new HSSFWorkbook(fs); HSSFSheet sheet = workBook.getSheetAt(0); Vector<Integer> badHeads = new Vector<Integer>(); Vector<Integer> emptyCols = new Vector<Integer>(); ((ConfigureXLS) config).checkHeadsAndCols(sheet, badHeads, emptyCols); if (badHeads.size() > 0 && doesFirstRowHaveHeaders) { if (table != null) { ((ConfigureXLS) config).showBadHeadingsMsg(badHeads, emptyCols, getTitle()); } this.doesFirstRowHaveHeaders = false; try { ignoreActions = true; this.containsHeaders.setSelected(false); } finally { ignoreActions = false; } if (table != null) { return table; } } boolean firstRow = true; //quick fix to prevent ".0" at end of catalog numbers etc NumberFormat nf = NumberFormat.getInstance(); nf.setMinimumFractionDigits(0); nf.setMaximumFractionDigits(20); nf.setGroupingUsed(false); //gets rid of commas int maxCols = 0; // Iterate over each row in the sheet Iterator<?> rows = sheet.rowIterator(); while (rows.hasNext()) { numCols = 0; rowData = new Vector<String>(); HSSFRow row = (HSSFRow) rows.next(); //log.debug(row.getLastCellNum()+" "+row.getPhysicalNumberOfCells()); int maxSize = Math.max(row.getPhysicalNumberOfCells(), row.getLastCellNum()); if (maxSize > maxCols) { maxCols = maxSize; } while (numCols < maxSize) { if (emptyCols.indexOf(new Integer(numCols)) == -1) { HSSFCell cell = row.getCell(numCols); String value = null; // if cell is blank, set value to "" if (cell == null) { value = ""; } else { int type = cell.getCellType(); switch (type) { case HSSFCell.CELL_TYPE_NUMERIC: // The best I can do at this point in the app is to guess if a // cell is a date. // Handle dates carefully while using HSSF. Excel stores all // dates as numbers, internally. // The only way to distinguish a date is by the formatting of // the cell. (If you // have ever formatted a cell containing a date in Excel, you // will know what I mean.) // Therefore, for a cell containing a date, cell.getCellType() // will return // HSSFCell.CELL_TYPE_NUMERIC. However, you can use a utility // function, // HSSFDateUtil.isCellDateFormatted(cell), to check if the cell // can be a date. // This function checks the format against a few internal // formats to decide the issue, // but by its very nature it is prone to false negatives. if (HSSFDateUtil.isCellDateFormatted(cell)) { value = scrDateFormat.getSimpleDateFormat().format(cell.getDateCellValue()); //value = scrDateFormat.getSimpleDateFormat().format(cell.getDateCellValue()); } else { double numeric = cell.getNumericCellValue(); value = nf.format(numeric); } break; case HSSFCell.CELL_TYPE_STRING: value = cell.getRichStringCellValue().getString(); break; case HSSFCell.CELL_TYPE_BLANK: value = ""; break; case HSSFCell.CELL_TYPE_BOOLEAN: value = Boolean.toString(cell.getBooleanCellValue()); break; case HSSFCell.CELL_TYPE_FORMULA: value = UIRegistry.getResourceString("WB_FORMULA_IMPORT_NO_PREVIEW"); break; default: value = ""; log.error("unsuported cell type"); break; } } if (firstRow && doesFirstRowHaveHeaders) { checkUserColInfo(value, numCols); } if (isUserCol(numCols)) { rowData.add(value.toString()); } } numCols++; } if (doesFirstRowHaveHeaders && firstRow) { headerVector = rowData; headers = new String[rowData.size()]; } else if (!doesFirstRowHaveHeaders && firstRow) { //headers = createDummyHeaders(rowData.size()); tableDataVector.add(rowData); } else { tableDataVector.add(rowData); } firstRow = false; numRows++; } maxCols -= emptyCols.size(); if (!doesFirstRowHaveHeaders) { headerVector = createDummyHeadersAsVector(maxCols); headers = new String[maxCols]; } for (int i = 0; i < headerVector.size(); i++) { headers[i] = headerVector.elementAt(i); } printArray(headers); String[][] tableData = new String[tableDataVector.size()][maxCols]; for (int i = 0; i < tableDataVector.size(); i++) { Vector<String> v = tableDataVector.get(i); for (int j = 0; j < v.size(); j++) { tableData[i][j] = v.get(j).toString(); } } if (checkForErrors(headers, tableData)) { errorPanel.showDataImportStatusPanel(true); } else { errorPanel.showDataImportStatusPanel(false); } if ((doesFirstRowHaveHeaders ? numRows - 1 : numRows) > WorkbenchTask.MAX_ROWS) { hasTooManyRows = true; showTooManyRowsErrorDialog(); } else { hasTooManyRows = false; } log.debug(headers); log.debug(tableData); model = new PreviewTableModel(headers, tableData); JTable result = null; if (table == null) { result = new JTable(); result.setColumnSelectionAllowed(false); result.setRowSelectionAllowed(false); result.setCellSelectionEnabled(false); result.getTableHeader().setReorderingAllowed(false); result.setPreferredScrollableViewportSize(new Dimension(500, 100)); result.setAutoResizeMode(JTable.AUTO_RESIZE_OFF); } else { result = table; } result.setModel(model); result.setDefaultRenderer(String.class, new BiColorTableCellRenderer(false)); model.fireTableDataChanged(); model.fireTableStructureChanged(); return result; } catch (Exception ex) { UIRegistry.displayErrorDlgLocalized(UIRegistry.getResourceString("WB_ERROR_READING_IMPORT_FILE")); if (table != null) { String[] columnNames = {}; String[][] blankData = { {} }; model = new PreviewTableModel(columnNames, blankData); table.setModel(model); table.setColumnSelectionAllowed(false); table.setRowSelectionAllowed(false); table.setCellSelectionEnabled(false); table.getTableHeader().setReorderingAllowed(false); table.setPreferredScrollableViewportSize(new Dimension(500, 100)); table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF); table.setDefaultRenderer(String.class, new BiColorTableCellRenderer(false)); model.fireTableDataChanged(); model.fireTableStructureChanged(); return table; } //log.error("Error attempting to parse input xls file:" + ex); //ex.printStackTrace(); } return null; }
From source file:edu.ku.brc.ui.UIHelper.java
/** * @param table//from w ww . j a va 2 s .c o m * @param model * @return */ public static JTable autoResizeColWidth(final JTable table, final DefaultTableModel model) { table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF); table.setModel(model); int margin = 5; DefaultTableColumnModel colModel = (DefaultTableColumnModel) table.getColumnModel(); int preferredWidthTotal = 0; int renderedWidthTotal = 0; int[] colWidths = new int[table.getColumnCount()]; for (int i = 0; i < table.getColumnCount(); i++) { int vColIndex = i; 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; preferredWidthTotal += col.getPreferredWidth(); colWidths[i] = width; renderedWidthTotal += width; } if (renderedWidthTotal > preferredWidthTotal) { for (int i = 0; i < table.getColumnCount(); i++) { colModel.getColumn(i).setPreferredWidth(colWidths[i]); } } ((DefaultTableCellRenderer) table.getTableHeader().getDefaultRenderer()) .setHorizontalAlignment(SwingConstants.LEFT); // table.setAutoCreateRowSorter(true); table.getTableHeader().setReorderingAllowed(false); return table; }