List of usage examples for javax.swing.table TableModel getColumnCount
public int getColumnCount();
From source file:mekhq.Utilities.java
/** * Export a JTable to a CSV file//from w w w. j av a2 s.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.qspin.qtaste.ui.xmleditor.TestRequirementEditor.java
private void computeColumnWidths() { // horizontal spacing int hspace = 6; TableModel model = m_TestRequirementTable.getModel(); // rows no/*from w ww . j a v a 2 s .c o m*/ int cols = model.getColumnCount(); // columns no int rows = model.getRowCount(); // width vector int w[] = new int[model.getColumnCount()]; // computes headers widths for (int i = 0; i < cols; i++) { w[i] = (int) m_TestRequirementTable .getDefaultRenderer(String.class).getTableCellRendererComponent(m_TestRequirementTable, m_TestRequirementModel.getColumnName(i), false, false, -1, i) .getPreferredSize().getWidth() + hspace; TableColumn hcol = m_TestRequirementTable.getColumn(m_TestRequirementModel.getColumnName(i)); hcol.setHeaderRenderer(new MyTableHeaderRenderer()); } // check if cell values fit in their cells and if not // keep in w[i] the necessary with for (int i = 0; i < rows; i++) { for (int j = 0; j < cols; j++) { Object o = model.getValueAt(i, j); int width = 0; if (o != null) { width = (int) m_TestRequirementTable.getCellRenderer(i, j) .getTableCellRendererComponent(m_TestRequirementTable, o, false, false, i, j) .getPreferredSize().getWidth() + hspace; } if (w[j] < width) { w[j] = width; } } } TableColumnModel colModel = m_TestRequirementTable.getColumnModel(); // and finally setting the column widths for (int i = 0; i < cols; i++) { colModel.getColumn(i).setPreferredWidth(w[i]); } }
From source file:com.view.TradeWindow.java
private void TraderBlockOrdersActionPerformed(java.awt.event.ActionEvent evt) { TableModel dtm = (TableModel) TraderIncomingRequestsTable.getModel(); int nRow = dtm.getRowCount(); int nCol = dtm.getColumnCount(); Object[][] tableData = new Object[nRow][nCol]; ArrayList<SingleOrder> parsedOrders = new ArrayList(); ControllerBlockOrders control = new ControllerBlockOrders(); for (int i = 0; i < nRow; i++) { for (int j = 0; j < nCol; j++) { tableData[i][j] = dtm.getValueAt(i, j); }/*from ww w .ja v a2s. c om*/ SingleOrder o = new SingleOrder(); o.SingleOrderMakeBlocks(tableData[i]); parsedOrders.add(o); } singleOrderLists = control.MakeBlock(parsedOrders); showMessageDialog(null, "Blocks have been successfully completed."); //dtm.setRowCount(0); TraderPlatformBlockedRequests.setLayout(new BorderLayout()); int count = 1; ArrayList<JScrollPane> paneList = new ArrayList<JScrollPane>(); for (ArrayList<SingleOrder> b : singleOrderLists) { JTable jTable = new JTable(); jTable.setModel(CTraderBlockOrder.getTableModel(b)); Dimension d = jTable.getPreferredSize(); // System.out.println(d); int rows = jTable.getRowCount(); // System.out.println(rows); JScrollPane jPane = new JScrollPane(); jPane.setPreferredSize(new Dimension(d.width, jTable.getRowHeight() * rows + 50)); jPane.add(jTable); jPane.setViewportView(jTable); paneList.add(jPane); count++; } test.add(blockOptions); int i = 0; for (final JScrollPane j : paneList) { // JButton btn = new JButton(); // btn.setText("Split Block"); // btn.setName(""+i); JPanel cPanel = new JPanel(); /* btn.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { JViewport viewport = j.getViewport(); final JTable mytable = (JTable)viewport.getView(); final ArrayList<Integer> index = new ArrayList<Integer>(); for(int row = 0;row<mytable.getRowCount();row++){ if((boolean)mytable.getValueAt(row, 11)){ index.add(row); } } SplitBlockActionPerformed(evt,index,cPanel,test); } });*/ JCheckBox check = new JCheckBox(); JLabel label = new JLabel(); label.setText("Select Block"); check.setName("" + i); check.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { SelectBlockActionPerformed(evt); } }); JPanel splitOptions = new JPanel(); splitOptions.add(label); splitOptions.add(check); splitOptions.setName("splitOpt"); // splitOptions.add(btn); cPanel.setName("cPanel" + i); cPanel.add(splitOptions); cPanel.add(j); cPanel.setLayout(new BoxLayout(cPanel, BoxLayout.Y_AXIS)); test.add(cPanel); cPanelList.add(cPanel); i++; } test.setLayout(new BoxLayout(test, BoxLayout.Y_AXIS)); JScrollPane p = new JScrollPane(test); p.setName("ParentP"); TraderPlatformBlockedRequests.add(p); TraderPlatformBlockedRequests.validate(); TraderPlatformTabbedPane.setSelectedIndex(TraderPlatformTabbedPane.getSelectedIndex() + 1); }
From source file:maltcms.ui.fileHandles.csv.CSVTableView.java
/** * * @param tm//www . ja va 2 s . co m */ public void setTableModel(TableModel tm) { if (tm == null) { Logger.getLogger(this.getClass().getName()).log(Level.WARNING, "Received table model was null!"); return; } this.jTable1.setModel(tm); //default column model for (int i = 0; i < tm.getColumnCount(); i++) { this.jTable1.getColumnModel().getColumn(i).setCellRenderer( new ColorColumnRenderer(new Color(255, 255, 255, 255), jTable1.getSelectedRows())); } JTableCustomizer.changeComparators(this.jTable1); JTableCustomizer.fitAllColumnWidth(this.jTable1); this.jTable1.getTableHeader().addMouseListener(new MouseAdapter() { @Override public void mouseReleased(MouseEvent e) { if (e.getButton() == 3) { activeColumn = jTable1.getTableHeader().columnAtPoint(e.getPoint()); int[] selectedRows = jTable1.getSelectedRows(); int minRow = 0;// int maxRow = jTable1.getRowCount() - 1;// int[] selectedColumns = jTable1.getSelectedColumns(); int minCol = 0; int maxCol = jTable1.getColumnCount() - 1; if (cellSelection) { jTable1.setRowSelectionAllowed(true); minRow = MathTools.min(selectedRows); maxRow = MathTools.max(selectedRows); minCol = MathTools.min(selectedColumns); maxCol = MathTools.min(selectedColumns); } else { } jTable1.setColumnSelectionInterval(activeColumn, activeColumn); jTable1.setRowSelectionInterval(minRow, maxRow); createAndShowPopupMenu(e); } } }); }
From source file:net.sourceforge.processdash.ev.ui.EVReport.java
private static void customizeTableWriter(HTMLTableWriter writer, TableModel t, String[] toolTips) { writer.setTableAttributes("border='1'"); writer.setHeaderRenderer(new HTMLTableWriter.DefaultHTMLHeaderCellRenderer(toolTips)); for (int i = t.getColumnCount(); i-- > 0;) if (t.getColumnName(i).endsWith(" ")) writer.setSkipColumn(i, true); }
From source file:userInterface.HospitalAdminRole.ManagePatientsJPanel.java
private void saveReportBtnActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_saveReportBtnActionPerformed try {// ww 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:it.cnr.icar.eric.client.ui.swing.RegistryObjectsTable.java
/** * Creates default columns for the table from * the data model using the <code>getColumnCount</code> method * defined in the <code>TableModel</code> interface. * * Clears any existing columns before creating the * new columns based on information from the model. * * Overrides base class behaviour by setting the column width as a % of the * viewport width./*from w w w .j a v a 2s . co m*/ */ public void createDefaultColumnsFromModel() { TableModel m = getModel(); if (m != null) { // Remove any current columns TableColumnModel cm = getColumnModel(); while (cm.getColumnCount() > 0) { cm.removeColumn(cm.getColumn(0)); } // get parent width int parentWidth = 0; Component parent = getParent(); if (parent != null) { parentWidth = parent.getWidth(); } // Create new columns from the data model info int columnCount = m.getColumnCount(); for (int i = 0; i < m.getColumnCount(); i++) { int width = tableModel.getColumnWidth(i); if (width == 0) { width = parentWidth / columnCount; } else { //Width is a % of the viewport width width = (width * parentWidth) / 100; } TableColumn newColumn = new TableColumn(i); newColumn.setPreferredWidth(width); addColumn(newColumn); } } }
From source file:edu.ku.brc.specify.config.init.PrintTableHelper.java
/** * @param model//from w w w . j av a 2 s . 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.specify.tasks.ReportsBaseTask.java
/** * @param model//from ww w . ja v a 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(); } } 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, true)); 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(14, fontName, true)); /*Style numberStyle = new Style(); numberStyle.setHorizontalAlign(HorizontalAlign.RIGHT); Style amountStyle = new Style(); amountStyle.setHorizontalAlign(HorizontalAlign.RIGHT); amountStyle.setBackgroundColor(Color.cyan); amountStyle.setTransparency(Transparency.OPAQUE);*/ //Font dataRowFont = new Font(10, Font._FONT_VERDANA, true); // Odd Row Style Style oddRowStyle = new Style(); //oddRowStyle.setBorder(Border.NO_BORDER); //oddRowStyle.setFont(dataRowFont); oddRowStyle.setHorizontalAlign(HorizontalAlign.CENTER); Color veryLightGrey = new Color(240, 240, 240); oddRowStyle.setBackgroundColor(veryLightGrey); oddRowStyle.setTransparency(Transparency.OPAQUE); // Event Row Style //Style evenRowStyle = new Style(); //evenRowStyle.setBorder(Border.NO_BORDER); //evenRowStyle.setFont(dataRowFont); // 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.setWidth(new Integer(100)); colBldr.setStyle(columDetailWhite); //colBldr.setHeaderStyle(columDetailWhite); AbstractColumn column = colBldr.build(); drb.addColumn(column); Style headerStyle = new Style(); headerStyle.setFont(new Font(12, 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.setTitleHeight(new Integer(30)); //drb.setSubtitleHeight(new Integer(20)); //drb.setDetailHeight(new Integer(15)); //drb.setDefaultStyles(null, null, null, evenRowStyle); 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:org.apache.metamodel.jdbc.JdbcDataContextTest.java
public void testUsingDataSource() throws Exception { Connection con = getTestDbConnection(); DataSource ds = EasyMock.createMock(DataSource.class); CloseableConnectionWrapper con1 = new CloseableConnectionWrapper(con); CloseableConnectionWrapper con2 = new CloseableConnectionWrapper(con); CloseableConnectionWrapper con3 = new CloseableConnectionWrapper(con); CloseableConnectionWrapper con4 = new CloseableConnectionWrapper(con); CloseableConnectionWrapper con5 = new CloseableConnectionWrapper(con); assertFalse(con1.isClosed());//from w w w .j a v a 2 s . c o m assertFalse(con2.isClosed()); assertFalse(con3.isClosed()); assertFalse(con4.isClosed()); assertFalse(con5.isClosed()); EasyMock.expect(ds.getConnection()).andReturn(con1); EasyMock.expect(ds.getConnection()).andReturn(con2); EasyMock.expect(ds.getConnection()).andReturn(con3); EasyMock.expect(ds.getConnection()).andReturn(con4); EasyMock.expect(ds.getConnection()).andReturn(con5); EasyMock.replay(ds); JdbcDataContext dc = new JdbcDataContext(ds); dc.refreshSchemas(); dc.refreshSchemas(); Schema schema = dc.getDefaultSchema(); Query q = new Query(); q.from(schema.getTableByName("CUSTOMERS")).select(new SelectItem("COUNT(*)", null)); DataSet data = dc.executeQuery(q); TableModel tableModel = new DataSetTableModel(data); assertEquals(1, tableModel.getRowCount()); assertEquals(1, tableModel.getColumnCount()); assertEquals(122, tableModel.getValueAt(0, 0)); EasyMock.verify(ds); String assertionFailMsg = "Expected 5x true: " + con1.isClosed() + "," + con2.isClosed() + "," + con3.isClosed() + "," + con4.isClosed() + "," + con5.isClosed(); assertTrue(assertionFailMsg, con1.isClosed()); assertTrue(assertionFailMsg, con2.isClosed()); assertTrue(assertionFailMsg, con3.isClosed()); assertTrue(assertionFailMsg, con4.isClosed()); assertTrue(assertionFailMsg, con5.isClosed()); }