List of usage examples for javax.swing JTable setRowSelectionAllowed
@BeanProperty(visualUpdate = true, description = "If true, an entire row is selected for each selected cell.") public void setRowSelectionAllowed(boolean rowSelectionAllowed)
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 w w w. ja v a 2s.c o m * * @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.specify.tasks.subpane.wb.DataImportDialog.java
/** * Parses the given import 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. * @param table - the table to display the data * @return//from w ww .j a v a2 s.c om * JTable - the table to display the data */ private JTable setCSVTableData(final JTable table) { try { log.debug("setTableData - file - " + configCSV.getFile().toString()); CsvReader csv = new CsvReader(new FileInputStream(configCSV.getFile()), configCSV.getDelimiter(), configCSV.getCharset()); csv.setEscapeMode(configCSV.getEscapeMode()); csv.setTextQualifier(configCSV.getTextQualifier()); String[] headers = {}; Vector<String[]> tableDataVector = new Vector<String[]>(); highestColumnCount = getLargestColumnCountFromCSV(); if (configCSV.getFirstRowHasHeaders()) { csv.readHeaders(); headers = csv.getHeaders(); } int rowColumnCount = 0; while (csv.readRecord()) { //how many columns does this row of data contain rowColumnCount = csv.getColumnCount(); //create an array that contains teh row data String[] rowData = new String[csv.getColumnCount()]; for (int col = 0; col < csv.getColumnCount(); col++) { rowData[col] = csv.get(col); } //if the column count in this row of data is not as large //as the column header count, then "insert" blank string into the cells String[] newArray = padArray(highestColumnCount, rowData, false); //stick the row data into a vector because we do not know how many //rows of data there are tableDataVector.add(newArray); } if (!configCSV.getFirstRowHasHeaders() || headers == null) { //create headers with names Column1, Column2... headers = createDummyHeaders(rowColumnCount); } //if the header count is not as large as the longest column count in the data set //create dummy headers and append to end of table. headers = padArray(highestColumnCount, headers, true); log.debug("---------------------------------------------------"); printArray(headers); log.debug("---------------------------------------------------"); //pull row data out of vector and stick into an array for table model. String[][] tableData = new String[tableDataVector.size()][rowColumnCount]; for (int i = 0; i < tableData.length; i++) { tableData[i] = tableDataVector.elementAt(i); printArray(tableData[i]); } if (checkForErrors(headers, tableData)) { errorPanel.showDataImportStatusPanel(true); } else { errorPanel.showDataImportStatusPanel(false); } if ((doesFirstRowHaveHeaders ? tableDataVector.size() - 1 : tableDataVector.size()) > WorkbenchTask.MAX_ROWS) { hasTooManyRows = true; showTooManyRowsErrorDialog(); } else { hasTooManyRows = false; } model = new PreviewTableModel(headers, tableData); 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; } catch (IOException ex) { edu.ku.brc.af.core.UsageTracker.incrHandledUsageCount(); edu.ku.brc.exceptions.ExceptionTracker.getInstance().capture(DataImportDialog.class, ex); log.error("Error attempting to parse input csv file:" + ex); } return null; }
From source file:nz.govt.natlib.ndha.manualdeposit.ManualDepositPresenter.java
private void setJobQueueTableDefaults(JTable jobQueueTable, JobQueueTableModel jobQueueTableModel) { jobQueueTableModel.addTableModelListener(new JobQueueTableModelListener()); jobQueueTable.setModel(jobQueueTableModel); jobQueueTable.setSurrendersFocusOnKeystroke(true); jobQueueTable.setAutoResizeMode(JTable.AUTO_RESIZE_ALL_COLUMNS); jobQueueTable.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION); jobQueueTable.setColumnSelectionAllowed(true); jobQueueTable.setRowSelectionAllowed(true); TableRenderer renderer = new TableRenderer(); TableColumn col = jobQueueTable.getColumnModel().getColumn(0); int width = 200; col.setPreferredWidth(width);//w ww .j av a2 s . c om col.setWidth(width); col.setCellRenderer(renderer); col = jobQueueTable.getColumnModel().getColumn(1); width = 1400; col.setPreferredWidth(width); col.setWidth(width); col.setCellRenderer(renderer); }
From source file:org.isatools.isacreator.gui.formelements.SubForm.java
protected void setTableProperties(JTable table, boolean isFieldName) { Font font = (!isFieldName) ? UIHelper.VER_12_PLAIN : UIHelper.VER_12_BOLD; table.setFont(font);//from w w w . j ava2 s .c om table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF); table.setColumnSelectionAllowed(true); table.setRowSelectionAllowed(true); table.setGridColor(UIHelper.LIGHT_GREEN_COLOR); table.setShowGrid(true); }
From source file:org.isatools.isacreator.spreadsheet.Spreadsheet.java
/** * Setup the JTable with its desired characteristics *//*from www. j a v a2s . co m*/ private void setupTable() { table = new CustomTable(spreadsheetModel); table.setShowGrid(true); table.setGridColor(Color.BLACK); table.setShowVerticalLines(true); table.setShowHorizontalLines(true); table.setGridColor(UIHelper.LIGHT_GREEN_COLOR); table.setRowSelectionAllowed(true); table.setColumnSelectionAllowed(true); table.setAutoCreateColumnsFromModel(false); table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF); table.getSelectionModel().addListSelectionListener(this); table.getColumnModel().getSelectionModel().addListSelectionListener(this); table.getTableHeader().setReorderingAllowed(true); table.getColumnModel().addColumnModelListener(this); try { table.setDefaultRenderer(Class.forName("java.lang.Object"), new SpreadsheetCellRenderer()); } catch (ClassNotFoundException e) { // ignore this error } table.addMouseListener(this); table.getTableHeader().addMouseMotionListener(new MouseMotionListener() { public void mouseDragged(MouseEvent event) { } public void mouseMoved(MouseEvent event) { // display a tooltip when user hovers over a column. tooltip is derived // from the description of a field from the TableReferenceObject. JTable table = ((JTableHeader) event.getSource()).getTable(); TableColumnModel colModel = table.getColumnModel(); int colIndex = colModel.getColumnIndexAtX(event.getX()); // greater than 1 to account for the row no. being the first col if (colIndex >= 1) { TableColumn tc = colModel.getColumn(colIndex); if (tc != null) { try { table.getTableHeader().setToolTipText(getFieldDescription(tc)); } catch (Exception e) { // ignore this error } } } } }); //table.getColumnModel().addColumnModelListener(this); InputMap im = table.getInputMap(JTable.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT); KeyStroke tab = KeyStroke.getKeyStroke(KeyEvent.VK_TAB, 0); // Override the default tab behaviour // Tab to the next editable cell. When no editable cells goto next cell. final Action previousTabAction = table.getActionMap().get(im.get(tab)); Action newTabAction = new AbstractAction() { public void actionPerformed(ActionEvent e) { // maintain previous tab action procedure previousTabAction.actionPerformed(e); JTable table = (JTable) e.getSource(); int row = table.getSelectedRow(); int originalRow = row; int column = table.getSelectedColumn(); int originalColumn = column; while (!table.isCellEditable(row, column)) { previousTabAction.actionPerformed(e); row = table.getSelectedRow(); column = table.getSelectedColumn(); // Back to where we started, get out. if ((row == originalRow) && (column == originalColumn)) { break; } } if (table.editCellAt(row, column)) { table.getEditorComponent().requestFocusInWindow(); } } }; table.getActionMap().put(im.get(tab), newTabAction); TableColumnModel model = table.getColumnModel(); String previousColumnName = null; for (int columnIndex = 0; columnIndex < tableReferenceObject.getHeaders().size(); columnIndex++) { if (!model.getColumn(columnIndex).getHeaderValue().toString() .equals(TableReferenceObject.ROW_NO_TEXT)) { model.getColumn(columnIndex).setHeaderRenderer(columnRenderer); model.getColumn(columnIndex).setPreferredWidth(spreadsheetFunctions .calcColWidths(model.getColumn(columnIndex).getHeaderValue().toString())); // add appropriate cell editor for cell. spreadsheetFunctions.addCellEditor(model.getColumn(columnIndex), previousColumnName); previousColumnName = model.getColumn(columnIndex).getHeaderValue().toString(); } else { model.getColumn(columnIndex).setHeaderRenderer(new RowNumberCellRenderer()); } } JTableHeader header = table.getTableHeader(); header.setBackground(UIHelper.BG_COLOR); header.addMouseListener(new HeaderListener(header, columnRenderer)); table.addNotify(); }
From source file:org.tellervo.desktop.tridasv2.ui.ComponentViewer.java
private void setupTable() { tableModel = new ElementListTableModel(); table = new JXTable(tableModel); tableSorter = new ElementListTableSorter(tableModel, table); table.getTableHeader().addMouseListener(tableSorter); // add sorter & header renderer table.setColumnSelectionAllowed(false); table.setRowSelectionAllowed(true); // set our column widths ElementListTableModel.setupColumnWidths(table); table.setDefaultRenderer(Object.class, new ElementListCellRenderer(this, false)); table.setDefaultRenderer(Boolean.class, new BooleanCellRenderer(this, false)); // hide irrelevent columns TableColumnModelExt colmodel = (TableColumnModelExt) table.getColumnModel(); table.setColumnControlVisible(true); colmodel.getColumnExt(I18n.getText("hidden.MostRecentVersion")).setVisible(false); colmodel.getColumnExt(I18n.getText("dbbrowser.n")).setVisible(false); colmodel.getColumnExt(I18n.getText("dbbrowser.rec")).setVisible(false); colmodel.getColumnExt(I18n.getText("dbbrowser.hash")).setVisible(false); // popup menu table.addMouseListener(new PopupListener() { @Override//from www . ja v a 2 s . c om public void showPopup(MouseEvent e) { // only clicks on tables if (!(e.getSource() instanceof JTable)) return; JTable table = (JTable) e.getSource(); ElementListTableModel model = (ElementListTableModel) table.getModel(); // get the row and sanity check int row = table.rowAtPoint(e.getPoint()); if (row < 0 || row >= model.getRowCount()) return; // select it? table.setRowSelectionInterval(row, row); // get the element Element element = model.getElementAt(row); // create and show the menu JPopupMenu popup = new ElementListPopupMenu(element, ComponentViewer.this); popup.show(table, e.getX(), e.getY()); } }); }
From source file:org.tellervo.desktop.tridasv2.ui.ComponentViewerOld.java
private void setupTable() { tableModel = new ElementListTableModel(); table = new JXTable(tableModel); tableSorter = new ElementListTableSorter(tableModel, table); table.getTableHeader().addMouseListener(tableSorter); // add sorter & header renderer table.setColumnSelectionAllowed(false); table.setRowSelectionAllowed(true); // set our column widths ElementListTableModel.setupColumnWidths(table); table.setDefaultRenderer(Object.class, new ElementListCellRenderer(this, false)); table.setDefaultRenderer(Boolean.class, new BooleanCellRenderer(this, false)); // hide irrelevent columns TableColumnModelExt colmodel = (TableColumnModelExt) table.getColumnModel(); table.setColumnControlVisible(true); colmodel.getColumnExt(I18n.getText("hidden.MostRecentVersion")).setVisible(false); colmodel.getColumnExt(I18n.getText("dbbrowser.n")).setVisible(false); colmodel.getColumnExt(I18n.getText("dbbrowser.rec")).setVisible(false); colmodel.getColumnExt(I18n.getText("dbbrowser.hash")).setVisible(false); // popup menu table.addMouseListener(new PopupListener() { @Override/* w w w.ja v a2s .c om*/ public void showPopup(MouseEvent e) { // only clicks on tables if (!(e.getSource() instanceof JTable)) return; JTable table = (JTable) e.getSource(); ElementListTableModel model = (ElementListTableModel) table.getModel(); // get the row and sanity check int row = table.rowAtPoint(e.getPoint()); if (row < 0 || row >= model.getRowCount()) return; // select it? table.setRowSelectionInterval(row, row); // get the element Element element = model.getElementAt(row); // create and show the menu JPopupMenu popup = new ElementListPopupMenu(element, ComponentViewerOld.this); popup.show(table, e.getX(), e.getY()); } }); }