List of usage examples for javax.swing.table TableModel getRowCount
public int getRowCount();
From source file:uk.ac.lkl.cram.ui.report.Report.java
private void addTutorSupportHours() { MainDocumentPart mdp = wordMLPackage.getMainDocumentPart(); mdp.addStyledParagraphOfText("Heading2", "Tutor Support Hours"); Tbl table = factory.createTbl();/* w w w . j a v a2 s .co m*/ Tr tableHead = factory.createTr(); TableModel tableModel = new TutorHoursTableModel(module); addTableCell(tableHead, tableModel.getColumnName(0), JcEnumeration.CENTER, true); for (int col = 4; col < 7; col++) { addTableCell(tableHead, tableModel.getColumnName(col), JcEnumeration.CENTER, true); } table.getContent().add(tableHead); for (int row = 0; row < tableModel.getRowCount(); row++) { boolean lastRow = row == tableModel.getRowCount() - 1; Tr tableRow = factory.createTr(); if (lastRow) { addTableCell(tableRow, tableModel.getValueAt(row, 0).toString(), JcEnumeration.LEFT, true); } else { addSimpleTableCell(tableRow, tableModel.getValueAt(row, 0).toString()); } for (int col = 4; col < 7; col++) { addTableCell(tableRow, FLOAT_FORMATTER.format(tableModel.getValueAt(row, col)), JcEnumeration.RIGHT, lastRow); } table.getContent().add(tableRow); } addBorders(table); mdp.addObject(table); float[] tutor_hours_online = new float[3]; float[] tutor_hours_f2f = new float[3]; List<ModulePresentation> modulePresentations = module.getModulePresentations(); for (int i = 0; i < modulePresentations.size(); i++) { ModulePresentation mp = modulePresentations.get(i); for (TLALineItem tLALineItem : module.getTLALineItems()) { SupportTime st = tLALineItem.getSupportTime(mp); float tutor_hours = st.getTotalHours(module, mp, tLALineItem); StudentTeacherInteraction sti = tLALineItem.getActivity().getStudentTeacherInteraction(); if (sti.isOnline()) { tutor_hours_online[i] += tutor_hours; } if (sti.isTutorSupported() && sti.isLocationSpecific()) { tutor_hours_f2f[i] += tutor_hours; } } } mdp.addParagraphOfText(""); table = factory.createTbl(); tableHead = factory.createTr(); addSimpleTableCell(tableHead, ""); table.getContent().add(tableHead); for (int col = 4; col < 7; col++) { addTableCell(tableHead, tableModel.getColumnName(col), JcEnumeration.CENTER, true); } Tr tableRow = factory.createTr(); addSimpleTableCell(tableRow, "Tutor hours online"); for (int i = 0; i < tutor_hours_online.length; i++) { addTableCell(tableRow, INTEGER_FORMATTER.format(tutor_hours_online[i]), JcEnumeration.RIGHT, false); } table.getContent().add(tableRow); tableRow = factory.createTr(); addSimpleTableCell(tableRow, "Tutor hours face-to-face"); for (int i = 0; i < tutor_hours_f2f.length; i++) { addTableCell(tableRow, INTEGER_FORMATTER.format(tutor_hours_f2f[i]), JcEnumeration.RIGHT, false); } table.getContent().add(tableRow); addBorders(table); mdp.addObject(table); }
From source file:mekhq.Utilities.java
/** * Export a JTable to a CSV file//from w ww. ja v a 2s. c om * @param table * @param file * @return report */ public static String exportTabletoCSV(JTable table, File file) { String report; try { TableModel model = table.getModel(); BufferedWriter writer = Files.newBufferedWriter(Paths.get(file.getPath())); String[] columns = new String[model.getColumnCount()]; for (int i = 0; i < model.getColumnCount(); i++) { columns[i] = model.getColumnName(i); } CSVPrinter csvPrinter = new CSVPrinter(writer, CSVFormat.DEFAULT.withHeader(columns)); for (int i = 0; i < model.getRowCount(); i++) { Object[] towrite = new String[model.getColumnCount()]; for (int j = 0; j < model.getColumnCount(); j++) { // use regex to remove any HTML tags towrite[j] = model.getValueAt(i, j).toString().replaceAll("\\<[^>]*>", ""); } csvPrinter.printRecord(towrite); } csvPrinter.flush(); csvPrinter.close(); report = model.getRowCount() + " " + resourceMap.getString("RowsWritten.text"); } catch (Exception ioe) { MekHQ.getLogger().log(Utilities.class, "exportTabletoCSV", LogLevel.INFO, "Error exporting JTable"); report = "Error exporting JTable. See log for details."; } return report; }
From source file:com.perl5.lang.htmlmason.idea.configuration.HTMLMasonSettingsConfigurable.java
protected void createCustomTagsComponent(FormBuilder builder) { myTagNameColumnInfo myTagNameColumnInfo = new myTagNameColumnInfo(); customTagsModel = new ListTableModel<HTMLMasonCustomTag>(myTagNameColumnInfo, new myTagRoleColumInfo()); myTagNameColumnInfo.setCustomTagsModel(customTagsModel); customTagsTable = new JBTable(customTagsModel); final TableColumn secondColumn = customTagsTable.getColumnModel().getColumn(1); ComboBoxTableRenderer<HTMLMasonCustomTagRole> roleComboBoxTableRenderer = new ComboBoxTableRenderer<HTMLMasonCustomTagRole>( HTMLMasonCustomTagRole.values()) { @Override//from w w w . j a v a2 s.c o m protected String getTextFor(@NotNull HTMLMasonCustomTagRole value) { return value.getTitle(); } @Override public boolean isCellEditable(EventObject event) { if (event instanceof MouseEvent) { return ((MouseEvent) event).getClickCount() >= 1; } return true; } }; secondColumn.setCellRenderer(roleComboBoxTableRenderer); secondColumn.setCellEditor(roleComboBoxTableRenderer); builder.addLabeledComponent(new JLabel("Custom tags that mimics built-in HTML::Mason tags:"), ToolbarDecorator.createDecorator(customTagsTable).setAddAction(new AnActionButtonRunnable() { @Override public void run(AnActionButton anActionButton) { final TableCellEditor cellEditor = customTagsTable.getCellEditor(); if (cellEditor != null) { cellEditor.stopCellEditing(); } final TableModel model = customTagsTable.getModel(); int indexToEdit = -1; for (HTMLMasonCustomTag entry : customTagsModel.getItems()) { if (StringUtil.isEmpty(entry.getText())) { indexToEdit = customTagsModel.indexOf(entry); break; } } if (indexToEdit == -1) { customTagsModel.addRow(new HTMLMasonCustomTag( "customTag" + customTagsModel.getItems().size(), HTMLMasonCustomTagRole.PERL)); indexToEdit = model.getRowCount() - 1; } TableUtil.editCellAt(customTagsTable, indexToEdit, 0); } }).disableDownAction().disableUpAction() .setPreferredSize(JBUI.size(0, PerlConfigurationUtil.WIDGET_HEIGHT)).createPanel()); }
From source file:gtu._work.mvn.MavenRepositoryUI.java
List<File> fetchPomDependencyTableJarList() { TableModel model = pomDenpendencyTable.getModel(); PomFile pomFile = null;//from ww w. j a v a2 s .c om List<File> list = new ArrayList<File>(); for (int ii = 0; ii < model.getRowCount(); ii++) { pomFile = (PomFile) model.getValueAt(ii, 3); if (pomFile != null && pomFile.jarFile != null && !list.contains(pomFile.jarFile)) { list.add(pomFile.jarFile); } } Collections.sort(list); return list; }
From source file:userInterface.HospitalAdminRole.ManagePatientsJPanel.java
private void saveReportBtnActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_saveReportBtnActionPerformed try {/*from w w w .ja v a2 s. c o m*/ HSSFWorkbook fWorkbook = new HSSFWorkbook(); HSSFSheet fSheet = fWorkbook.createSheet("new Sheet"); HSSFFont sheetTitleFont = fWorkbook.createFont(); File file = new File("C:\\Users\\Reshmi\\OneDrive\\Documents\\reports.xls"); HSSFCellStyle cellStyle = fWorkbook.createCellStyle(); sheetTitleFont.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD); //sheetTitleFont.setColor(); TableModel model = vitalSignjTable.getModel(); TableColumnModel tcm = vitalSignjTable.getColumnModel(); HSSFRow fRow1 = fSheet.createRow((short) 0); for (int j = 0; j < tcm.getColumnCount(); j++) { HSSFCell cell = fRow1.createCell((short) j); cell.setCellValue(tcm.getColumn(j).getHeaderValue().toString()); } for (int i = 0; i < model.getRowCount(); i++) { HSSFRow fRow = fSheet.createRow((short) i + 1); for (int j = 0; j < model.getColumnCount(); j++) { HSSFCell cell = fRow.createCell((short) j); cell.setCellValue(tcm.getColumn(j).getHeaderValue().toString()); cell.setCellValue(model.getValueAt(i, j).toString()); cell.setCellStyle(cellStyle); } } FileOutputStream fileOutputStream; fileOutputStream = new FileOutputStream(file); BufferedOutputStream bos = new BufferedOutputStream(fileOutputStream); fWorkbook.write(bos); bos.close(); fileOutputStream.close(); JOptionPane.showMessageDialog(null, "File saved as reports.xls ", "Export", JOptionPane.INFORMATION_MESSAGE); // Runtime run = Runtime.getRuntime(); // run.exec("cmd.exetart " + file); } catch (Exception e) { JOptionPane.showMessageDialog(null, "File not saved", "Export", JOptionPane.INFORMATION_MESSAGE); } }
From source file:org.jas.gui.MainWindow.java
private int getRow(Metadata metadataTarget) { TableModel model = getDescriptionTable().getModel(); List<Metadata> metadataList = viewEngineConfigurator.getViewEngine().get(Model.METADATA); for (int i = 0; i < model.getRowCount(); i++) { String artist = (String) model.getValueAt(i, 0); String title = (String) model.getValueAt(i, 1); if (artist.equals(metadataTarget.getArtist()) && title.equals(metadataTarget.getTitle())) { return i; }//from w w w .j av a2s.c om } return 0; }
From source file:fll.web.FullTournamentTest.java
/** * Simulate entering subjective scores by pulling them out of testDataConn. * //from ww w. j av a2s.c o m * @param testDataConn Where to get the test data from * @param challengeDocument the challenge descriptor * @throws SQLException * @throws SAXException * @throws InterruptedException */ private void enterSubjectiveScores(final Connection testDataConn, final ChallengeDescription description, final Tournament sourceTournament, final Path outputDirectory) throws SQLException, IOException, MalformedURLException, ParseException, SAXException, InterruptedException { final Path subjectiveZip = outputDirectory .resolve(sanitizeFilename(sourceTournament.getName()) + "_subjective-data.fll"); IntegrationTestUtils.downloadFile(new URL(TestUtils.URL_ROOT + "admin/subjective-data.fll"), "application/zip", subjectiveZip); final SubjectiveFrame subjective = new SubjectiveFrame(); subjective.load(subjectiveZip.toFile()); // insert scores into zip for (final ScoreCategory subjectiveElement : description.getSubjectiveCategories()) { final String category = subjectiveElement.getName(); final String title = subjectiveElement.getTitle(); // find appropriate table model final TableModel tableModel = subjective.getTableModelForTitle(title); Assert.assertNotNull(tableModel); final int teamNumberColumn = findColumnByName(tableModel, "TeamNumber"); Assert.assertTrue("Can't find TeamNumber column in subjective table model", teamNumberColumn >= 0); if (LOGGER.isTraceEnabled()) { LOGGER.trace("Found team number column at " + teamNumberColumn); } try (final PreparedStatement prep = testDataConn .prepareStatement("SELECT * FROM " + category + " WHERE Tournament = ?")) { prep.setInt(1, sourceTournament.getTournamentID()); try (final ResultSet rs = prep.executeQuery()) { while (rs.next()) { final int teamNumber = rs.getInt("TeamNumber"); // find row number in table int rowIndex = -1; for (int rowIdx = 0; rowIdx < tableModel.getRowCount(); ++rowIdx) { final Object teamNumberRaw = tableModel.getValueAt(rowIdx, teamNumberColumn); Assert.assertNotNull(teamNumberRaw); final int value = Utilities.NUMBER_FORMAT_INSTANCE.parse(teamNumberRaw.toString()) .intValue(); if (LOGGER.isTraceEnabled()) { LOGGER.trace("Checking if " + teamNumber + " equals " + value + " raw: " + teamNumberRaw + "? " + (value == teamNumber) + " rowIdx: " + rowIdx + " numRows: " + tableModel.getRowCount()); } if (value == teamNumber) { rowIndex = rowIdx; break; } } Assert.assertTrue("Can't find team " + teamNumber + " in subjective table model", rowIndex >= 0); if (rs.getBoolean("NoShow")) { // find column for no show final int columnIndex = findColumnByName(tableModel, "No Show"); Assert.assertTrue("Can't find No Show column in subjective table model", columnIndex >= 0); tableModel.setValueAt(Boolean.TRUE, rowIndex, columnIndex); } else { for (final AbstractGoal goalElement : subjectiveElement.getGoals()) { if (!goalElement.isComputed()) { final String goalName = goalElement.getName(); final String goalTitle = goalElement.getTitle(); // find column index for goal and call set final int columnIndex = findColumnByName(tableModel, goalTitle); Assert.assertTrue( "Can't find " + goalTitle + " column in subjective table model", columnIndex >= 0); final int value = rs.getInt(goalName); tableModel.setValueAt(Integer.valueOf(value), rowIndex, columnIndex); } } } // not NoShow } // foreach score } // try ResultSet } // try PreparedStatement } // foreach category subjective.save(); // upload scores IntegrationTestUtils.loadPage(selenium, TestUtils.URL_ROOT + "admin/index.jsp"); final WebElement fileInput = selenium.findElement(By.name("subjectiveFile")); fileInput.sendKeys(subjectiveZip.toAbsolutePath().toString()); selenium.findElement(By.id("uploadSubjectiveFile")).click(); Assert.assertFalse(IntegrationTestUtils.isElementPresent(selenium, By.id("error"))); Assert.assertTrue(IntegrationTestUtils.isElementPresent(selenium, By.id("success"))); }
From source file:edu.ku.brc.specify.config.init.PrintTableHelper.java
/** * @param model// w w w .j a va 2s . c o m * @return * @throws Exception */ public DynamicReport buildReport(final TableModel model, final PageSetupDlg pageSetupDlg) throws Exception { // Find a Sans Serif Font on the System String fontName = null; GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment(); for (java.awt.Font font : ge.getAllFonts()) { String fName = font.getFamily().toLowerCase(); if (StringUtils.contains(fName, "sansserif") || StringUtils.contains(fName, "arial") || StringUtils.contains(fName, "verdana")) { fontName = font.getFamily(); break; } } if (fontName == null) { fontName = Font._FONT_TIMES_NEW_ROMAN; } /** * Creates the DynamicReportBuilder and sets the basic options for the report */ FastReportBuilder drb = new FastReportBuilder(); Style columDetail = new Style(); //columDetail.setBorder(Border.THIN); Style columDetailWhite = new Style(); //columDetailWhite.setBorder(Border.THIN); columDetailWhite.setBackgroundColor(Color.WHITE); columDetailWhite.setFont(new Font(10, fontName, false)); columDetailWhite.setHorizontalAlign(HorizontalAlign.CENTER); columDetailWhite.setBlankWhenNull(true); Style columDetailWhiteBold = new Style(); //columDetailWhiteBold.setBorder(Border.THIN); columDetailWhiteBold.setBackgroundColor(Color.WHITE); Style titleStyle = new Style(); titleStyle.setFont(new Font(12, fontName, true)); // Odd Row Style Style oddRowStyle = new Style(); //oddRowStyle.setBorder(Border.NO_BORDER); oddRowStyle.setHorizontalAlign(HorizontalAlign.CENTER); Color veryLightGrey = new Color(240, 240, 240); oddRowStyle.setBackgroundColor(veryLightGrey); oddRowStyle.setTransparency(Transparency.OPAQUE); // Create Column Headers for the Report for (int i = 0; i < model.getColumnCount(); i++) { String colName = model.getColumnName(i); Class<?> dataClass = model.getColumnClass(i); if (dataClass == Object.class) { if (model.getRowCount() > 0) { Object data = model.getValueAt(0, i); if (data != null) { dataClass = data.getClass(); } else { // Column in first row was null so search down the rows // for a non-empty cell for (int j = 1; j < model.getRowCount(); j++) { data = model.getValueAt(j, i); if (dataClass != null) { dataClass = data.getClass(); break; } } if (dataClass == null) { dataClass = String.class; } } } } ColumnBuilder colBldr = ColumnBuilder.getInstance().setColumnProperty(colName, dataClass.getName()); int bracketInx = colName.indexOf('['); if (bracketInx > -1) { colName = colName.substring(0, bracketInx - 1); } colBldr.setTitle(colName); colBldr.setStyle(columDetailWhite); AbstractColumn column = colBldr.build(); drb.addColumn(column); Style headerStyle = new Style(); headerStyle.setFont(new Font(11, fontName, true)); //headerStyle.setBorder(Border.THIN); headerStyle.setHorizontalAlign(HorizontalAlign.CENTER); headerStyle.setVerticalAlign(VerticalAlign.MIDDLE); headerStyle.setBackgroundColor(new Color(80, 80, 80)); headerStyle.setTransparency(Transparency.OPAQUE); headerStyle.setTextColor(new Color(255, 255, 255)); column.setHeaderStyle(headerStyle); } drb.setTitle(pageSetupDlg.getPageTitle()); drb.setTitleStyle(titleStyle); drb.setLeftMargin(20); drb.setRightMargin(20); drb.setTopMargin(10); drb.setBottomMargin(10); drb.setPrintBackgroundOnOddRows(true); drb.setOddRowBackgroundStyle(oddRowStyle); drb.setColumnsPerPage(new Integer(1)); drb.setUseFullPageWidth(true); drb.setColumnSpace(new Integer(5)); // This next line causes an exception // Event with DynamicReport 3.0.12 and JasperReposrts 3.7.3 //drb.addAutoText(AutoText.AUTOTEXT_PAGE_X_OF_Y, AutoText.POSITION_FOOTER, AutoText.ALIGMENT_CENTER); Page[] pageSizes = new Page[] { Page.Page_Letter_Portrait(), Page.Page_Legal_Portrait(), Page.Page_A4_Portrait(), Page.Page_Letter_Landscape(), Page.Page_Legal_Landscape(), Page.Page_A4_Landscape() }; int pageSizeInx = pageSetupDlg.getPageSize() + (pageSetupDlg.isPortrait() ? 0 : 3); drb.setPageSizeAndOrientation(pageSizes[pageSizeInx]); DynamicReport dr = drb.build(); return dr; }
From source file:edu.ku.brc.ui.UIHelper.java
/** * Calculates and sets the each column to it preferred size. NOTE: This * method also sets the table height to 10 rows. * //from w w w . jav a2 s . c o m * @param table the table to fix up * @param numRowsHeight the number of rows to make the table height (or null not to set it) */ public static void calcColumnWidths(final JTable table, final Integer numRowsHeight, final Integer maxWidth) { if (table != null) { JTableHeader header = table.getTableHeader(); TableCellRenderer defaultHeaderRenderer = null; if (header != null) { defaultHeaderRenderer = header.getDefaultRenderer(); } TableColumnModel columns = table.getColumnModel(); TableModel data = table.getModel(); int margin = columns.getColumnMargin(); // only JDK1.3 int rowCount = data.getRowCount(); int totalWidth = 0; for (int i = columns.getColumnCount() - 1; i >= 0; --i) { TableColumn column = columns.getColumn(i); int columnIndex = column.getModelIndex(); 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, i); width = c.getPreferredSize().width; } for (int row = rowCount - 1; row >= 0; --row) { TableCellRenderer r = table.getCellRenderer(row, i); Component c = r.getTableCellRendererComponent(table, data.getValueAt(row, columnIndex), false, false, row, i); width = Math.max(width, c.getPreferredSize().width + 10); // adding an arbitray 10 pixels to make it look nicer if (maxWidth != null) { width = Math.min(width, maxWidth); } } if (width >= 0) { column.setPreferredWidth(width + margin); // <1.3: without margin } else { // ??? } totalWidth += column.getPreferredWidth(); } // If you like; This does not make sense for two many columns! Dimension size = table.getPreferredScrollableViewportSize(); //if (totalWidth > size.width) { if (numRowsHeight != null) { size.height = Math.min(size.height, table.getRowHeight() * numRowsHeight); } size.width = totalWidth; table.setPreferredScrollableViewportSize(size); } } }
From source file:com.osparking.attendant.AttListForm.java
private void showAttendantDetail(int clickedRow) { TableModel attModel = usersTable.getModel(); if (attModel.getRowCount() == 0) { // Clear attendant detail panel as no one is selected currently. return;//from w w w . j a va 2 s . c om } Object field = null; if (formMode != FormMode.CreateMode) { // <editor-fold defaultstate="collapsed" desc="-- Display ID and E-mail, initialize password"> userIDText.setText(attModel.getValueAt(clickedRow, 0).toString()); changeFieldButtonUsability(clickedRow); field = attModel.getValueAt(clickedRow, 5); if (field == null) { emailAddrText.setText(""); } else { emailAddrText.setText(field.toString()); emailAddrText.setCaretPosition(0); } changePWCheckBox.setSelected(false); ChangeNewPasswordEnabled(false); userPassword.setText(""); creationDateText.setText(attModel.getValueAt(clickedRow, 6).toString()); // </editor-fold> } userNameText.setText(attModel.getValueAt(clickedRow, 1).toString()); String adminAuthority = attModel.getValueAt(clickedRow, 2).toString(); managerCheckBox.setSelected(adminAuthority.equals("Y")); // <editor-fold defaultstate="collapsed" desc="-- 2 Display or copy phone number"> field = attModel.getValueAt(clickedRow, 3); if (field == null) { cellPhoneText.setText(""); } else { cellPhoneText.setText(field.toString()); } field = attModel.getValueAt(clickedRow, 4); if (field == null) { phoneText.setText(""); } else { phoneText.setText(field.toString()); } // </editor-fold> if (isManager) { userPassword.setToolTipText(PW_INPUT_TOOTLTIP.getContent()); userPWLabel.setToolTipText((PW_INPUT_TOOTLTIP.getContent())); } }