void saveTableFile() { java.io.File file = tableFileChooser.getSelectedFile(); try { FileWriter fwriter = new FileWriter(file); BufferedWriter bwriter = new BufferedWriter(fwriter); for (int j = 0; j < table.getColumnCount(); j++) { String xml = ""; xml += table.getColumnName(j); bwriter.write(xml); bwriter.write('\t'); } bwriter.newLine(); for (int i = 0; i < table.getRowCount(); i++) { // xml+= "<row number = '" + i + "'>\n"; for (int j = 0; j < table.getColumnCount(); j++) { String xml = ""; xml += table.getValueAt(i, j); bwriter.write(xml); bwriter.write('\t'); } // xml += "\n"; bwriter.newLine(); } // fwriter.write(xml); // fwriter.close(); bwriter.close(); } catch (IOException ioe) { ioe.printStackTrace(); } }
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]); } }
/** * Exports the given table to the given text file. * * @param fileName Name of the file * @param table Table to export * @throws IOException Thrown if an error occurs while writing to the file. */ public void export(String fileName, JTable table) throws IOException { BufferedWriter bw = new BufferedWriter(new FileWriter(fileName)); // Export selected rows int[] rows = table.getSelectedRows(); // Export entire table if there is no selection if (rows == null || rows.length < 1) { rows = new int[table.getRowCount()]; for (int i = 0; i < rows.length; i++) { rows[i] = i; } } // Write headers for (int col = 0; col < table.getColumnCount(); col++) { bw.write(LINE_COMMENT); bw.write(table.getColumnName(col)); if (col != table.getColumnCount()) bw.write(COL_DELIMITER); } bw.write(ROW_DELIMITER); // Write table content for (int row : rows) { for (int col = 0; col < table.getColumnCount(); col++) { Object o = table.getValueAt(row, col); if (o != null) bw.write(o.toString()); if (col != table.getColumnCount()) bw.write(COL_DELIMITER); } bw.write(ROW_DELIMITER); } bw.close(); }
public void actionPerformed(ActionEvent e) { Object value = getValue(NAME); if (value == MNEMONIC) { JComponent c = (JComponent) e.getSource(); c.requestFocusInWindow(); value = getValue(MNEMONIC); if (value != null) { JComboBox combo = (JComboBox) c; combo.setSelectedItem(value); } } else if (value == EDIT) { JTable table = (JTable) e.getSource(); int row = table.getSelectionModel().getLeadSelectionIndex(); if (row < 0 || row >= table.getRowCount()) return; int col = UITableModel.VALUE_COLUMN_INDEX; table.editCellAt(row, table.convertColumnIndexToView(col)); } else if (value == SORT) { value = getValue(SORT); JTable table = (JTable) e.getSource(); for (int col = table.getColumnCount(); --col >= 0; ) { if (value.equals(table.getColumnName(col))) { table.getRowSorter().toggleSortOrder(table.convertColumnIndexToModel(col)); break; } } } else if (value == CLOSE) { SwingUtilities.getWindowAncestor((Component) e.getSource()).dispose(); } }
/** * @param table * @return an HTML formated table */ private String createHtmlTable(JTable table) { if (table.getRowCount() <= 0) return this.START_PARAPH + "NO ENTRY" + this.END_PARAPH; StringBuilder sb = new StringBuilder("<table border='2' width='100%'>"); int rows = table.getRowCount(); int cols = table.getColumnCount(); sb.append("<tr background = blue><th>"); for (int i = 0; i < cols; i++) { Object value = table.getModel().getColumnName(i); sb.append(value.toString()); if (i == cols - 1) sb.append("</th>"); else sb.append("</th><th>"); } sb.append("</th></tr>\n"); for (int i = 0; i < rows; i++) { sb.append("<tr><td>"); for (int j = 0; j < cols; j++) { Object value = table.getValueAt(i, j); if (value != null) sb.append(value.toString()); if (j == cols - 1) sb.append("</td>"); else sb.append("</td><td>"); } sb.append("</td></tr>\n"); } sb.append("</table>"); return sb.toString(); }
private void initTabla() { tblHerramientas.setRowHeight(TABLA_DEFAULT_ALTO); DefaultTableModel modelo = (DefaultTableModel) tblHerramientas.getModel(); // Ancho de Columnas int anchoColumna = 0; TableColumnModel modeloColumna = tblHerramientas.getColumnModel(); TableColumn columnaTabla; for (int i = 0; i < tblHerramientas.getColumnCount(); i++) { columnaTabla = modeloColumna.getColumn(i); switch (i) { case TABLA_HERRAMIENTAS_COLUMNA_ESTADO: anchoColumna = 100; break; case TABLA_HERRAMIENTAS_COLUMNA_NOMBRE: anchoColumna = 350; break; case TABLA_HERRAMIENTAS_COLUMNA_HORAS: anchoColumna = 50; break; } columnaTabla.setPreferredWidth(anchoColumna); columnaTabla.setWidth(anchoColumna); } }
/** Obtains the table from R and prints it out. */ private void getTable() { double[][] ddArr = new double[tabIn.getRowCount()][tabIn.getColumnCount()]; // some comment out("Obtain table from R and print it out."); // obtain values ddArr = receiveTableFromR("df01"); // set the values in the table for (int row = 0; row < tabOut.getRowCount(); ++row) { for (int col = 0; col < tabOut.getColumnCount(); ++col) { tabOut.setValueAt(String.valueOf(ddArr[row][col]), row, col); } } }
/** * 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; }
// 선택된 이미지를 보여줍니다. private void image_Show() { int row = table_ftp_view.getSelectedRow(); int col = table_ftp_view.getColumnCount(); Vector<Object> temp = new Vector<Object>(); for (int i = 0; i < col; i++) { temp.add(dtm.getValueAt(row, i)); } Image image = null; try { URL url = new URL( "http://14.38.161.45:7080/" + Server_Config.getFTPMARTPATH() + "/" + temp.get(1) + "." + temp.get(2)); System.out.println(url.toString()); image = ImageIO.read(url); label_show_image.setIcon( new ImageIcon(image.getScaledInstance(250, 250, Image.SCALE_SMOOTH))); } catch (IOException e) { e.printStackTrace(); } // l.setIcon(new ImageIcon(image.getScaledInstance(150, 150, Image.SCALE_SMOOTH))); }
private Vector<String> getColumnNames() { Vector<String> columnNames = new Vector<String>(); for (int i = 0; i < jTable1.getColumnCount(); i++) columnNames.add(jTable1.getColumnName(i)); return columnNames; }
private Component table() { String[] titles = { "Year", "Starting Balance", "Starting Principal", "Withdrawals", "Appreciation", "Deposits", "Ending Balance" }; tableModel = new DefaultTableModel(titles, 0); for (int i = 0; i < 12800; i++) { tableModel.addRow( new Integer[] {1900 + i, 10000 + i, 8000 + i, 50 + i, 905 + i, 2000 + i, 12000 + i}); } JTable table = new CustomTable(tableModel); int preferredWidth = 0; for (int i = 0; i < table.getColumnCount(); i++) { int width = packColumn(table, i, 2); preferredWidth += width; } Dimension preferredSize = new Dimension(preferredWidth, 400); table.setPreferredScrollableViewportSize(preferredSize); this.setMinimumSize(preferredSize); JScrollPane scrollPane = new JScrollPane(table); return scrollPane; }
public void actionPerformed(ActionEvent arg0) { int numero = tabla.getRowCount(); while (numero > 0) { model.removeRow(0); numero--; } Object[][] Tabla = getTabla(); Object[] fila = new Object[tabla.getColumnCount()]; for (int i = 0; i < Tabla.length; i++) { model.addRow(fila); for (int j = 0; j < tabla.getColumnCount(); j++) { model.setValueAt(Tabla[i][j], i, j); } } }
private void buildColumnRenderer() { int iColumns = table.getColumnCount(); for (int i = 0; i < iColumns; i++) { TableColumn column = table.getColumnModel().getColumn(i); column.setCellRenderer(columnRenderer); } }
private int buscarColumna(String busColumna, javax.swing.JTable tablaAbuscar) { int busCol = 0; for (int i = 0; i < tablaAbuscar.getColumnCount(); i++) { if (tablaAbuscar.getColumnName(i).equals(busColumna)) busCol = i; } return busCol; }
/** * 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); } }
/** * fills 'cTable' with the values in confMatrix * * @param confMatrix Mat - a result from TestingResult 'res' */ public void fillConfTable(double[][] confMatrix) { // initialize table header JTableHeader header = cTable.getTableHeader(); for (int i = 0; i < cTable.getColumnCount() - 1; i++) { TableColumn column1 = cTable.getTableHeader().getColumnModel().getColumn(i + 1); column1.setHeaderValue(wordClasses[i]); } System.out.println(cTable.getColumnCount()); // fill the first column with classes for (int i = 0; i < wordClasses.length; i++) { for (int j = 0; j < wordClasses.length; j++) { cTable.setValueAt(wordClasses[i], i, 0); cTable.setValueAt(confMatrix[i][j], i, j + 1); } } }
protected void addWidgets(DescriptorQueryList list, ActionMap actions, boolean captionsOnly) { setLayout(new BorderLayout()); setBorder(BorderFactory.createTitledBorder(caption)); setBackground(AmbitColors.BrightClr); setForeground(AmbitColors.DarkClr); tableModel = new DescriptorQueryTableModel(list, captionsOnly); JTable table = new JTable(tableModel, createTableColumnModel(tableModel, captionsOnly)); table.setSurrendersFocusOnKeystroke(true); table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); table.setRowSelectionAllowed(false); table.getTableHeader().setReorderingAllowed(false); table.setRowHeight(24); TableColumn col; int[] pSize = {32, 240, 32, 32, 64, 32, 32, 32}; int[] mSize = {24, 120, 32, 32, 64, 32, 32, 32}; for (int i = 0; i < table.getColumnCount(); i++) { col = table.getColumnModel().getColumn(i); col.setPreferredWidth(pSize[i]); col.setMinWidth(mSize[i]); } // table.setShowGrid(false); table.setShowHorizontalLines(true); table.setShowVerticalLines(false); scrollPane = new JScrollPane(table); scrollPane.setPreferredSize(new Dimension(420, 360)); scrollPane.setMinimumSize(new Dimension(370, 120)); scrollPane.setAutoscrolls(true); // tPane.addTab("Search descriptors",scrollPane); add(scrollPane, BorderLayout.CENTER); /* JToolBar t = new JToolBar(); //t.setBackground(Color.white); t.setFloatable(false); //t.setBorder(BorderFactory.createTitledBorder("Search by descriptors and distance between atoms")); Object[] keys = actions.allKeys(); if (keys != null) { for (int i=0; i < keys.length;i++) t.add(actions.get(keys[i])); add(t,BorderLayout.SOUTH); } */ if (actions != null) { Object[] keys = actions.allKeys(); if (keys != null) { for (int i = 0; i < keys.length; i++) { add( new DescriptorSearchActionPanel(list, actions.get(keys[i]), keys[i].toString()), BorderLayout.SOUTH); break; } } } }
/** Inits the input table. */ private void initTableIn() { double dummy = 0.0; for (int row = 0; row < tabIn.getRowCount(); ++row) { for (int col = 0; col < tabIn.getColumnCount(); ++col) { ++dummy; tabIn.setValueAt(String.valueOf(dummy), row, col); } } }
public int[] findValue(String value) { for (int i = 0; i < myTable.getColumnCount(); i++) { for (int j = 0; j < myTable.getRowCount(); j++) { if (value.compareToIgnoreCase(getValueAt(i, j)) == 0) return new int[] {i, j}; } } return new int[] {-1, -1}; }
private void Table(javax.swing.JTable tb, int lebar[]) { tb.setAutoResizeMode(JTable.AUTO_RESIZE_OFF); int kolom = tb.getColumnCount(); for (int i = 0; i < kolom; i++) { javax.swing.table.TableColumn tbc = tb.getColumnModel().getColumn(i); tbc.setPreferredWidth(lebar[i]); tb.setRowHeight(17); } }
public String[] getRowVector(int fila) { DefaultTableModel model = (DefaultTableModel) tableGrid_Perfil.getModel(); int col = tableGrid_Perfil.getColumnCount(); String result = ""; for (int i = 0; i < col; i++) { result += (i == 0 ? "" : " - ") + model.getValueAt(fila, i).toString(); } return result.split("-"); }
/** * Selects the result with the given index in the results list. * * @param index the index of the result to select */ public void setSelectedResult(int index) { if (index < 0 || index > bgResultsTable.getRowCount() - 1) { bgResultsTable.clearSelection(); } else { bgResultsTable.setRowSelectionInterval(index, index); int colCount = bgResultsTable.getColumnCount(); bgResultsTable.setColumnSelectionInterval(0, colCount - 1); } }
public void ukuran_colom(JTable name, int[] lebar) { int jumlah = name.getColumnCount(); // atau // int jumlah = name.getColumnCount()-1; name.setAutoResizeMode(name.AUTO_RESIZE_OFF); for (int a = 0; a < jumlah; a++) { TableColumn column = name.getColumnModel().getColumn(a); column.setPreferredWidth(lebar[a]); } }
@Override public void mouseClicked(MouseEvent e) { int column = table.getColumnModel().getColumnIndexAtX(e.getX()); int row = e.getY() / table.getRowHeight(); if (row < table.getRowCount() && row >= 0 && column < table.getColumnCount() && column >= 0) { Object value = table.getValueAt(row, column); if (value != null && value instanceof JButton) ((JButton) value).doClick(); } }
/** Puts the input table into a data.frame in R. */ private void setTable() { double[][] ddArr = new double[tabIn.getRowCount()][tabIn.getColumnCount()]; // some comment out("Read table and send it to R."); // put values from table in an array for (int row = 0; row < tabIn.getRowCount(); ++row) { for (int col = 0; col < tabIn.getColumnCount(); ++col) { try { ddArr[row][col] = Double.parseDouble(String.valueOf(tabIn.getValueAt(row, col))); } catch (NumberFormatException nfe) { ddArr[row][col] = 0.0; } } } // set the array in R sendTable2R(ddArr, tabIn.getColumnCount(), tabIn.getRowCount(), "df01"); }
protected TimeWindowConfigurationStorage getTableConfiguration() { TimeWindowConfigurationStorage storage = new TimeWindowConfigurationStorage(); storage.setViewFoldedNodes(mViewFoldedNodes); for (int i = 0; i < timeTable.getColumnCount(); i++) { TimeWindowColumnSetting setting = new TimeWindowColumnSetting(); setting.setColumnWidth(timeTable.getColumnModel().getColumn(i).getWidth()); setting.setColumnSorting(sorter.getSortingStatus(i)); storage.addTimeWindowColumnSetting(setting); } return storage; }
/** * CONSTRUCTOR This would be the ideal constructor, but there are issues with the initcomponents * in Analyster so the tab must be initialized first then the table can be added * * @param table */ public Tab(JTable table) { tableName = ""; this.table = table; totalRecords = 0; recordsShown = 0; filter = new TableFilter(table); ColumnPopupMenu = new ColumnPopupMenu(filter); // store the column names for the table for (int i = 0; i < table.getColumnCount(); i++) tableColNames[i] = table.getColumnName(i); }
/** * This method is activated on the Keystrokes we are listening to in this implementation. Here it * listens for Copy and Paste ActionCommands. Selections comprising non-adjacent cells result in * invalid selection and then copy action cannot be performed. Paste is done by aligning the upper * left corner of the selection with the 1st element in the current selection of the JTable. */ public void actionPerformed(ActionEvent e) { if (e.getActionCommand().compareTo("Copy") == 0) { StringBuffer sbf = new StringBuffer(); // Check to ensure we have selected only a contiguous block of // cells int numcols = jTable1.getSelectedColumnCount(); int numrows = jTable1.getSelectedRowCount(); int[] rowsselected = jTable1.getSelectedRows(); int[] colsselected = jTable1.getSelectedColumns(); if (!((numrows - 1 == rowsselected[rowsselected.length - 1] - rowsselected[0] && numrows == rowsselected.length) && (numcols - 1 == colsselected[colsselected.length - 1] - colsselected[0] && numcols == colsselected.length))) { JOptionPane.showMessageDialog( null, "Invalid Copy Selection", "Invalid Copy Selection", JOptionPane.ERROR_MESSAGE); return; } for (int i = 0; i < numrows; i++) { for (int j = 0; j < numcols; j++) { sbf.append(jTable1.getValueAt(rowsselected[i], colsselected[j])); if (j < numcols - 1) sbf.append("\t"); } sbf.append("\n"); } stsel = new StringSelection(sbf.toString()); system = Toolkit.getDefaultToolkit().getSystemClipboard(); system.setContents(stsel, stsel); } if (e.getActionCommand().compareTo("Paste") == 0) { System.out.println("Trying to Paste"); int startRow = (jTable1.getSelectedRows())[0]; int startCol = (jTable1.getSelectedColumns())[0]; try { String trstring = (String) (system.getContents(this).getTransferData(DataFlavor.stringFlavor)); System.out.println("String is:" + trstring); StringTokenizer st1 = new StringTokenizer(trstring, "\n"); for (int i = 0; st1.hasMoreTokens(); i++) { rowstring = st1.nextToken(); StringTokenizer st2 = new StringTokenizer(rowstring, "\t"); for (int j = 0; st2.hasMoreTokens(); j++) { value = (String) st2.nextToken(); if (startRow + i < jTable1.getRowCount() && startCol + j < jTable1.getColumnCount()) jTable1.setValueAt(value, startRow + i, startCol + j); System.out.println( "Putting " + value + "at row = " + startRow + i + "column = " + startCol + j); } } } catch (Exception ex) { ex.printStackTrace(); } } }
private int setupColumnWidths() { // Column widths. String[] columnVariables = tickerTableModel.getColumnVariables(); int tickerWidth = HORIZONTAL_DELTA; if (tickerTableModel.getRowCount() > 1) { // There may be a scroll bar so give it some space. tickerWidth += SCROLLBAR_WIDTH; } int numberOfColumns = Math.min(table.getColumnCount(), columnVariables.length); for (int i = 0; i < numberOfColumns; i++) { // work out width int columnWidth; if (TickerTableModel.TICKER_COLUMN_CURRENCY.equals(columnVariables[i])) { columnWidth = PER_COLUMN_HORIZONTAL_DELTA + Math.max( Math.max( fontMetrics.stringWidth( controller .getLocaliser() .getString("tickerTableModel." + columnVariables[i])), fontMetrics.stringWidth((String) tickerTableModel.getValueAt(0, i))), fontMetrics.stringWidth((String) tickerTableModel.getValueAt(1, i))); } else if (TickerTableModel.TICKER_COLUMN_EXCHANGE.equals(columnVariables[i])) { columnWidth = PER_COLUMN_HORIZONTAL_DELTA + Math.max( Math.max( fontMetrics.stringWidth( controller .getLocaliser() .getString("tickerTableModel." + columnVariables[i])), fontMetrics.stringWidth((String) tickerTableModel.getValueAt(0, i))), fontMetrics.stringWidth((String) tickerTableModel.getValueAt(1, i))); } else { columnWidth = PER_COLUMN_HORIZONTAL_DELTA + Math.max( fontMetrics.stringWidth( controller .getLocaliser() .getString("tickerTableModel." + columnVariables[i])), fontMetrics.stringWidth("000000.00000")); } tickerWidth += columnWidth; table.getColumnModel().getColumn(i).setPreferredWidth(columnWidth); } return tickerWidth; }
private void paintVerticalGridLines(Graphics g) { // paint the column grid dividers for the non-existent rows. int x = 0; for (int i = 0; i < fTable.getColumnCount(); i++) { TableColumn column = fTable.getColumnModel().getColumn(i); // increase the x position by the width of the current column. x += column.getWidth(); g.setColor(TABLE_GRID_COLOR); // draw the grid line (not sure what the -1 is for, but BasicTableUI // also does it. g.drawLine(x - 1, g.getClipBounds().y, x - 1, getHeight()); } }