/** * auto fit table columns width * * @version 1.0 * @author dinglinhui */ public void FitTableColumns(JTable myTable) { JTableHeader header = myTable.getTableHeader(); int rowCount = myTable.getRowCount(); Enumeration columns = myTable.getColumnModel().getColumns(); while (columns.hasMoreElements()) { TableColumn column = (TableColumn) columns.nextElement(); int col = header.getColumnModel().getColumnIndex(column.getIdentifier()); int width = (int) myTable .getTableHeader() .getDefaultRenderer() .getTableCellRendererComponent( myTable, column.getIdentifier(), false, false, -1, col) .getPreferredSize() .getWidth(); for (int row = 0; row < rowCount; row++) { int preferedWidth = (int) myTable .getCellRenderer(row, col) .getTableCellRendererComponent( myTable, myTable.getValueAt(row, col), false, false, row, col) .getPreferredSize() .getWidth(); width = Math.max(width, preferedWidth); } header.setResizingColumn(column); // 此行很重要 column.setWidth(width + myTable.getIntercellSpacing().width); } }
private static int preferredWidth(JTable table, int col) { TableColumn tableColumn = table.getColumnModel().getColumn(col); int width = (int) table .getTableHeader() .getDefaultRenderer() .getTableCellRendererComponent( table, tableColumn.getIdentifier(), false, false, -1, col) .getPreferredSize() .getWidth(); if (table.getRowCount() != 0) { int from = 0, to = 0; Rectangle rect = table.getVisibleRect(); from = table.rowAtPoint(rect.getLocation()); to = table.rowAtPoint(new Point((int) rect.getMaxX(), (int) rect.getMaxY())) + 1; for (int row = from; row < to; row++) { int preferedWidth = (int) table .getCellRenderer(row, col) .getTableCellRendererComponent( table, table.getValueAt(row, col), false, false, row, col) .getPreferredSize() .getWidth(); width = Math.max(width, preferedWidth); } } return width + table.getIntercellSpacing().width; }
// 表格列根据内容调整大小 public static void adjustTableColumnWidths(JTable table) { JTableHeader header = table.getTableHeader(); // 表头 int rowCount = table.getRowCount(); // 表格的行数 TableColumnModel cm = table.getColumnModel(); // 表格的列模型 for (int i = 0; i < cm.getColumnCount(); i++) { // 循环处理每一列 TableColumn column = cm.getColumn(i); // 第i个列对象 int width = (int) header .getDefaultRenderer() .getTableCellRendererComponent(table, column.getIdentifier(), false, false, -1, i) .getPreferredSize() .getWidth(); // 用表头的绘制器计算第i列表头的宽度 for (int row = 0; row < rowCount; row++) { // 循环处理第i列的每一行,用单元格绘制器计算第i列第row行的单元格度 int preferedWidth = (int) table .getCellRenderer(row, i) .getTableCellRendererComponent( table, table.getValueAt(row, i), false, false, row, i) .getPreferredSize() .getWidth(); width = Math.max(width, preferedWidth); // 取最大的宽度 } column.setPreferredWidth(width + table.getIntercellSpacing().width); // 设置第i列的首选宽度 } table.doLayout(); // 按照刚才设置的宽度重新布局各个列 }
// 设置每列的宽 private void setTableColumn(JTable table) { DefaultTableColumnModel model = (DefaultTableColumnModel) table.getColumnModel(); for (int i = 0; i < table.getColumnCount(); i++) { // 得到列对象 TableColumn column = model.getColumn(i); // 得到列名 String columnName = (String) column.getIdentifier(); // 设置最小宽度 int width = columnName.length() * 10; // 设置列宽最小为150 int prefectWidth = (width < 150) ? 150 : width; column.setMinWidth(prefectWidth); } }
public void mouseClicked(MouseEvent paramMouseEvent) { if (this.hrr.getColumnModel() == null) { return; } int i = cif.a(this.hrs).getColumnIndexAtX(paramMouseEvent.getX()); TableColumn localTableColumn = cif.a(this.hrs).getColumn(i); if (localTableColumn == null) { return; } bJl localbJl = bJl.aL(localTableColumn.getIdentifier()); if (localbJl == null) { return; } cif.b(this.hrs).a(localbJl); }
/** @return true if replace operation can proceed. */ protected boolean canReplace() { TableColumn sortedColumn = table.getSortedColumn(); if (sortedColumn != null) { if (isSearchSelection()) { int[] selCols = table.getSelectedColumns(); int sortCol = table.getColumnModel().getColumnIndex(sortedColumn.getIdentifier()); for (int c = 0; c < selCols.length; c++) { if (selCols[c] == sortCol) { return false; } } } else { return false; } } return true; }
/** * Returns the position of the first column whose identifier equals <code>identifier</code>. * Position is the the index in all visible columns if <code>onlyVisible</code> is true or else * the index in all columns. * * @param identifier the identifier object to search for * @param onlyVisible if set searches only visible columns * @return the index of the first column whose identifier equals <code>identifier</code> * @exception IllegalArgumentException if <code>identifier</code> is <code>null</code>, or if no * <code>TableColumn</code> has this <code>identifier</code> * @see #getColumn */ public int getColumnIndex(Object identifier, boolean onlyVisible) { if (identifier == null) { throw new IllegalArgumentException("Identifier is null"); } Vector columns = (onlyVisible ? tableColumns : allTableColumns); int noColumns = columns.size(); TableColumn column; for (int columnIndex = 0; columnIndex < noColumns; ++columnIndex) { column = (TableColumn) columns.get(columnIndex); if (identifier.equals(column.getIdentifier())) return columnIndex; } throw new IllegalArgumentException("Identifier not found"); }
/** * Returns the index of the first column in the <code>tableColumns</code> array whose identifier * is equal to <code>identifier</code>, when compared using <code>equals</code>. * * @param identifier the identifier object * @return the index of the first column in the <code>tableColumns</code> array whose identifier * is equal to <code>identifier</code> * @exception IllegalArgumentException if <code>identifier</code> is <code>null</code>, or if no * <code>TableColumn</code> has this <code>identifier</code> * @see #getColumn */ public int getColumnIndex(Object identifier) { if (identifier == null) { throw new IllegalArgumentException("Identifier is null"); } Enumeration enumeration = getColumns(); TableColumn aColumn; int index = 0; while (enumeration.hasMoreElements()) { aColumn = (TableColumn) enumeration.nextElement(); // Compare them this way in case the column's identifier is null. if (identifier.equals(aColumn.getIdentifier())) return index; index++; } throw new IllegalArgumentException("Identifier not found"); }
public static void main(String args[]) { final Object rowData[][] = { {"1", "one", "I"}, {"2", "two", "II"}, {"3", "three", "III"} }; final String columnNames[] = {"#", "English", "Roman"}; final JTable table = new JTable(rowData, columnNames); JScrollPane scrollPane = new JScrollPane(table); JFrame frame = new JFrame("Resizing Table"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.add(scrollPane, BorderLayout.CENTER); TableColumn tc = null; for (int i = 0; i < 3; i++) { tc = table.getColumnModel().getColumn(i); if (tc.getModelIndex() == 0) tc.setResizable(false); if (i == 2) { tc.setPreferredWidth(100); // sport column is bigger } else { tc.setPreferredWidth(50); } System.out.printf( "column [%s] header=[%s] modelIndex=[%d] resizable=[%b] minWidth=[%s] maxWidth=[%d] preferredWidth=[%d]\n", tc.getIdentifier(), tc.getHeaderValue(), tc.getModelIndex(), tc.getResizable(), tc.getMinWidth(), tc.getMaxWidth(), tc.getPreferredWidth()); } frame.setSize(300, 150); frame.setVisible(true); }
public static void resizeColumnToFit( PRManFrame frame, TableView view, TableColumn tc, JTable table) { int cIdx = table.getColumnModel().getColumnIndex(tc.getIdentifier()); int width = tc.getWidth(); for (int iCnt = 0; iCnt < table.getRowCount(); iCnt++) { if (view == null || !frame.isDescriptionResourceRow(view.tableModel.getModelRowForIndex(iCnt))) { Component comp = table .getCellRenderer(iCnt, cIdx) .getTableCellRendererComponent( table, table.getValueAt(iCnt, cIdx), true, false, iCnt, cIdx); comp.invalidate(); comp.validate(); int cpw = comp.getPreferredSize().width; width = Math.max(width, cpw); } } tc.setPreferredWidth(width); }
/** Creates new form jAltaBeneficiario */ public jListadoBeneficiarios() { initComponents(); ArrayList<Beneficiario> usuarios = Gestor_de_beneficiarios.obtenerBeneficiarios(); // Para establecer el modelo al JTable DefaultTableModel modelo = new DefaultTableModel(); jTable1.setModel(modelo); // Creamos columnas modelo.addColumn("NIF"); modelo.addColumn("Nombre"); modelo.addColumn("Apellidos"); modelo.addColumn("Fecha Nacimiento"); modelo.addColumn("Nacionalidad"); modelo.addColumn("Estado Civil"); modelo.addColumn("Domicilio"); modelo.addColumn("Localidad"); modelo.addColumn("Telefono"); modelo.addColumn("Email"); modelo.addColumn("Fecha inscripcion"); modelo.addColumn("Expediente"); modelo.addColumn("Profesion"); Object[] fila = new Object[13]; /*Obtenemos todas las filas*/ for (int i = 0; i < usuarios.size(); i++) { fila[0] = usuarios.get(i).obtenerNIFCIF(); fila[1] = usuarios.get(i).obtenerNombre(); fila[2] = usuarios.get(i).obtenerApellidos(); // fila[3] = usuarios.get(i).FechaNac; fila[4] = usuarios.get(i).obtenerNacionalidad(); fila[5] = usuarios.get(i).obtenerEstadoCivil(); fila[6] = usuarios.get(i).obtenerDomicilio(); fila[7] = usuarios.get(i).obtenerLocalidad(); fila[8] = usuarios.get(i).obtenerTelefono(); fila[9] = usuarios.get(i).obtenerEmail(); // fila[10] = usuarios.get(i).Fecha_Inscripcion; fila[11] = usuarios.get(i).obtenerExpediente(); fila[12] = usuarios.get(i).obtenerProfesion(); // El elemento jTable no permite mostrar datos del tipo Date, por ello, antes de mostrar el // dato // se comprueba si es de tipo Date, y si es asi, se pasa a string para mostrarlo en la tabla. // Primero se lee el tipo Date, y despues con las dos ultimas instrucciones se transforma a // String if (usuarios.get(i).obtenerFechaNac() != null) { java.util.Date date = (java.util.Date) usuarios.get(i).obtenerFechaNac(); // primero leo el objeto fecha java.text.SimpleDateFormat sdf = new java.text.SimpleDateFormat("dd/MM/yyyy"); fila[3] = (String) sdf.format(date); } else { fila[3] = ""; } if (usuarios.get(i).obtenerFechaInscripcion() != null) { java.util.Date date = (java.util.Date) usuarios.get(i).obtenerFechaInscripcion(); // primero leo el objeto fecha java.text.SimpleDateFormat sdf = new java.text.SimpleDateFormat("dd/MM/yyyy"); fila[10] = (String) sdf.format(date); } else { fila[10] = ""; } /*Añadimos la fila*/ modelo.addRow(fila); } /*Adjustamos el tamaño de las columnas*/ int numColumnas = fila.length; for (int columna = 0; columna < numColumnas; columna++) { TableColumn tableColumn = jTable1.getColumnModel().getColumn(columna); int maxWidth = (int) jTable1 .getTableHeader() .getDefaultRenderer() .getTableCellRendererComponent( jTable1, tableColumn.getIdentifier(), false, false, -1, columna) .getPreferredSize() .getWidth(); /*Buscamos la mayor longitud entre los campos*/ for (int i = 0; i < usuarios.size(); i++) { Object cellValue = jTable1.getValueAt(i, columna); if (cellValue != null) maxWidth = Math.max( jTable1 .getCellRenderer(i, columna) .getTableCellRendererComponent( jTable1, cellValue, false, false, i, columna) .getPreferredSize() .width + jTable1.getIntercellSpacing().width, maxWidth); } maxWidth++; jTable1.getColumnModel().getColumn(columna).setWidth(maxWidth); jTable1.getColumnModel().getColumn(columna).setMaxWidth(maxWidth); } }
/** * Returns a html representation of the construction protocol. * * @param imgBase64 : image file to be included */ public String getHTML(String imgBase64) { StringBuilder sb = new StringBuilder(); boolean icon_column; // Let's be W3C compliant: sb.append("<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\"\n"); sb.append("\"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\">\n"); sb.append("<html xmlns=\"http://www.w3.org/1999/xhtml\" lang=\"en\" xml:lang=\"en\">"); sb.append("<head>\n"); sb.append("<title>"); sb.append(StringUtil.toHTMLString(GeoGebraConstants.APPLICATION_NAME)); sb.append(" - "); sb.append(app.getPlain("ConstructionProtocol")); sb.append("</title>\n"); sb.append("<meta keywords = \""); sb.append(StringUtil.toHTMLString(GeoGebraConstants.APPLICATION_NAME)); sb.append(" export\">"); sb.append( "<style type=\"text/css\"><!--body { font-family:Arial,Helvetica,sans-serif; margin-left:40px }--></style>"); sb.append("<meta http-equiv=\"content-type\" content=\"text/html; charset=utf-8\">"); sb.append("</head>\n"); sb.append("<body>\n"); // header with title Construction cons = kernel.getConstruction(); String title = cons.getTitle(); if (!title.equals("")) { sb.append("<h1>"); sb.append(StringUtil.toHTMLString(title)); sb.append("</h1>\n"); } // header with author and date String author = cons.getAuthor(); String date = cons.getDate(); String line = null; if (!author.equals("")) { line = author; } if (!date.equals("")) { if (line == null) line = date; else line = line + " - " + date; } if (line != null) { sb.append("<h3>"); sb.append(StringUtil.toHTMLString(line)); sb.append("</h3>\n"); } // include image file if (imgBase64 != null) { sb.append("<p>\n"); sb.append("<img src=\"data:image/png;base64,"); sb.append(imgBase64); sb.append("\" alt=\""); sb.append(StringUtil.toHTMLString(GeoGebraConstants.APPLICATION_NAME)); sb.append(' '); sb.append(StringUtil.toHTMLString(app.getPlain("DrawingPad"))); sb.append("\" border=\"1\">\n"); sb.append("</p>\n"); } // table sb.append("<table border=\"1\">\n"); // table headers sb.append("<tr>\n"); TableColumnModel colModel = table.getColumnModel(); int nColumns = colModel.getColumnCount(); for (int nCol = 0; nCol < nColumns; nCol++) { // toolbar icon will only be inserted on request icon_column = table.getColumnName(nCol).equals("ToolbarIcon"); if ((icon_column && addIcons) || !icon_column) { TableColumn tk = colModel.getColumn(nCol); title = (String) tk.getIdentifier(); sb.append("<th>"); sb.append(StringUtil.toHTMLString(title)); sb.append("</th>\n"); } } sb.append("</tr>\n"); // table rows int endRow = table.getRowCount(); for (int nRow = 0; nRow < endRow; nRow++) { sb.append("<tr valign=\"baseline\">\n"); for (int nCol = 0; nCol < nColumns; nCol++) { // toolbar icon will only be inserted on request icon_column = table.getColumnName(nCol).equals("ToolbarIcon"); if ((icon_column && addIcons) || !icon_column) { int col = table.getColumnModel().getColumn(nCol).getModelIndex(); String str = StringUtil.toHTMLString( ((ConstructionTableData) data).getPlainHTMLAt(nRow, col), false); sb.append("<td>"); if (str.equals("")) sb.append(" "); // space else { Color color = ((ConstructionTableData) data).getColorAt(nRow, col); if (color != Color.black) { sb.append("<span style=\"color:#"); sb.append(StringUtil.toHexString(new org.geogebra.desktop.awt.GColorD(color))); sb.append("\">"); sb.append(str); sb.append("</span>"); } else sb.append(str); } sb.append("</td>\n"); } } sb.append("</tr>\n"); } sb.append("</table>\n"); // footer sb.append(((GuiManagerD) app.getGuiManager()).getCreatedWithHTML(false)); // append base64 string so that file can be reloaded with File -> Open sb.append( "\n<!-- Base64 string so that this file can be opened in GeoGebra with File -> Open -->"); sb.append("\n<applet style=\"display:none\">"); sb.append("\n<param name=\"ggbBase64\" value=\""); appendBase64((AppD) app, sb); sb.append("\">\n<applet>"); sb.append("\n</body>"); sb.append("\n</html>"); return sb.toString(); }
public void init() { try { UIManager.setLookAndFeel("com.sun.java.swing.plaf.nimbus.NimbusLookAndFeel"); } catch (ClassNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (InstantiationException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IllegalAccessException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (UnsupportedLookAndFeelException e) { // TODO Auto-generated catch block e.printStackTrace(); } Window window = SwingUtilities.windowForComponent(this); if (window instanceof JFrame) { JFrame frame = (JFrame) window; if (!frame.isResizable()) frame.setResizable(true); } try { Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver"); String connectionUrl = "jdbc:sqlserver://130.208.252.230:1433;databaseName=PROD_UPG_DATA;user=limsadmin;password=starlims;"; con = DriverManager.getConnection(connectionUrl); List<Proj> folders = getProjects(); model = createModel(folders); } catch (ClassNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } table.setAutoCreateRowSorter(true); if (model != null) table.setModel(model); Set<TableColumn> remcol = new HashSet<TableColumn>(); Enumeration<TableColumn> taben = table.getColumnModel().getColumns(); while (taben.hasMoreElements()) { TableColumn tc = taben.nextElement(); if (tc.getIdentifier().toString().startsWith("_")) { remcol.add(tc); } } for (TableColumn tc : remcol) { table.removeColumn(tc); } table .getSelectionModel() .addListSelectionListener( new ListSelectionListener() { @Override public void valueChanged(ListSelectionEvent e) { if (currentSelection != null) { Proj project = orderMap.get(currentSelection); if (project != null) { project._OrderComment = textarea.getText(); project._ResultComment = rtextarea.getText(); } } int r = table.getSelectedRow(); if (r != -1) { currentSelection = (String) table.getValueAt(r, 0); r = table.convertRowIndexToModel(r); String t = (String) model.getValueAt(r, 1); if (t != null) textarea.setText(t); else { textarea.setText(""); } t = (String) model.getValueAt(r, 2); if (t != null) rtextarea.setText(t); else { rtextarea.setText(""); } } } }); scrollpane.setViewportView(table); scrollarea.setViewportView(textarea); rscrollarea.setViewportView(rtextarea); vista.setAction( new AbstractAction("Vista") { private static final long serialVersionUID = 1L; @Override public void actionPerformed(ActionEvent e) { try { Proj project = orderMap.get(currentSelection); if (project != null) save(project, rtextarea.getText(), textarea.getText()); } catch (SQLException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } } }); for (String s : fset) { combo.addItem(s); } combo.addItemListener( new ItemListener() { @Override public void itemStateChanged(ItemEvent e) { String s = (String) combo.getSelectedItem(); TableRowSorter<TableModel> trs = (TableRowSorter<TableModel>) table.getRowSorter(); String filterText = "(?i).*" + s + ".*"; trs.setRowFilter(RowFilter.regexFilter(filterText)); } }); JComponent comp = new JComponent() {}; comp.setLayout(new BorderLayout()); comp.add(scrollarea); comp.add(vista, BorderLayout.SOUTH); JComponent comp2 = new JComponent() {}; comp2.setLayout(new BorderLayout()); comp2.add(scrollpane); comp2.add(combo, BorderLayout.NORTH); rsplitpane.setTopComponent(rscrollarea); rsplitpane.setBottomComponent(comp); splitpane.setLeftComponent(comp2); splitpane.setRightComponent(rsplitpane); splitpane.setDividerLocation(0.33); this.add(splitpane); }
/** * Descripción de Método * * @param aPanel * @param mTab * @param table * @return */ private int setupVTable(APanel aPanel, MTab mTab, VTable table) { if (!mTab.isDisplayed()) { return 0; } int size = mTab.getFieldCount(); for (int i = 0; i < size; i++) { TableColumn tc = getTableColumn(table, i); MField mField = mTab.getField(i); // if (mField.getColumnName().equals(tc.getIdentifier().toString())) { if (mField.getDisplayType() == DisplayType.RowID) { tc.setCellRenderer(new VRowIDRenderer(false)); tc.setCellEditor(new VRowIDEditor(false)); tc.setHeaderValue(""); tc.setMaxWidth(2); } else { // need to set CellEditor explicitly as default editor based on class causes problem // (YesNo-> Boolean) if (mField.isDisplayed() && mField.isDisplayedInGrid()) { tc.setCellRenderer(new VCellRenderer(mField)); VCellEditor ce = new VCellEditor(mField, this); tc.setCellEditor(ce); // tc.setHeaderValue(mField.getHeader()); // tc.setPreferredWidth( Math.min( mField.getDisplayLength(),30 )); original, Modificado // por ConSerTi tc.setPreferredWidth(mField.getDisplayLength()); tc.setMinWidth(1); tc.setHeaderRenderer(new VHeaderRenderer(mField.getDisplayType())); // Enable Button actions in grid if (mField.getDisplayType() == DisplayType.Button) { VEditor button = ce.getEditor(); if ((button != null) && (aPanel != null)) { ((JButton) button).addActionListener(aPanel); } } } else // column not displayed { tc.setHeaderValue(null); tc.setMinWidth(0); tc.setMaxWidth(0); tc.setPreferredWidth(0); } } // System.out.println ("TableColumnID " + tc.getIdentifier () // + " Renderer=" + tc.getCellRenderer () // + mField.getHeader ()); // Modificado Por ConSerTi, para permitir campos de longuitud menor de 30 tc.setMinWidth(10); } // found field else { log.log( Level.SEVERE, "TableColumn " + tc.getIdentifier() + " <> MField " + mField.getColumnName() + mField.getHeader()); } } // for all fields table.createSortRenderers(); return size; } // setupVTable